pythonswaggerazure-cognitive-servicesazure-speech

Module 'swagger_client' has no attribute 'CustomSpeechTranscriptionsApi'


I'm using Microsoft's official GitHub repository to set up Azure Speech Services Batch Transcription API from Python

I receive an error from line number 142 in main.py which states

AttributeError: module 'swagger_client' has no attribute 'CustomSpeechTranscriptionsApi'

I suppose this has to do with the recent changes made to the swagger_client. How to fix this issue any thoughts?

I already followed the below threads and noticed a few others also reported the same issue but nothing helped,
Thread 1, Thread 2

To debug I gave print(dir(swagger_client)) before it throws the above error and here is the output of the print statement

['ApiClient', 'ApiSpeechtotextV30DatasetsLocalesGet200ApplicationJsonResponse', 'ApiSpeechtotextV30EndpointsLocalesGet200ApplicationJsonResponse', 'ApiSpeechtotextV30EvaluationsLocalesGet200ApplicationJsonResponse', 'ApiSpeechtotextV30ModelsLocalesGet200ApplicationJsonResponse', 'ApiSpeechtotextV30ProjectsLocalesGet200ApplicationJsonResponse', 'ApiSpeechtotextV30TranscriptionsLocalesGet200ApplicationJsonResponse', 'Component', 'Configuration', 'Dataset', 'DatasetProperties', 'DatasetUpdate', 'DefaultApi', 'Endpoint', 'EndpointLinks', 'EndpointProperties', 'EndpointPropertiesUpdate', 'EndpointUpdate', 'EntityError', 'EntityReference', 'Error', 'ErrorContent', 'ErrorDetail', 'Evaluation', 'EvaluationProperties', 'EvaluationUpdate', 'File', 'FileLinks', 'FileProperties', 'HealthStatus', 'InnerError', 'InnerErrorV2', 'InternalModel', 'Links', 'ManagementModel', 'ManagementModelArray', 'ManagementModelProperties', 'Model', 'ModelCopy', 'ModelDeprecationDates', 'ModelFile', 'ModelLinks', 'ModelManifest', 'ModelProperties', 'ModelUpdate', 'PaginatedDatasets', 'PaginatedEndpoints', 'PaginatedEvaluations', 'PaginatedFiles', 'PaginatedModels', 'PaginatedProjects', 'PaginatedTranscriptions', 'PaginatedWebHooks', 'Project', 'ProjectLinks', 'ProjectProperties', 'ProjectUpdate', 'Transcription', 'TranscriptionProperties', 'TranscriptionUpdate', 'WebHook', 'WebHookEvents', 'WebHookEvents1', 'WebHookLinks', 'WebHookProperties', 'WebHookPropertiesUpdate', 'WebHookUpdate', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'absolute_import', 'api', 'api_client', 'configuration', 'models', 'rest']

