Search code examples
pythonspeech-recognitiongoogle-speech-api

Using Google Cloud API python sample asynchronous recording code is giving me attribute error


Link to code:

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

I'm using the sample python code from Google Speech API to convert long (greater than 1 minute) audio files from speech to text. How do I run the code in PyCharm so it converts my audio file (in wave format) to text using the API key I created (to charge my account) without getting the 'NoneType' error?

I added the path of the audio file directly into the code (line 73). I also added "--" in front of 'path' to make it process the LOC (line 73). The error I get is as follows:

**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)

I expect it to output a file with text from the audio file being transcribed, billing my account in the process.


Solution

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

    With parser.add_argument('--path', help='C:/Users/Dave/Desktop/mizu/output.wav') you just defined that your script may accept argument --path after it's invoked from command line, and that text is just a help text shown if someone starts your script with --help argument.

    So, if that script where if __name__ == '__main__' is located has the name myscript.py, you actually have to start your script like:

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

    But, that routine makes no sense in this case, a solution for you is to get rid of that extra code. Do just:

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