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

如何通过GCP Python客户端库调用区域Speech-to-Text识别器?

如何通过GCP Python客户端库调用区域Speech-to-Text识别器(Chirp模型)

问题背景

目标是使用Python客户端库通过Chirp识别器将语音音频文件转换为文本。原代码基于GCP Speech-to-Text v2文档编写,在使用global区域模型时运行正常,但Chirp模型仅在us-central1区域可用。修改代码指定非global区域时出现以下错误:

  • 直接修改识别器名称路径为us-central1时,触发400错误,提示位置应为global
  • 尝试创建us-central1区域识别器时,触发404错误,提示识别器不存在

解决方案

要调用区域识别器(如Chirp),需要在客户端初始化、识别器创建两个关键步骤中指定正确的区域,以下是修改后的完整代码及关键说明:

修改后的完整代码

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech


def speech_to_text(project_id, recognizer_id, audio_file):
    # 初始化客户端时指定us-central1区域的API端点
    client = SpeechClient(
        client_options={"api_endpoint": "us-central1-speech.googleapis.com"}
    )

    # 创建识别器时指定us-central1作为父区域,模型设置为chirp
    request = cloud_speech.CreateRecognizerRequest(
        parent=f"projects/{project_id}/locations/us-central1",
        recognizer_id=recognizer_id,
        recognizer=cloud_speech.Recognizer(
            language_codes=["en-US"], model="chirp"
        ),
    )

    # 创建识别器
    operation = client.create_recognizer(request=request)
    recognizer = operation.result()

    # 读取音频文件
    with open(audio_file, "rb") as f:
        content = f.read()

    config = cloud_speech.RecognitionConfig(auto_decoding_config={})

    # 发起识别请求,直接使用创建好的区域识别器名称
    request = cloud_speech.RecognizeRequest(
        recognizer=recognizer.name, config=config, content=content
    )

    # 处理识别结果
    response = client.recognize(request=request)
    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

关键修改点说明

  • 客户端区域指定:默认的SpeechClient会连接global区域的API端点,必须通过client_options指定us-central1-speech.googleapis.com,确保客户端与目标区域匹配。
  • 识别器创建的父区域:parent参数必须设置为projects/{project_id}/locations/us-central1,与客户端区域一致,否则会出现位置不匹配的400错误。
  • 模型指定:将model参数设置为"chirp",明确使用Chirp识别模型(原代码使用的latest_long是global区域的通用模型)。

额外注意事项

  • 如果识别器已提前创建,可跳过create_recognizer步骤,直接使用正确的识别器名称路径:projects/{project_id}/locations/us-central1/recognizers/{recognizer_id}
  • 确保GCP账号拥有us-central1区域的Speech-to-Text API权限,且已启用该区域的API服务

内容的提问来源于stack exchange,提问作者M.Hossein Rahimi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:13:14