Solution

  • AttributeError: module 'swagger_client' has no attribute 'CustomSpeechTranscriptionsApi

    The above error states you have not correctly installed swagger_client.

    Make sure you have downloaded the API client library with Swagger correctly and the Python environment using pip to install the python-client module: pip install path/to/package/python-client

    I followed the same Github-document with the same code can able to get the transcription from the audio file.

    I also checked with print(dir(swagger_client) i can able to get the CustomSpeechTranscriptionsApi attribute and my version swagger_client = 1.0.0.

    enter image description here

    Code:

    def transcribe():
        logging.info("Starting transcription client...")
    
        # configure API key authorization: subscription_key
        configuration = swagger_client.Configuration()
        configuration.api_key["Ocp-Apim-Subscription-Key"] = SUBSCRIPTION_KEY
        configuration.host = f"https://{SERVICE_REGION}.api.cognitive.microsoft.com/speechtotext/v3.1"
    
        # create the client object and authenticate
        client = swagger_client.ApiClient(configuration)
    
        # create an instance of the transcription api class
        api = swagger_client.CustomSpeechTranscriptionsApi(api_client=client)
        properties = swagger_client.TranscriptionProperties()
        transcription_definition = transcribe_from_single_blob(RECORDINGS_BLOB_URI, properties)
        created_transcription, status, headers = api.transcriptions_create_with_http_info(transcription=transcription_definition)
    
        transcription_id = headers["location"].split("/")[-1]
    
        # Log information about the created transcription. If you should ask for support, please
        # include this information.
        logging.info(f"Created new transcription with id '{transcription_id}' in region {SERVICE_REGION}")
    
        logging.info("Checking status.")
    
        completed = False
    
        while not completed:
            # wait for 5 seconds before refreshing the transcription status
            time.sleep(5)
    
            transcription = api.transcriptions_get(transcription_id)
            logging.info(f"Transcriptions status: {transcription.status}")
    
            if transcription.status in ("Failed", "Succeeded"):
                completed = True
    
            if transcription.status == "Succeeded":
                pag_files = api.transcriptions_list_files(transcription_id)
                for file_data in _paginate(api, pag_files):
                    if file_data.kind != "Transcription":
                        continue
    
                    audiofilename = file_data.name
                    results_url = file_data.links.content_url
                    results = requests.get(results_url)
                    logging.info(f"Results for {audiofilename}:\n{results.content.decode('utf-8')}")
            elif transcription.status == "Failed":
                logging.info(f"Transcription failed: {transcription.properties.error.message}")
    
    
    if __name__ == "__main__":
        transcribe()
    

    Output:

    05/08/2023 11:10:07 AM India Standard Time Starting transcription client...
    05/08/2023 11:10:08 AM India Standard Time Created new transcription with id 'your id' in region <region>05/08/2023 11:10:08 AM India Standard Time Checking status.
    05/08/2023 11:10:13 AM India Standard Time Transcriptions status: Running
    05/08/2023 11:10:19 AM India Standard Time Transcriptions status: Succeeded
    05/08/2023 11:10:20 AM India Standard Time Results for contenturl_0.json:
    {
      "source": "https://<storageaccountname>.blob.core.windows.net/test/harvard.wav?<sas-token>",
      "timestamp": "2023-05-08T05:40:15Z",
      "durationInTicks": 183500000,
      "duration": "PT18.35S",
      "combinedRecognizedPhrases": [
        {
          "channel": 0,
          "lexical": "the stale smell of old beer lingers it takes heat to bring out the odor a cold dip restores health and zest a salt pickle tastes fine with ham tacos al pastor are my favorite a zestful food is the hot cross bun",
          "itn": "the stale smell of old beer lingers it takes heat to bring out the odor a cold dip restores health and zest a salt pickle tastes fine with ham tacos al pastor are my favorite a zestful food is the hot cross bun",
          "maskedITN": "the stale smell of old beer lingers it takes heat to bring out the odor a cold dip restores health and zest a salt pickle tastes fine with ham tacos al pastor are my favorite a zestful food is the hot cross bun",
          "display": "The stale smell of old beer lingers. It takes heat to bring out the odor. A cold dip restores health and zest. A salt pickle tastes fine with ham tacos. Al pastor are my favorite. A zestful food is the hot cross bun."
        },
        {
          "channel": 1,
          "lexical": "the stale smell of old beer lingers it takes heat to bring out the odor a cold dip restores health and zest a salt pickle tastes fine with ham tacos al pastor are my favorite a zestful food is the hot cross bun",
          "itn": "the stale smell of old beer lingers it takes heat to bring out the odor a cold dip restores health and zest a salt pickle tastes fine with ham tacos al pastor are my favorite a zestful food is the hot cross bun",
          "maskedITN": "the stale smell of old beer lingers it takes heat to bring out the odor a cold dip restores health and zest a salt pickle tastes fine with ham tacos al pastor are my favorite a zestful food is the hot cross bun",
          "display": "The stale smell of old beer lingers. It takes heat to bring out the odor. A cold dip restores health and zest. A salt pickle tastes fine with ham tacos. Al pastor are my favorite. A zestful food is the hot cross bun
          
    

    enter image description here