Google Cloud Speech API v2元数据元素编码类型及解码问题咨询
Google Cloud Speech API v2 长时识别任务元数据解码问题
问题描述
我正在使用Google Cloud Speech API v2查询长时间运行的识别任务状态,代码如下:
from google.cloud.speech_v2 import SpeechClient client_options_ = client_options.ClientOptions( api_endpoint = "us-west1-speech.googleapis.com" ) client = SpeechClient(client_options = client_options_) ops_obj = { "name": "{{name-of-my-job}}" } resp_obj = client.get_operation(ops_obj) resp_metadata = resp_obj.metadata.value print(resp_metadata)
获取到的元数据片段如下:
b'\n\x0c\x08\xf0\x8a\xc7\xaf\x06\x10\xa0\xdf\xb3\xce\x03\x12\x0c\x08\x89\xac\xc7\xaf\x06\x10\xe0\xef...
尝试执行resp_metadata.decode('utf-8')解码时,出现错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf0 in position 3: invalid continuation byte
请问该元数据采用何种编码?如何将其转为可用数据?
解决方案
这个元数据不是UTF-8编码的字符串,而是Protocol Buffer(Protobuf)二进制格式的数据。Google Cloud API的操作元数据普遍以Protobuf二进制形式传输,需要用对应生成的Python类解析。
具体步骤
导入对应Protobuf类
Speech API v2的长时识别任务元数据对应google.cloud.speech_v2.types.LongRunningRecognizeMetadata类,直接导入即可:from google.cloud.speech_v2.types import LongRunningRecognizeMetadata解析二进制元数据
使用LongRunningRecognizeMetadata的ParseFromString方法解析二进制数据:metadata = LongRunningRecognizeMetadata() metadata.ParseFromString(resp_metadata)访问解析后的数据
解析完成后,可像访问普通Python对象属性一样获取元数据内容,例如:print(f"任务创建时间: {metadata.create_time}") print(f"已处理音频时长: {metadata.processed_audio_duration}") print(f"任务状态: {metadata.state}")
完整示例代码
from google.cloud.speech_v2 import SpeechClient from google.cloud.speech_v2.types import LongRunningRecognizeMetadata import client_options client_options_ = client_options.ClientOptions( api_endpoint = "us-west1-speech.googleapis.com" ) client = SpeechClient(client_options = client_options_) ops_obj = { "name": "{{name-of-my-job}}" } resp_obj = client.get_operation(ops_obj) # 解析元数据 metadata = LongRunningRecognizeMetadata() metadata.ParseFromString(resp_obj.metadata.value) # 打印解析后的核心信息 print(f"任务状态: {metadata.state}") print(f"已处理音频时长: {metadata.processed_audio_duration}") print(f"任务创建时间: {metadata.create_time}")
内容的提问来源于stack exchange,提问作者SeanMaday
相关产品推荐
相关产品推荐

