def transcribe():
    logging.info("Starting transcription client...")

    # configure API key authorization: subscription_key
    configuration = cris_client.Configuration()
    configuration.api_key['Ocp-Apim-Subscription-Key'] = SUBSCRIPTION_KEY
    configuration.host = "https://{}.cris.ai".format(SERVICE_REGION)

    # create the client object and authenticate
    client = cris_client.ApiClient(configuration)

    # create an instance of the transcription api class
    transcription_api = cris_client.CustomSpeechTranscriptionsApi(api_client=client)

    # get all transcriptions for the subscription
    transcriptions: List[cris_client.Transcription] = transcription_api.get_transcriptions()

    logging.info("Deleting all existing completed transcriptions.")

    # delete all pre-existing completed transcriptions
    # if transcriptions are still running or not started, they will not be deleted
    for transcription in transcriptions:
        try:
            transcription_api.delete_transcription(transcription.id)
        except ValueError:
            # ignore swagger error on empty response message body: https://github.com/swagger-api/swagger-core/issues/2446
            pass

    # Specify transcription properties by passing a dict to the properties parameter. See
    # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription#configuration-properties
    # for supported parameters.
    properties = {
        # 'PunctuationMode': 'DictatedAndAutomatic',
        # 'ProfanityFilterMode': 'Masked',
        # 'AddWordLevelTimestamps': 'False',
        # 'AddDiarization': 'False',
        # 'AddSentiment': False,
        # 'TranscriptionResultsContainerUrl': "<results container>"
    }

    # Use base models for transcription. Comment this block if you are using a custom model.
    transcription_definition = cris_client.TranscriptionDefinition(
        name=NAME, description=DESCRIPTION, locale=LOCALE, recordings_url=RECORDINGS_BLOB_URI,
        properties=properties
    )

    # Uncomment this block to use custom models for transcription.
    # Model information (ADAPTED_ACOUSTIC_ID and ADAPTED_LANGUAGE_ID) must be set above.
    # if ADAPTED_ACOUSTIC_ID is None or ADAPTED_LANGUAGE_ID is None:
    #     logging.info("Custom model ids must be set to when using custom models")
    # transcription_definition = cris_client.TranscriptionDefinition(
    #     name=NAME, description=DESCRIPTION, locale=LOCALE, recordings_url=RECORDINGS_BLOB_URI,
    #     models=[cris_client.ModelIdentity(ADAPTED_ACOUSTIC_ID), cris_client.ModelIdentity(ADAPTED_LANGUAGE_ID)],
    #     properties=properties
    # )

    data, status, headers = transcription_api.create_transcription_with_http_info(transcription_definition)

    # extract transcription location from the headers
    transcription_location: str = headers["location"]

    # get the transcription Id from the location URI
    created_transcription: str = transcription_location.split('/')[-1]

    logging.info("Created new transcription with id {}".format(created_transcription))

    logging.info("Checking status.")

    completed = False

    while not completed:
        running, not_started = 0, 0

        # get all transcriptions for the user
        transcriptions: List[cris_client.Transcription] = transcription_api.get_transcriptions()

        # for each transcription in the list we check the status
        for transcription in transcriptions:
            if transcription.status in ("Failed", "Succeeded"):
                # we check to see if it was the transcription we created from this client
                if created_transcription != transcription.id:
                    continue

                completed = True

                if transcription.status == "Succeeded":
                    results_uri = transcription.results_urls["channel_0"]
                    results = requests.get(results_uri)
                    logging.info("Transcription succeeded. Results: ")
                    logging.info(results.content.decode("utf-8"))
                else:
                    logging.info("Transcription failed :{}.".format(transcription.status_message))
                    break
            elif transcription.status == "Running":
                running += 1
            elif transcription.status == "NotStarted":
                not_started += 1

        logging.info("Transcriptions status: "
                     "completed (this transcription): {}, {} running, {} not started yet".format(
                         completed, running, not_started))

        # wait for 5 seconds
        time.sleep(5)

    input("Press any key...")
