Ссылка на код:
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)
Я ожидаю, что он выведет файл с текстом из аудиофайла, который транскрибируется, и в процессе будет выставлен счет.