2017-05-12 21 views
0

下面是一個片段,它調用谷歌雲語音API長時間運行的操作將音頻文件轉換爲文本如何在以後獲得長時間運行的Google雲語音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() 

然而,因爲它是一個長期運行的操作,這可能需要一段時間,我非常唐」不想在等待的時候繼續開會。是否可以存儲一些信息並稍後檢索結果?

回答

1

閱讀源代碼後,我發現GRPC有10分鐘的超時時間。如果您提交一個大文件,轉錄可能需要10分鐘以上。訣竅是使用HTTP後端。 HTTP後端不會像GRPC那樣維護連接,而是每次您調查時發送HTTP請求。要使用HTTP,做

speech_client = speech.Client(_use_grpc=False)

0

不,沒有辦法做到這一點。你可以做的就是使用線程模塊,因爲它可以在後臺運行時在後臺運行。

0

作爲另一個答覆中提到,你可以使用一個單獨的線程,而主線程繼續輪詢操作。或者,您可以將返回的操作的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'}]}]}} 
相關問題