예제 #2
0
def transcribe():
    logging.info("Starting transcription client...")

    # configure API key authorization: subscription_key
    configuration = cris_client.Configuration()
    configuration.api_key['Ocp-Apim-Subscription-Key'] = SUBSCRIPTION_KEY
    configuration.host = "https://{}.cris.ai".format(SERVICE_REGION)

    # create the client object and authenticate
    client = cris_client.ApiClient(configuration)

    # create an instance of the transcription api class
    transcription_api = cris_client.CustomSpeechTranscriptionsApi(
        api_client=client)

    # Use base models for transcription. Comment this block if you are using a custom model.
    # Note: you can specify additional transcription properties by passing a
    # dictionary in the properties parameter. See
    # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription
    # for supported parameters.
    transcription_definition = cris_client.TranscriptionDefinition(
        name=NAME,
        description=DESCRIPTION,
        locale=LOCALE,
        recordings_url=RECORDINGS_BLOB_URI)

    # Uncomment this block to use custom models for transcription.
    # Model information (ADAPTED_ACOUSTIC_ID and ADAPTED_LANGUAGE_ID) must be set above.
    # if ADAPTED_ACOUSTIC_ID is None or ADAPTED_LANGUAGE_ID is None:
    #     logging.info("Custom model ids must be set to when using custom models")
    # transcription_definition = cris_client.TranscriptionDefinition(
    #     name=NAME, description=DESCRIPTION, locale=LOCALE, recordings_url=RECORDINGS_BLOB_URI,
    #     models=[cris_client.ModelIdentity(ADAPTED_ACOUSTIC_ID), cris_client.ModelIdentity(ADAPTED_LANGUAGE_ID)]
    # )

    data, status, headers = transcription_api.create_transcription_with_http_info(
        transcription_definition)

    # extract transcription location from the headers
    transcription_location: str = headers["location"]

    # get the transcription Id from the location URI
    created_transcription: str = transcription_location.split('/')[-1]

    logging.info(
        "Created new transcription with id {}".format(created_transcription))

    logging.info("Checking status.")

    completed = False

    while not completed:
        running, not_started = 0, 0

        # get all transcriptions for the user
        transcriptions: List[
            cris_client.Transcription] = transcription_api.get_transcriptions(
            )

        # for each transcription in the list we check the status
        for transcription in transcriptions:
            if transcription.status in ("Failed", "Succeeded"):
                # we check to see if it was the transcription we created from this client
                if created_transcription != transcription.id:
                    continue

                completed = True

                if transcription.status == "Succeeded":
                    results_uri = transcription.results_urls["channel_0"]
                    results = requests.get(results_uri)
                    logging.info("Transcription succeeded. Results: ")
                    logging.info(results.content.decode("utf-8"))
                else:
                    logging.info("Transcription failed :{}.".format(
                        transcription.status_message))
                    break
            elif transcription.status == "Running":
                running += 1
            elif transcription.status == "NotStarted":
                not_started += 1

        logging.info(
            "Transcriptions status: "
            "completed (this transcription): {}, {} running, {} not started yet"
            .format(completed, running, not_started))

        # wait for 5 seconds
        time.sleep(5)

    input("Press any key...")
