【问题标题】:How to get the result of a long-running Google Cloud Speech API operation later?以后如何获取长时间运行的 Google Cloud Speech API 操作的结果?
【发布时间】:2017-05-12 19:26:02
【问题描述】:

下面是一个调用 Google Cloud Speech API 长时间运行操作将音频文件转换为文本的 sn-p

from google.cloud import speech
speech_client = speech.Client()

audio_sample = speech_client.sample(
    content=None,
    source_uri=gcs_uri,
    encoding='FLAC',
    sample_rate_hertz=44100)

operation = audio_sample.long_running_recognize('en-US')

retry_count = 100
while retry_count > 0 and not operation.complete:
    retry_count -= 1
    time.sleep(60)
    operation.poll()

但是,由于这是一个长时间运行的操作,可能需要一段时间,而且我理想情况下不希望在等待时保持会话打开。是否可以存储一些信息并稍后检索结果?

【问题讨论】:

    标签: python google-cloud-speech


    【解决方案1】:

    正如另一个答案中提到的,您可以在主线程继续运行时使用单独的线程来轮询操作。或者,您可以将返回的操作的operation.name 传递给单独的服务,并让该其他服务处理轮询。例如,在实践中,调用长时间运行操作的服务可以将 operation.name 发布到 Pub/Sub 主题。

    以下是通过名称查找长时间运行的操作的一种可能方法:

    from oauth2client.client import GoogleCredentials
    from googleapiclient import discovery
    
    credentials = GoogleCredentials.get_application_default()
    speech_service = discovery.build('speech', 'v1', credentials=credentials)
    
    operation_name = .... # operation.name
    
    get_operation_request = speech_service.operations().get(name=operation_name)
    
    # response is a dictionary
    response = get_operation_response.execute()
    
    # handle polling
    retry_count = 100
    while retry_count > 0 and not response.get('done', False):
        retry_count -= 1
        time.sleep(60)
        response = get_operation_response.execute()
    

    操作完成后,response dict 可能如下所示:

    {u'done': True,
     u'metadata': {u'@type': u'type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata',
      u'lastUpdateTime': u'2017-06-21T19:38:14.522280Z',
      u'progressPercent': 100,
      u'startTime': u'2017-06-21T19:38:13.599009Z'},
     u'name': u'...................',
     u'response': {u'@type': u'type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse',
      u'results': [{u'alternatives': [{u'confidence': 0.987629,
          u'transcript': u'how old is the Brooklyn Bridge'}]}]}}
    

    【讨论】:

      【解决方案2】:

      看了源码,发现GRPC有10分钟的超时时间。如果您提交大文件,转录可能需要 10 多分钟。诀窍是使用 HTTP 后端。 HTTP 后端不像 GRPC 那样维护连接,而是每次轮询时都会发送一个 HTTP 请求。要使用 HTTP,请执行

      speech_client = speech.Client(_use_grpc=False)

      【讨论】:

        【解决方案3】:

        不,没有办法做到这一点。您可以做的是使用 threading 模块,这样它就可以在您运行下一个任务时在后台运行。

        【讨论】:

          猜你喜欢
          • 2017-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-14
          • 1970-01-01
          • 2018-11-24
          • 2012-04-03
          • 1970-01-01
          相关资源
          最近更新 更多