Использование образца асинхронной записи Python для Google Cloud API приводит к ошибке атрибута - PullRequest
1 голос
/ 09 июля 2019

Ссылка на код:

https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_async.py

Я использую пример кода Python из Google Speech API для преобразования длинных (более 1 минуты) аудиофайлов из речи в текст. Как запустить код в PyCharm, чтобы он преобразовывал мой аудиофайл (в волновом формате) в текст, используя ключ API, который я создал (для зарядки моей учетной записи), без получения ошибки NoneType?

Я добавил путь к аудиофайлу прямо в код (строка 73). Я также добавил «-» перед «path», чтобы он обрабатывал LOC (строка 73). Я получаю следующую ошибку:

**C:\Users\Dave\AppData\Local\Programs\Python\Python37\python.exe C:/Users/Dave/Desktop/mizu/gcapi.py
Traceback (most recent call last):
  File "C:/Users/Dave/Desktop/mizu/gcapi.py", line 75, in <module>
    if args.path.startswith('gs://'):
AttributeError: 'NoneType' object has no attribute 'startswith'
Process finished with exit code1**


import argparse
import io


# [START speech_transcribe_async]
def transcribe_file(speech_file):
    """Transcribe the given audio file asynchronously."""
    from google.cloud import speech
    from google.cloud.speech import enums
    from google.cloud.speech import types
    client = speech.SpeechClient()

    # [START speech_python_migration_async_request]
    with io.open(speech_file, 'rb') as audio_file:
        content = audio_file.read()

    audio = types.RecognitionAudio(content=content)
    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code='en-US')

    # [START speech_python_migration_async_response]
    operation = client.long_running_recognize(config, audio)
    # [END speech_python_migration_async_request]

    print('Waiting for operation to complete...')
    response = operation.result(timeout=90)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(u'Transcript: {}'.format(result.alternatives[0].transcript))
        print('Confidence: {}'.format(result.alternatives[0].confidence))
    # [END speech_python_migration_async_response]
# [END speech_transcribe_async]


# [START speech_transcribe_async_gcs]
def transcribe_gcs(gcs_uri):
    """Asynchronously transcribes the audio file specified by the gcs_uri."""
    from google.cloud import speech
    from google.cloud.speech import enums
    from google.cloud.speech import types
    client = speech.SpeechClient()

    audio = types.RecognitionAudio(uri=gcs_uri)
    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=16000,
        language_code='en-US')

    operation = client.long_running_recognize(config, audio)

    print('Waiting for operation to complete...')
    response = operation.result(timeout=90)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(u'Transcript: {}'.format(result.alternatives[0].transcript))
        print('Confidence: {}'.format(result.alternatives[0].confidence))
# [END speech_transcribe_async_gcs]


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '--path', help='C:/Users/Dave/Desktop/mizu/output.wav')
    args = parser.parse_args()
    if args.path.startswith('gs://'):
        transcribe_gcs(args.path)
    else:
        transcribe_file(args.path)

Я ожидаю, что он выведет файл с текстом из аудиофайла, который транскрибируется, и в процессе будет выставлен счет.

1 Ответ

0 голосов
/ 09 июля 2019

https://docs.python.org/3/library/argparse.html

С помощью parser.add_argument('--path', help='C:/Users/Dave/Desktop/mizu/output.wav') вы только что определили, что ваш скрипт может принимать аргумент --path после его вызова из командной строки, и этот текст является просто текстом справки, который отображается, если кто-то запускает ваш скрипт с--help аргумент.

Итак, если этот сценарий, в котором находится if __name__ == '__main__', имеет имя myscript.py, вам действительно нужно запустить свой сценарий следующим образом:

python myscript.py --path C:/Users/Dave/Desktop/mizu/output.wav

Но эта процедура не имеет смысла вВ этом случае решение для вас - избавиться от лишнего кода.Просто:

if __name__ == '__main__':
    transcribe_file('C:/Users/Dave/Desktop/mizu/output.wav')
...