예제 #3
0
    def transcribe(self,
                   blob_uri,
                   name='',
                   description='',
                   locale='en-US',
                   properties={},
                   output_file=None):
        logging.info("Starting transcription client...")

        # configure API key authorization: subscription_key
        configuration = cris_client.Configuration()
        configuration.api_key['Ocp-Apim-Subscription-Key'] = self.speech_key
        configuration.host = "https://{}.cris.ai".format(self.service_region)

        # create the client object and authenticate
        client = cris_client.ApiClient(configuration)

        # create an instance of the transcription api class
        transcription_api = cris_client.CustomSpeechTranscriptionsApi(
            api_client=client)

        # get all transcriptions for the subscription
        transcriptions: List[
            cris_client.Transcription] = transcription_api.get_transcriptions(
            )

        logging.info("Deleting all existing completed transcriptions.")

        # delete all pre-existing completed transcriptions
        # if transcriptions are still running or not started, they will not be deleted
        for transcription in transcriptions:
            try:
                transcription_api.delete_transcription(transcription.id)
            except Exception as e:
                print(e)

        # Specify transcription properties by passing a dict to the properties parameter. See
        # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription#configuration-properties
        # for supported parameters.
        # properties = {
        # 'PunctuationMode': 'DictatedAndAutomatic',
        # 'ProfanityFilterMode': 'Masked',
        # 'AddWordLevelTimestamps': 'False',
        # 'AddDiarization': 'False',
        # 'AddSentiment': False,
        # 'TranscriptionResultsContainerUrl': "<results container>"
        # }

        # Use base models for transcription. Comment this block if you are using a custom model.
        transcription_definition = cris_client.TranscriptionDefinition(
            name=name,
            description=description,
            locale=locale,
            recordings_url=blob_uri,
            properties=properties)

        data, status, headers = transcription_api.create_transcription_with_http_info(
            transcription_definition)

        # extract transcription location from the headers
        transcription_location: str = headers["location"]

        # get the transcription Id from the location URI
        created_transcription: str = transcription_location.split('/')[-1]

        logging.info("Created new transcription with id {}".format(
            created_transcription))

        logging.info("Checking status.")

        completed = False

        while not completed:
            running, not_started = 0, 0

            # get all transcriptions for the user
            transcriptions: List[
                cris_client.
                Transcription] = transcription_api.get_transcriptions()

            # for each transcription in the list we check the status
            for transcription in transcriptions:
                if transcription.status in ("Failed", "Succeeded"):
                    # we check to see if it was the transcription we created from this client
                    if created_transcription != transcription.id:
                        continue

                    completed = True

                    if transcription.status == "Succeeded":
                        results_uri = transcription.results_urls["channel_0"]
                        results = requests.get(results_uri)
                        logging.info("Transcription succeeded. Results: ")

                        logging.info(
                            "######### TRANSCRIPTION BEGIN ########## ")
                        logging.info(results.content.decode("utf-8"))

                        if (output_file):
                            json_file = open(output_file, 'w')
                            json_file.write(
                                json.loads(
                                    json.dumps(results.content.decode("utf-8"),
                                               ensure_ascii=False)))

                        logging.info("######### TRANSCRIPTION END ########## ")
                    else:
                        logging.info("Transcription failed :{}.".format(
                            transcription.status_message))
                        break
                elif transcription.status == "Running":
                    running += 1
                elif transcription.status == "NotStarted":
                    not_started += 1

            logging.info(
                "Transcriptions status: "
                "completed (this transcription): {}, {} running, {} not started yet"
                .format(completed, running, not_started))

            # wait for 5 seconds
            time.sleep(5)
