GoogleCloud Speech2Text“long_running_recognize”响应对象不可迭代

问题描述 投票:0回答:1

当从 Google 云服务运行语音到文本 api 请求时(超过 60 秒的音频,因此我需要使用 long_running_recognize 函数,以及从云存储桶检索音频),我正确地获得了文本响应,但无法迭代通过返回的 LongRunningResponse 对象,这使得里面的信息半无用。

当仅使用“client.recognize()”函数时,我得到与长时间运行响应类似的响应,除了当我检查简短形式的结果时,我可以很好地迭代对象,这与长时间运行的响应相反回应。

我通过每个识别功能运行几乎相同的参数(长时间运行的长音频为 1 分 40 秒,短识别为 30 秒,均来自我的云存储桶)。

short_response = client.recognize(config=config, audio=audio_uri)

subs_list = []
for result in short_response.results:
    for alternative in result.alternatives:
         for word in alternative.words:
               if not word.start_time:
                   start = 0
               else:
                   start = word.start_time.total_seconds()
               end = word.end_time.total_seconds()
               t = word.word
               subs_list.append( ((float(start),float(end)), t) )

    print(subs_list)

上面的函数工作正常,“.results”属性正确返回我可以进一步获取属性并迭代的对象。我使用 for 循环为视频创建字幕。 然后我在 long_running_recognize 上尝试类似的事情,并得到这个:

long_response = client.long_running_recognize(config=config, audio=audio_uri)

#1
print(long_response.results)

#2
print(long_response.result())

#1 的输出返回错误: AttributeError:“操作”对象没有属性“结果”。您指的是:“结果”吗?

#2 的输出返回我需要的信息,但是在检查“type(long_response.result())”时我得到:

我认为这不是一个可迭代的对象,并且我无法弄清楚如何应用与识别函数类似的过程来以我需要的方式获取字幕。

python-3.x google-cloud-platform google-speech-api
1个回答
0
投票

我花了一些时间才弄清楚,你必须自己解析响应。这是代码:

def serialize_response(response):
  result_dict = {
    "results": []
   }

  for result in response.results:
    # Each result contains a list of alternatives
    alternatives = [
        {
            "transcript": alternative.transcript,
            "confidence": alternative.confidence,
            "words": [{
                "start_time": word.start_time.seconds,
                "end_time": word.end_time.seconds,
                "word": word.word,
                "speaker_tag": word.speaker_tag
            } for word in alternative.words]
        } for alternative in result.alternatives
    ]
    
    result_dict["results"].append({
        "alternatives": alternatives
    })

return result_dict
© www.soinside.com 2019 - 2024. All rights reserved.