You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中从Google Cloud Speech-to-Text V2的BatchRecognizeResponse提取srt_format_uri

问题:Google Cloud Speech-to-Text V2 API提取srt_format_uri及Protobuf结构疑问

我正在使用Google Cloud Speech-to-Text V2 API,涉及BatchRecognizeResponse类型的响应。这是一个包含多个嵌套字段的Protobuf对象,但我不确定它转换后的具体Python类型。我的代码如下:

operation = client.batch_recognize(request=request)
response = operation.result()

打印response得到:

results {
  key: "gs://my-path"
  value {
    metadata {
      total_billed_duration {
        seconds: 121
      }
    }
    cloud_storage_result {
      srt_format_uri: "my-output-path"
    }
  }
}
total_billed_duration {
  seconds: 121
}

我需要提取其中的srt_format_uri值(即"my-output-path")。尝试将results视为字典使用.items(),以及遍历operation.result()的方法均无效。请问如何在Python中正确提取该值?另外,如何确定Protobuf转换后的内部Python结构?是否有相关.proto文件的文档?


解决方法

1. 提取srt_format_uri值

Google Cloud生成的Protobuf对象不是原生字典,而是带属性访问器的自定义类实例,需通过属性链访问嵌套字段:

# 遍历results下所有键值对(适配多输入文件场景)
for key, value in response.results.items():
    srt_uri = value.cloud_storage_result.srt_format_uri
    print(srt_uri)  # 输出: my-output-path

如果仅对应单个输入文件,可直接通过键取值:

# 替换为你的实际输入路径
target_value = response.results["gs://my-path"]
srt_uri = target_value.cloud_storage_result.srt_format_uri

2. 确定Protobuf转换后的Python结构

  • 查看对象属性:用dir()函数查看对象的可用属性和方法,比如dir(response)或dir(response.results),快速获取可访问字段列表。
  • 打印对象类型:通过type(response)或type(response.results)确认具体Python类,类名与Protobuf定义直接对应。
  • Protobuf内置方法:使用ListFields()方法列出对象所有字段及对应值:
    for field, value in response.ListFields():
        print(f"字段名: {field.name}, 值: {value}")
    
  • 官方Protobuf定义:Google Cloud Speech-to-Text V2的.proto文件定义会明确所有嵌套字段的名称和类型,Python类的属性名对应proto字段名的驼峰转下划线形式(如cloud_storage_result对应proto中的cloudStorageResult)。

内容的提问来源于stack exchange,提问作者Kris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:52:32