예제 #4
0
def transcribe(url):
    logging.info("Starting transcription client...")
    # Your subscription key and region for the speech service
    SUBSCRIPTION_KEY = ""
    SERVICE_REGION = "southcentralus"
    NAME = "Simple transcription"
    DESCRIPTION = "Simple transcription description"
    LOCALE = "en-US"
    # Set subscription information when doing transcription with custom models
    ADAPTED_ACOUSTIC_ID = None  # guid of a custom acoustic model
    ADAPTED_LANGUAGE_ID = None  # guid of a custom language model


   # configure API key authorization: subscription_key
    configuration = cris_client.Configuration()
    configuration.api_key['Ocp-Apim-Subscription-Key'] = SUBSCRIPTION_KEY
    configuration.host = "https://{}.cris.ai".format(SERVICE_REGION)

    # create the client object and authenticate
    client = cris_client.ApiClient(configuration)

    # create an instance of the transcription api class
    transcription_api = cris_client.CustomSpeechTranscriptionsApi(api_client=client)

    # get all transcriptions for the subscription
    transcriptions: List[cris_client.Transcription] = transcription_api.get_transcriptions()

    logging.info("Deleting all existing completed transcriptions.")

    # delete all pre-existing completed transcriptions
    # if transcriptions are still running or not started, they will not be deleted
    for transcription in transcriptions:
        try:
            transcription_api.delete_transcription(transcription.id)
        except ValueError:
            # ignore swagger error on empty response message body: https://github.com/swagger-api/swagger-core/issues/2446
            pass

    # Use base models for transcription. Comment this block if you are using a custom model.
    # Note: you can specify additional transcription properties by passing a
    # dictionary in the properties parameter. See
    # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription
    # for supported parameters.
    logging.info("Printing URL ::: {}".format(url))
    transcription_definition = cris_client.TranscriptionDefinition(
        name=NAME, description=DESCRIPTION, locale=LOCALE, recordings_url=url
    )

    # Uncomment this block to use custom models for transcription.
    # Model information (ADAPTED_ACOUSTIC_ID and ADAPTED_LANGUAGE_ID) must be set above.
    # if ADAPTED_ACOUSTIC_ID is None or ADAPTED_LANGUAGE_ID is None:
    #     logging.info("Custom model ids must be set to when using custom models")
    # transcription_definition = cris_client.TranscriptionDefinition(
    #     name=NAME, description=DESCRIPTION, locale=LOCALE, recordings_url=RECORDINGS_BLOB_URI,
    #     models=[cris_client.ModelIdentity(ADAPTED_ACOUSTIC_ID), cris_client.ModelIdentity(ADAPTED_LANGUAGE_ID)]
    # )

    data, status, headers = transcription_api.create_transcription_with_http_info(transcription_definition)

    # extract transcription location from the headers
    transcription_location: str = headers["location"]

    # get the transcription Id from the location URI
    created_transcription: str = transcription_location.split('/')[-1]

    logging.info("Created new transcription with id {}".format(created_transcription))

    logging.info("Checking status.")

    completed = False

    while not completed:
        running, not_started = 0, 0

        # get all transcriptions for the user
        transcriptions: List[cris_client.Transcription] = transcription_api.get_transcriptions()

        # for each transcription in the list we check the status
        for transcription in transcriptions:
            if transcription.status in ("Failed", "Succeeded"):
                # we check to see if it was the transcription we created from this client
                if created_transcription != transcription.id:
                    continue

                completed = True

                if transcription.status == "Succeeded":
                    results_uri = transcription.results_urls["channel_0"]
                    results = requests.get(results_uri)
                    logging.info("Transcription succeeded. Results: ")
                    logging.info(results.content.decode("utf-8"))
                    return results.content.decode("utf-8")
                else:
                    logging.info("Transcription failed :{}.".format(transcription.status_message))

                break
            elif transcription.status == "Running":
                running += 1
            elif transcription.status == "NotStarted":
                not_started += 1

        logging.info("Transcriptions status: "
                "completed (this transcription): {}, {} running, {} not started yet".format(
                    completed, running, not_started))

        # wait for 5 seconds
        time.sleep(5)
예제 #5
0
def transcribe():
    logging.info("Starting transcription client...")

    # configure API key authorization: subscription_key
    configuration = cris_client.Configuration()
    configuration.api_key['Ocp-Apim-Subscription-Key'] = SUBSCRIPTION_KEY

    # create the client object and authenticate
    client = cris_client.ApiClient(configuration)

    # create an instance of the transcription api class
    transcription_api = cris_client.CustomSpeechTranscriptionsApi(
        api_client=client)

    # get all transcriptions for the subscription
    transcriptions: List[
        cris_client.Transcription] = transcription_api.get_transcriptions()

    logging.info("Deleting all existing completed transcriptions.")

    # delete all pre-existing completed transcriptions
    # if transcriptions are still running or not started, they will not be deleted
    for transcription in transcriptions:
        try:
            transcription_api.delete_transcription(transcription.id)
        except ValueError:
            # ignore swagger error on empty response message body: https://github.com/swagger-api/swagger-core/issues/2446
            pass

    logging.info("Creating transcriptions.")

    # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription
    properties = {'AddWordLevelTimestamps': 'True', 'AddDiarization': 'True'}

    transcription_definition = cris_client.TranscriptionDefinition(
        name=NAME,
        description=DESCRIPTION,
        locale=LOCALE,
        recordings_url=RECORDINGS_BLOB_URI,
        properties=properties)

    data, status, headers = transcription_api.create_transcription_with_http_info(
        transcription_definition)

    # extract transcription location from the headers
    transcription_location: str = headers["location"]

    # get the transcription Id from the location URI
    created_transcription: str = transcription_location.split('/')[-1]

    logging.info("Checking status.")

    completed = False

    while not completed:
        running, not_started = 0, 0

        # get all transcriptions for the user
        transcriptions: List[
            cris_client.Transcription] = transcription_api.get_transcriptions(
            )

        # for each transcription in the list we check the status
        for transcription in transcriptions:
            if transcription.status in ("Failed", "Succeeded"):
                # we check to see if it was one of the transcriptions we created from this client
                if created_transcription != transcription.id:
                    continue

                completed = True

                if transcription.status == "Succeeded":
                    results_uri = transcription.results_urls["channel_0"]
                    results = requests.get(results_uri)
                    logging.info("Transcription succeeded. Results: ")
                    logging.info(results.content.decode("utf-8"))
                else:
                    logging.info("Transcription failed :{}.".format(
                        transcription.status_message))
            elif transcription.status == "Running":
                running += 1
            elif transcription.status == "NotStarted":
                not_started += 1

        logging.info(
            "Transcriptions status: "
            "completed (this transcription): {}, {} running, {} not started yet"
            .format(completed, running, not_started))

        time.sleep(5)

    sys.exit()
