如何在以后获得长时间运行的Google云语音API操作的结果?

2024-09-29 07:21:48 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个代码片段,它调用googlecloudspeechapi长时间运行操作来将音频文件转换为文本

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

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


Tags: sample代码from文本clientcloudcountgoogle
3条回答

不,没有办法。您可以使用线程模块,这样它就可以在运行下一个任务时在后台运行。在

在阅读了源代码之后,我发现GRPC有10分钟的超时。如果你提交一个大文件,转录可能需要10分钟以上。诀窍是使用HTTP后端。HTTP后端不像GRPC那样维护连接,而是每次轮询它发送一个HTTP请求。要使用HTTP,请

speech_client = speech.Client(_use_grpc=False)

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

下面是通过按名称查找长时间运行的操作来检索该操作的可能方法:

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

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

^{pr2}$

相关问题 更多 >