识别器

Speech-to-Text V2 支持名为识别器的 Google Cloud 资源。识别器代表存储的和可重复使用的识别配置。您可以使用它们对应用的转写或流量进行逻辑分组。

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Speech-to-Text API。

    启用 API

  5. 确保您拥有项目的以下一个或多个角色: Cloud Speech Administrator

    检查角色

    1. 在 Google Cloud 控制台中,前往 IAM 页面。

      转到 IAM
    2. 选择项目。
    3. 主账号列中,找到您的电子邮件地址所在的行。

      如果您的电子邮件地址不在此列,则表示您没有任何角色。

    4. 在您的电子邮件地址所在的行对应的角色列中,检查角色列表是否包含所需的角色。

    授予角色

    1. 在 Google Cloud 控制台中,前往 IAM 页面。

      转到 IAM
    2. 选择项目。
    3. 点击 授予访问权限
    4. 新的主账号字段中,输入您的电子邮件地址。
    5. 选择角色列表中,选择一个角色。
    6. 如需授予其他角色,请点击 添加其他角色,然后添加其他各个角色。
    7. 点击 Save(保存)。
  6. 安装 Google Cloud CLI。
  7. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  8. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  9. 确保您的 Google Cloud 项目已启用结算功能

  10. 启用 Speech-to-Text API。

    启用 API

  11. 确保您拥有项目的以下一个或多个角色: Cloud Speech Administrator

    检查角色

    1. 在 Google Cloud 控制台中,前往 IAM 页面。

      转到 IAM
    2. 选择项目。
    3. 主账号列中,找到您的电子邮件地址所在的行。

      如果您的电子邮件地址不在此列,则表示您没有任何角色。

    4. 在您的电子邮件地址所在的行对应的角色列中,检查角色列表是否包含所需的角色。

    授予角色

    1. 在 Google Cloud 控制台中,前往 IAM 页面。

      转到 IAM
    2. 选择项目。
    3. 点击 授予访问权限
    4. 新的主账号字段中,输入您的电子邮件地址。
    5. 选择角色列表中,选择一个角色。
    6. 如需授予其他角色,请点击 添加其他角色,然后添加其他各个角色。
    7. 点击 Save(保存)。
  12. 安装 Google Cloud CLI。
  13. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  14. Client libraries can use Application Default Credentials to easily authenticate with Google APIs and send requests to those APIs. With Application Default Credentials, you can test your application locally and deploy it without changing the underlying code. For more information, see Authenticate for using client libraries.

  15. 为您的 Google 账号创建本地身份验证凭据:

    gcloud auth application-default login

此外,请确保您已安装客户端库

了解识别器

识别器是可配置且可重复使用的识别配置。使用常用识别配置创建识别器有助于简化和减小识别请求的大小。

识别器的核心元素是其默认配置。这是此识别器执行的每个识别请求的配置。您可以为每个请求替换此默认值。为给定识别器的各项请求保留所需功能的默认配置,同时为特定请求重写特定功能。

尽可能频繁地重复使用识别器。为每个请求创建一个识别器会显著增加应用的延迟时间,并消耗资源配额。在集成和设置期间不要频繁创建识别器,而是可以随后将其重复用于识别请求。

创建识别器

以下示例展示了如何创建可用于发送识别请求的识别器:

Python

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

def create_recognizer(project_id: str, recognizer_id: str) -> cloud_speech.Recognizer:
    # Instantiates a client
    client = SpeechClient()

    request = cloud_speech.CreateRecognizerRequest(
        parent=f"projects/{project_id}/locations/global",
        recognizer_id=recognizer_id,
        recognizer=cloud_speech.Recognizer(
            default_recognition_config=cloud_speech.RecognitionConfig(
                language_codes=["en-US"], model="long"
            ),
        ),
    )

    operation = client.create_recognizer(request=request)
    recognizer = operation.result()

    print("Created Recognizer:", recognizer.name)
    return recognizer

使用现有识别器发送请求