예제 #6
0
def transcribe():
    logging.info("Starting transcription client...")

    # configure API key authorization: subscription_key
    configuration = cris_client.Configuration()
    configuration.api_key['Ocp-Apim-Subscription-Key'] = SUBSCRIPTION_KEY

    # create the client object and authenticate
    client = cris_client.ApiClient(configuration)

    # create an instance of the transcription api class
    transcription_api = cris_client.CustomSpeechTranscriptionsApi(
        api_client=client)

    # get all transcriptions for the subscription
    transcriptions: List[
        cris_client.Transcription] = transcription_api.get_transcriptions()

    logging.info("Deleting all existing completed transcriptions.")

    # delete all pre-existing completed transcriptions
    # if transcriptions are still running or not started, they will not be deleted
    for transcription in transcriptions:
        transcription_api.delete_transcription(transcription.id)

    logging.info("Creating transcriptions.")

    # Use base models for transcription. Comment this block if you are using a custom model.
    transcription_definition = cris_client.TranscriptionDefinition(
        name=NAME,
        description=DESCRIPTION,
        locale=LOCALE,
        recordings_url=RECORDINGS_BLOB_URI)

    # Uncomment this block to use custom models for transcription.
    # Model information (ADAPTED_ACOUSTIC_ID and ADAPTED_LANGUAGE_ID) must be set above.
    # if ADAPTED_ACOUSTIC_ID is None or ADAPTED_LANGUAGE_ID is None:
    #     logging.info("Custom model ids must be set to when using custom models")
    # transcription_definition = cris_client.TranscriptionDefinition(
    #     name=NAME, description=DESCRIPTION, locale=LOCALE, recordings_url=RECORDINGS_BLOB_URI,
    #     models=[cris_client.ModelIdentity(ADAPTED_ACOUSTIC_ID), cris_client.ModelIdentity(ADAPTED_LANGUAGE_ID)]
    # )

    data, status, headers = transcription_api.create_transcription_with_http_info(
        transcription_definition)

    # extract transcription location from the headers
    transcription_location: str = headers["location"]

    # get the transcription Id from the location URI
    created_transcription: str = transcription_location.split('/')[-1]

    logging.info("Checking status.")

    completed = False
    running, not_started = 0, 0

    while not completed:
        # get all transcriptions for the user
        transcriptions: List[
            cris_client.Transcription] = transcription_api.get_transcriptions(
            )

        # for each transcription in the list we check the status
        for transcription in transcriptions:
            if transcription.status == "Failed" or transcription.status == "Succeeded":
                # we check to see if it was one of the transcriptions we created from this client
                if created_transcription != transcription.id:
                    continue

                completed = True

                if transcription.status == "Succeeded":
                    results_uri = transcription.results_urls["channel_0"]
                    results = requests.get(results_uri)
                    logging.info("Transcription succeeded. Results: ")
                    logging.info(results.content.decode("utf-8"))
            elif transcription.status == "Running":
                running += 1
            elif transcription.status == "NotStarted":
                not_started += 1

        logging.info(
            "Transcriptions status: "
            "completed (this transcription): {}, {} running, {} not started yet"
            .format(completed, running, not_started))

        # wait for 5 seconds
        time.sleep(5)

    input("Press any key...")
