簡體   English   中英

如何在以后獲得長期運行的Google Cloud Speech API操作的結果?

[英]How to get the result of a long-running Google Cloud Speech API operation later?

以下是調用Google Cloud Speech API長時間運行操作以將音頻文件轉換為文本的代碼段

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

但是,因為它是一個長時間運行的操作,它可能需要一段時間,我理想情況下不希望在等待時保持會話。 是否可以存儲一些信息並在以后檢索結果?

如另一個答案所述,您可以使用單獨的線程在主線程繼續時輪詢操作。 或者,您可以通過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字典可能如下所示:

{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'}]}]}}

閱讀完源代碼后,我發現GRPC有10分鍾超時。 如果您提交大文件,轉錄可能需要10分鍾以上。 訣竅是使用HTTP后端。 HTTP后端不像GRPC那樣維護連接,而是每次輪詢它都會發送HTTP請求。 要使用HTTP,請執行

speech_client = speech.Client(_use_grpc=False)

不,沒有辦法做到這一點。 你可以做的是使用線程模塊,以便它可以在你下一個任務運行時在后台運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM