【问题标题】:Google Cloud Speech API python code sample has possible bugGoogle Cloud Speech API python 代码示例可能存在错误
【发布时间】:2017-04-18 03:27:29
【问题描述】:

我正在处理 Google Speech API found here 提供的代码 sn-ps。该代码应该足以将 .wav 文件转换为转录文本。

感兴趣的块在这里:

def transcribe_file(speech_file):
    """Transcribe the given audio file."""
    from google.cloud import speech
    speech_client = speech.Client()

    with io.open(speech_file, 'rb') as audio_file:
        content = audio_file.read()
        audio_sample = speech_client.sample(
            content=content,
            source_uri=None,
            encoding='LINEAR16',
            sample_rate_hertz=16000)

    alternatives = audio_sample.recognize('en-US')
    for alternative in alternatives:
        print('Transcript: {}'.format(alternative.transcript))

首先,我认为代码可能是旧的,sample_rate_hertz=16000 必须更改为 sample_rate=16000

之后,我收到此行的错误:
alternatives = audio_sample.recognize('en-US')
内容为
AttributeError: 'Sample' object has no attribute 'recognize'

我很好奇如何纠正这个问题。我似乎找不到有关此方法的任何文档。也许它也需要更换。

【问题讨论】:

  • 请看here,因为有类似的工作示例

标签: python google-speech-api


【解决方案1】:

您需要将文件读取为二进制文件,然后使用带有 body 参数 (dict) 的 service.speech().syncrecognize,其中包含所有必需的参数,例如:

  • 编码,
  • 采样率
  • 语言)

你可以试试这样的:

with open(speech_file, 'rb') as speech:
    speech_content = base64.b64encode(speech.read())

service = get_speech_service()
service_request = service.speech().syncrecognize(
    body={
        'config': {
            'encoding': 'LINEAR16',  # raw 16-bit signed LE samples
            'sampleRate': 16000,  # 16 khz
            'languageCode': 'en-US',  # a BCP-47 language tag
        },
        'audio': {
            'content': speech_content.decode('UTF-8')
            }
        })
response = service_request.execute()
print(json.dumps(response))

请看here,因为有一个类似的工作示例。

【讨论】:

    【解决方案2】:

    您使用的是 github quickstart.py 示例,所以我想知道这与文档 Google Cloud Speech API class sample 不同步。但它仍然是BETA

    假设isinstance(audio_sample, <class Sample(object)>) == True,
    然后.recognize 在你的

    alternatives = audio_sample.recognize('en-US')
    

    应该是其中之一

    async_recognize, streaming_recognize, sync_recognize
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多