def transcribe():
    logging.info("Starting transcription client...")

    # configure API key authorization: subscription_key
    configuration = cris_client.Configuration()
    configuration.api_key["Ocp-Apim-Subscription-Key"] = SUBSCRIPTION_KEY
    configuration.host = f"https://{SERVICE_REGION}.api.cognitive.microsoft.com/speechtotext/v3.0"

    # create the client object and authenticate
    client = cris_client.ApiClient(configuration)

    # create an instance of the transcription api class
    api = cris_client.CustomSpeechTranscriptionsApi(api_client=client)

    # Specify transcription properties by passing a dict to the properties parameter. See
    # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription#configuration-properties
    # for supported parameters.
    properties = {
        # "punctuationMode": "DictatedAndAutomatic",
        # "profanityFilterMode": "Masked",
        # "wordLevelTimestampsEnabled": True,
        # "diarizationEnabled": True,
        # "destinationContainerUrl": "<SAS Uri with at least write (w) permissions for an Azure Storage blob container that results should be written to>",
        # "timeToLive": "PT1H"
    }

    # Use base models for transcription. Comment this block if you are using a custom model.
    transcription_definition = transcribe_from_single_blob(
        RECORDINGS_BLOB_URI, properties)

    # Uncomment this block to use custom models for transcription.
    # transcription_definition = transcribe_with_custom_model(api, RECORDINGS_BLOB_URI, properties)

    # Uncomment this block to transcribe all files from a container.
    # transcription_definition = transcribe_from_container(RECORDINGS_CONTAINER_URI, properties)

    created_transcription, status, headers = api.create_transcription_with_http_info(
        transcription=transcription_definition)

    # get the transcription Id from the location URI
    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.get_transcription(transcription_id)
        logging.info(f"Transcriptions status: {transcription.status}")

        if transcription.status in ("Failed", "Succeeded"):
            completed = True

        if transcription.status == "Succeeded":
            pag_files = api.get_transcription_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}"
            )
예제 #8
0
def transcribe():
    logging.info("Starting transcription client...")

    # APIキー認証の構成
    configuration = cris_client.Configuration()
    configuration.api_key["Ocp-Apim-Subscription-Key"] = SUBSCRIPTION_KEY
    configuration.host = "https://{}.cris.ai".format(SERVICE_REGION)

    # clientオブジェクトの生成
    client = cris_client.ApiClient(configuration)

    # transcription apiクラスのインスタンス生成
    transcription_api = cris_client.CustomSpeechTranscriptionsApi(
        api_client=client)

    # ベースモデルを使ったtranscriptionの定義
    transcription_definition = cris_client.TranscriptionDefinition(
        name=NAME,
        description=DESCRIPTION,
        locale=LOCALE,
        recordings_url=RECORDINGS_BLOB_URI)

    data, status, headers = transcription_api.create_transcription_with_http_info(
        transcription_definition)

    # locationの取得
    transcription_location: str = headers["location"]

    # transcription idの取得
    created_transcription: str = transcription_location.split("/")[-1]

    logging.info(
        "Created new transcription with id {}".format(created_transcription))

    logging.info("Checking status...")

    completed = False

    while not completed:
        running, not_started = 0, 0

        # transcriptionの実行
        transcriptions: List[
            cris_client.Transcription] = transcription_api.get_transcriptions(
            )

        for transcription in transcriptions:
            if transcription.status in ("Failed", "Succeeded"):
                if created_transcription != transcription.id:
                    continue

                completed = True

                if transcription.status == "Succeeded":
                    results_uri = transcription.results_urls["channel_0"]
                    results = requests.get(results_uri)
                    logging.info("Transcription succeeded. Results: ")
                    logging.info(results.content.decode("utf-8"))
                else:
                    logging.info("Transaction failed :{}.".format(
                        transcription.status_message))

                break
            elif transcription.status == "Running":
                running += 1
            elif transcription.status == "NotStarted":
                not_started += 1

        logging.info(
            "Transctions status: "
            "completed (this transcription): {}, {} running, {} not started yet"
            .format(completed, running, not_started))

        time.sleep(5)

    input("Press any key...")
