指定区域级端点

Speech-to-Text 提供美国和欧盟区域 API 端点。如果使用区域端点,则静态数据和使用中的数据都将存放在欧洲大陆边界或美国内。如果必须控制数据的位置以符合当地法规的要求,则指定端点很重要。该 API 的行为功能在功能上没有变化。

使用区域端点时,请务必在 parent 字符串中包含匹配的 useu 位置。如需详细了解如何配置识别请求正文,请参阅 RecognitionConfig 文档。

协议

如需使用区域级端点执行语音识别,请运行下表中的相应命令以配置正确的端点:

多区域 端点替换
欧盟 $ export CLOUD_SPEECH_ENDPOINT=https://eu-speech.googleapis.com
美国 $ export CLOUD_SPEECH_ENDPOINT=https://us-speech.googleapis.com

以下代码示例演示了如何发送 recognize request 以将所有数据都限于指定的区域中。可以使用 EUUS 区域端点替换 CLOUD_SPEECH_ENDPOINT 变量。


$ curl   -H "Content-Type: application/json"  \
         -H  "Authorization: Bearer "$(gcloud auth print-access-token)   \
          $CLOUD_SPEECH_ENDPOINT/v1/speech:recognize \
         --data "{
        'config': {
            'encoding': 'LINEAR16',
            'languageCode': 'en-US'
        },
        'audio': {
            'uri':'gs://speech-samples-00/commercial_mono.wav'
        }
    }"

此示例使用 Google Cloud CLI 为您的用户账号生成凭据。如需了解如何安装和初始化 gcloud CLI,请参阅快速入门

请求正文中提供的音频内容采用 base64 编码。如需详细了解如何对音频执行 base64 编码,请参阅 Base64 编码音频内容。如需详细了解 content 字段,请参阅 RecognitionAudio

gcloud

以下命令设置区域端点:

多区域 端点替换
欧盟 gcloud config set api_endpoint_overrides/speech https://eu-speech.googleapis.com/
美国 gcloud config set api_endpoint_overrides/speech https://us-speech.googleapis.com/

设置区域端点后,当您发送后续的 recognize requests 时,所有数据都将限于指定的区域。以下示例演示了识别请求。

$ gcloud ml speech recognize gs://cloud-samples-tests/speech/brooklyn.flac \
    --language-code=en-US --log-http

Python

如需了解如何安装和使用 Speech-to-Text 客户端库,请参阅 Speech-to-Text 客户端库。如需了解详情,请参阅 Speech-to-Text Python API 参考文档

如需向 Speech-to-Text 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


# Imports the Google Cloud client library
from google.api_core import client_options
from google.cloud import speech

def sync_recognize_with_multi_region_gcs() -> speech.RecognizeResponse:
    """Recognizes speech synchronously in the GCS bucket."""

    # Instantiates a client

    # Pass an additional argument, ClientOptions, to specify the new endpoint.
    _client_options = client_options.ClientOptions(
        api_endpoint="eu-speech.googleapis.com"
    )

    client = speech.SpeechClient(client_options=_client_options)

    # The name of the audio file to transcribe
    gcs_uri = "gs://cloud-samples-data/speech/brooklyn_bridge.raw"

    audio = speech.RecognitionAudio(uri=gcs_uri)

    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
    )

    # Detects speech in the audio file
    response = client.recognize(config=config, audio=audio)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response.results