認識ツール

Speech-to-Text V2 は、認識ツールと呼ばれる Google Cloud リソースをサポートしています。認識ツールは、保存され再利用可能な認識構成を表します。認識ツールを使用して、アプリケーションの音声文字変換やトラフィックを論理的にグループ化できます。

始める前に

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Speech-to-Text API を有効にします。

    API を有効にする

  5. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role colunn to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      [IAM] に移動
    2. プロジェクトを選択します。
    3. [ アクセスを許可] をクリックします。
    4. [新しいプリンシパル] フィールドに、ユーザー ID を入力します。 これは通常、Google アカウントのメールアドレスです。

    5. [ロールを選択] リストでロールを選択します。
    6. 追加のロールを付与するには、 [別のロールを追加] をクリックして各ロールを追加します。
    7. [保存] をクリックします。
    8. Install the Google Cloud CLI.
    9. To initialize the gcloud CLI, run the following command:

      gcloud init
    10. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

      プロジェクト セレクタに移動

    11. Google Cloud プロジェクトで課金が有効になっていることを確認します

    12. Speech-to-Text API を有効にします。

      API を有効にする

    13. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

      Check for the roles

      1. In the Google Cloud console, go to the IAM page.

        Go to IAM
      2. Select the project.
      3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

      4. For all rows that specify or include you, check the Role colunn to see whether the list of roles includes the required roles.

      Grant the roles

      1. In the Google Cloud console, go to the IAM page.

        [IAM] に移動
      2. プロジェクトを選択します。
      3. [ アクセスを許可] をクリックします。
      4. [新しいプリンシパル] フィールドに、ユーザー ID を入力します。 これは通常、Google アカウントのメールアドレスです。

      5. [ロールを選択] リストでロールを選択します。
      6. 追加のロールを付与するには、 [別のロールを追加] をクリックして各ロールを追加します。
      7. [保存] をクリックします。
      8. Install the Google Cloud CLI.
      9. To initialize the gcloud CLI, run the following command:

        gcloud init
      10. クライアント ライブラリは、アプリケーションのデフォルト認証情報を使用することによって、Google API で簡単に認証を行い、これらの API にリクエストを送信できます。アプリケーションのデフォルト認証情報を使用すると、ベースとなるコードを変更することなく、ローカルでのアプリケーションのテストやアプリケーションのデプロイが可能です。詳しくは、<atrack-type="commonincludes" l10n-attrs-original-order="href,track-type,track-name" l10n-encrypted-href="WDE63JFVMK0YqIWBqG8nCycgwkRfOeEqRvzYs1N+2tJUEhcZvE5VtDH5LoWw0lj/" track-name="referenceLink">クライアント ライブラリを使用して認証する</atrack-type="commonincludes">をご覧ください。

      11. Create local authentication credentials for your user account:

        gcloud auth application-default login

      また、クライアント ライブラリがインストールされていることを確認してください。

      認識ツールについて

      認識ツールは構成可能で再利用可能な認識構成です。頻繁に使用される認識構成を使用して認識ツールを作成すると、認識リクエストを簡素化し、リクエストのサイズを削減できます。

      認識ツールの重要な要素は、デフォルト構成です。これは、この認識ツールが実行するすべての認識リクエストの構成です。このデフォルト値は、リクエストごとにオーバーライドできます。特定の認識ツールのリクエストで必要となる機能のデフォルト構成をそのまま使用する場合もあれば、特定のリクエストで特定の機能をオーバーライドする場合もあります。

      認識ツールをできる限り再利用するようにしてください。リクエストごとに認識ツールを作成すると、アプリケーションのレイテンシが大幅に増加し、リソースの割り当てを消費します。統合や設定の際に少数の認識ツールを作成し、認識リクエストではそれらを再利用するようにしてください。

      認識ツールを作成する

      認識リクエストの送信の際に使用できる認識ツールを作成する例を次に示します。

      Python

      import os
      
      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
      
      
      def create_recognizer(recognizer_id: str) -> cloud_speech.Recognizer:
          """Сreates a recognizer with an unique ID and default recognition configuration.
          Args:
              recognizer_id (str): The unique identifier for the recognizer to be created.
          Returns:
              cloud_speech.Recognizer: The created recognizer object with configuration.
          """
          # 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"
                  ),
              ),
          )
          # Sends the request to create a recognizer and waits for the operation to complete
          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

      import os
      
      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
      
      
      def quickstart_v2(audio_file: str) -> cloud_speech.RecognizeResponse:
          """Transcribe an audio file.
          Args:
              audio_file (str): Path to the local audio file to be transcribed.
          Returns:
              cloud_speech.RecognizeResponse: The response from the recognize request, containing
              the transcription results
          """
          # Reads a file as bytes
          with open(audio_file, "rb") as f:
              audio_content = f.read()
      
          # Instantiates a client
          client = SpeechClient()
      
          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=audio_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

      コンソール

    14. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    15. In the project list, select the project that you want to delete, and then click Delete.
    16. In the dialog, type the project ID, and then click Shut down to delete the project.
    17. gcloud

      Delete a Google Cloud project:

      gcloud projects delete PROJECT_ID

      次のステップ