def transcribe(outfile, file_name):
    block_blob_service = BlockBlobService(account_name=ACCOUNT_NAME,
                                          account_key=ACCOUNT_KEY)
    container_name = "youcook2-videos-audio"
    blob_name = 'train/' + file_name + '.wav'
    sas_url = block_blob_service.generate_blob_shared_access_signature(
        container_name,
        blob_name,
        permission=BlobPermissions.READ,
        expiry=datetime.utcnow() + timedelta(hours=1),
        start=datetime.utcnow())
    print(sas_url)
    recordings_blob_uri = URI_PREFIX + '/' + blob_name + '?' + sas_url
    print(recordings_blob_uri)
    logging.info("Starting transcription client...")

    # configure API key authorization: subscription_key
    configuration = cris_client.Configuration()
    configuration.api_key['Ocp-Apim-Subscription-Key'] = SUBSCRIPTION_KEY

    # create the client object and authenticate
    client = cris_client.ApiClient(configuration)

    # create an instance of the transcription api class
    transcription_api = cris_client.CustomSpeechTranscriptionsApi(
        api_client=client)

    # get all transcriptions for the subscription
    transcriptions: List[
        cris_client.Transcription] = transcription_api.get_transcriptions()

    #logging.info("Deleting all existing completed transcriptions.")

    # delete all pre-existing completed transcriptions
    # if transcriptions are still running or not started, they will not be deleted
    #for transcription in transcriptions:
    #    try:
    #        transcription_api.delete_transcription(transcription.id)
    #    except ValueError:
    # ignore swagger error on empty response message body: https://github.com/swagger-api/swagger-core/issues/2446
    #        pass

    logging.info("Creating transcriptions.")

    # Use base models for transcription. Comment this block if you are using a custom model.
    # Note: you can specify additional transcription properties by passing a
    # dictionary in the properties parameter. See
    # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription
    # for supported parameters.
    transcription_definition = cris_client.TranscriptionDefinition(
        name=NAME,
        description=DESCRIPTION,
        locale=LOCALE,
        recordings_url=recordings_blob_uri)

    # Uncomment this block to use custom models for transcription.
    # Model information (ADAPTED_ACOUSTIC_ID and ADAPTED_LANGUAGE_ID) must be set above.
    # if ADAPTED_ACOUSTIC_ID is None or ADAPTED_LANGUAGE_ID is None:
    #     logging.info("Custom model ids must be set to when using custom models")
    # transcription_definition = cris_client.TranscriptionDefinition(
    #     name=NAME, description=DESCRIPTION, locale=LOCALE, recordings_url=RECORDINGS_BLOB_URI,
    #     models=[cris_client.ModelIdentity(ADAPTED_ACOUSTIC_ID), cris_client.ModelIdentity(ADAPTED_LANGUAGE_ID)]
    # )

    data, status, headers = transcription_api.create_transcription_with_http_info(
        transcription_definition)

    # extract transcription location from the headers
    transcription_location: str = headers["location"]

    # get the transcription Id from the location URI
    created_transcription: str = transcription_location.split('/')[-1]

    logging.info("Checking status.")

    completed = False

    while not completed:
        running, not_started = 0, 0

        # get all transcriptions for the user
        transcriptions: List[
            cris_client.Transcription] = transcription_api.get_transcriptions(
            )

        # for each transcription in the list we check the status
        for transcription in transcriptions:
            if transcription.status in ("Failed", "Succeeded"):
                # we check to see if it was one of the transcriptions we created from this client
                if created_transcription != transcription.id:
                    continue

                completed = True

                if transcription.status == "Succeeded":
                    results_uri = transcription.results_urls["channel_0"]
                    results = requests.get(results_uri)
                    logging.info("Transcription succeeded. Results: ")
                    with open(outfile, 'w', encoding='utf-8') as f:
                        json.dump(results.json(),
                                  f,
                                  ensure_ascii=False,
                                  indent=4)
                else:
                    logging.info("Transcription failed :{}.".format(
                        transcription.status_message))
            elif transcription.status == "Running":
                running += 1
            elif transcription.status == "NotStarted":
                not_started += 1

        logging.info(
            "Transcriptions status: "
            "completed (this transcription): {}, {} running, {} not started yet"
            .format(completed, running, not_started))

        # wait for 10 seconds
        time.sleep(10)