以下示例展示了如何使用同一识别器发送多个识别请求:

Python

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

def transcribe_reuse_recognizer(
    project_id: str,
    recognizer_id: str,
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file using an existing recognizer."""
    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        content = f.read()

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{project_id}/locations/global/recognizers/{recognizer_id}",
        content=content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

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

    return response

启用识别器中的功能

识别器可用于在识别过程中启用各种功能,例如自动加注标点符号脏话过滤

以下示例展示了如何在识别器中启用自动加注标点符号功能,该示例在使用此识别器的识别请求中启用自动加注标点符号功能:

Python

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

def transcribe_feature_in_recognizer(
    project_id: str,
    recognizer_id: str,
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file using an existing recognizer."""
    # Instantiates a client
    client = SpeechClient()

    request = cloud_speech.CreateRecognizerRequest(
        parent=f"projects/{project_id}/locations/global",
        recognizer_id=recognizer_id,
        recognizer=cloud_speech.Recognizer(
            default_recognition_config=cloud_speech.RecognitionConfig(
                auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
                language_codes=["en-US"],
                model="latest_long",
                features=cloud_speech.RecognitionFeatures(
                    enable_automatic_punctuation=True,
                ),
            ),
        ),
    )

    operation = client.create_recognizer(request=request)
    recognizer = operation.result()

    print("Created Recognizer:", recognizer.name)

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        content = f.read()

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{project_id}/locations/global/recognizers/{recognizer_id}",
        content=content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

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

    return response

替换识别请求中的识别器功能

以下示例展示了如何在识别器中启用多项功能,但为此识别请求停用自动加注标点符号功能:

Python

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech
from google.protobuf.field_mask_pb2 import FieldMask

def transcribe_override_recognizer(
    project_id: str,
    recognizer_id: str,
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file using an existing recognizer."""
    # Instantiates a client
    client = SpeechClient()

    request = cloud_speech.CreateRecognizerRequest(
        parent=f"projects/{project_id}/locations/global",
        recognizer_id=recognizer_id,
        recognizer=cloud_speech.Recognizer(
            default_recognition_config=cloud_speech.RecognitionConfig(
                auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
                language_codes=["en-US"],
                model="latest_long",
                features=cloud_speech.RecognitionFeatures(
                    enable_automatic_punctuation=True,
                    enable_word_time_offsets=True,
                ),
            ),
        ),
    )

    operation = client.create_recognizer(request=request)
    recognizer = operation.result()

    print("Created Recognizer:", recognizer.name)

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        content = f.read()

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{project_id}/locations/global/recognizers/{recognizer_id}",
        config=cloud_speech.RecognitionConfig(
            features=cloud_speech.RecognitionFeatures(
                enable_word_time_offsets=False,
            ),
        ),
        config_mask=FieldMask(paths=["features.enable_word_time_offsets"]),
        content=content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

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

    return response

在不使用识别器的情况下发送请求

识别器在识别请求中是可选的。如需在不使用识别器的情况下发出请求,只需在发出请求的位置使用识别器资源 ID _。示例如下:

Python

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

def quickstart_v2(
    project_id: str,
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file."""
    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        content = f.read()

    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        language_codes=["en-US"],
        model="long",
    )

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{project_id}/locations/global/recognizers/_",
        config=config,
        content=content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

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

    return response

清理

为避免因本页中使用的资源导致您的 Google Cloud 账号产生费用,请按照以下步骤操作。

  1. 可选:撤消您创建的身份验证凭据,并删除本地凭据文件。

    gcloud auth application-default revoke
  2. 可选:从 gcloud CLI 撤消凭据。

    gcloud auth revoke

控制台

  • 在 Google Cloud 控制台中,进入管理资源页面。

    转到“管理资源”

  • 在项目列表中,选择要删除的项目,然后点击删除
  • 在对话框中输入项目 ID,然后点击关闭以删除项目。
  • gcloud

    删除 Google Cloud 项目:

    gcloud projects delete PROJECT_ID

    后续步骤