長い音声ファイルをテキストに変換する

このページでは、Speech-to-Text API と非同期音声認識を使用して、長い音声ファイル(1 分を超える)をテキストに変換する方法について説明します。

非同期音声認識について

一括音声認識では、音声処理オペレーションの長時間実行が開始されます。60 秒を超える音声を文字に変換するには、非同期音声認識を使用します。短い音声の場合は、同期音声認識を使用したほうが早くて簡単です。非同期音声認識の上限は 480 分(8 時間)です。

一括音声認識では、Cloud Storage に保存されている音声のみ文字変換できます。音声文字変換の出力は、レスポンスにインラインで送信することも(単一ファイルの一括認識リクエストの場合)、Cloud Storage に書き込むこともできます。

一括認識リクエストは、リクエストの継続的な認識処理に関する情報を含む Operation を返します。オペレーションをポーリングすると、オペレーションの完了と音声文字変換テキストのタイミングを確認できます。

始める前に

  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

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

      Cloud Storage へのアクセスを有効にする

      Speech-to-Text は、サービス アカウントを使用して Cloud Storage 内のファイルにアクセスします。デフォルトでは、サービス アカウントは同じプロジェクト内の Cloud Storage ファイルにアクセスできます。

      サービス アカウントのメールアドレスは次のとおりです。

      service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com
      

      別のプロジェクトの Cloud Storage ファイルを音声文字変換するには、このサービス アカウントにもう一方のプロジェクトの Speech-to-Text サービス エージェント ロールを付与します。

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com \
          --role=roles/speech.serviceAgent
      

      プロジェクトの IAM ポリシーの詳細については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

      サービス アカウントにさらにきめ細かくアクセス権を付与するには、特定の Cloud Storage バケットへの権限を付与します。

      gsutil iam ch serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com:admin \
          gs://BUCKET_NAME
      

      Cloud Storage へのアクセスの管理の詳細については、Cloud Storage ドキュメントのアクセス制御リストの作成と管理をご覧ください。

      一括認識を実行してインラインで結果を読み取る

      Cloud Storage の音声ファイルに対して一括音声認識を実行し、レスポンスから音声文字変換結果をインラインで読み取る例を次に示します。

      Python

      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      def transcribe_batch_gcs_input_inline_output_v2(
          project_id: str,
          gcs_uri: str,
      ) -> cloud_speech.BatchRecognizeResults:
          """Transcribes audio from a Google Cloud Storage URI.
      
          Args:
              project_id: The Google Cloud project ID.
              gcs_uri: The Google Cloud Storage URI.
      
          Returns:
              The RecognizeResponse.
          """
          # Instantiates a client
          client = SpeechClient()
      
          config = cloud_speech.RecognitionConfig(
              auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
              language_codes=["en-US"],
              model="long",
          )
      
          file_metadata = cloud_speech.BatchRecognizeFileMetadata(uri=gcs_uri)
      
          request = cloud_speech.BatchRecognizeRequest(
              recognizer=f"projects/{project_id}/locations/global/recognizers/_",
              config=config,
              files=[file_metadata],
              recognition_output_config=cloud_speech.RecognitionOutputConfig(
                  inline_response_config=cloud_speech.InlineOutputConfig(),
              ),
          )
      
          # Transcribes the audio into text
          operation = client.batch_recognize(request=request)
      
          print("Waiting for operation to complete...")
          response = operation.result(timeout=120)
      
          for result in response.results[gcs_uri].transcript.results:
              print(f"Transcript: {result.alternatives[0].transcript}")
      
          return response.results[gcs_uri].transcript
      
      

      一括認識を実行して結果を Cloud Storage に書き込む

      次に、Cloud Storage の音声ファイルに対して一括音声認識を実行し、Cloud Storage の出力ファイルから音声文字変換結果を読み取る例を示します。Cloud Storage に書き込まれるファイルは JSON 形式の BatchRecognizeResults メッセージです。

      Python

      import re
      
      from google.cloud import storage
      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      def transcribe_batch_gcs_input_gcs_output_v2(
          project_id: str,
          gcs_uri: str,
          gcs_output_path: str,
      ) -> cloud_speech.BatchRecognizeResults:
          """Transcribes audio from a Google Cloud Storage URI.
      
          Args:
              project_id: The Google Cloud project ID.
              gcs_uri: The Google Cloud Storage URI.
              gcs_output_path: The Cloud Storage URI to which to write the transcript.
      
          Returns:
              The BatchRecognizeResults message.
          """
          # Instantiates a client
          client = SpeechClient()
      
          config = cloud_speech.RecognitionConfig(
              auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
              language_codes=["en-US"],
              model="long",
          )
      
          file_metadata = cloud_speech.BatchRecognizeFileMetadata(uri=gcs_uri)
      
          request = cloud_speech.BatchRecognizeRequest(
              recognizer=f"projects/{project_id}/locations/global/recognizers/_",
              config=config,
              files=[file_metadata],
              recognition_output_config=cloud_speech.RecognitionOutputConfig(
                  gcs_output_config=cloud_speech.GcsOutputConfig(
                      uri=gcs_output_path,
                  ),
              ),
          )
      
          # Transcribes the audio into text
          operation = client.batch_recognize(request=request)
      
          print("Waiting for operation to complete...")
          response = operation.result(timeout=120)
      
          file_results = response.results[gcs_uri]
      
          print(f"Operation finished. Fetching results from {file_results.uri}...")
          output_bucket, output_object = re.match(
              r"gs://([^/]+)/(.*)", file_results.uri
          ).group(1, 2)
      
          # Instantiates a Cloud Storage client
          storage_client = storage.Client()
      
          # Fetch results from Cloud Storage
          bucket = storage_client.bucket(output_bucket)
          blob = bucket.blob(output_object)
          results_bytes = blob.download_as_bytes()
          batch_recognize_results = cloud_speech.BatchRecognizeResults.from_json(
              results_bytes, ignore_unknown_fields=True
          )
      
          for result in batch_recognize_results.results:
              print(f"Transcript: {result.alternatives[0].transcript}")
      
          return batch_recognize_results
      
      

      複数のファイルに対して一括認識を実行する

      次に、Cloud Storage の複数の音声ファイルに対して一括音声認識を実行し、Cloud Storage の出力ファイルから音声文字変換結果を読み取る例を示します。

      Python

      import re
      from typing import List
      
      from google.cloud import storage
      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      def transcribe_batch_multiple_files_v2(
          project_id: str,
          gcs_uris: List[str],
          gcs_output_path: str,
      ) -> cloud_speech.BatchRecognizeResponse:
          """Transcribes audio from a Google Cloud Storage URI.
      
          Args:
              project_id: The Google Cloud project ID.
              gcs_uris: The Google Cloud Storage URIs to transcribe.
              gcs_output_path: The Cloud Storage URI to which to write the transcript.
      
          Returns:
              The BatchRecognizeResponse message.
          """
          # Instantiates a client
          client = SpeechClient()
      
          config = cloud_speech.RecognitionConfig(
              auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
              language_codes=["en-US"],
              model="long",
          )
      
          files = [cloud_speech.BatchRecognizeFileMetadata(uri=uri) for uri in gcs_uris]
      
          request = cloud_speech.BatchRecognizeRequest(
              recognizer=f"projects/{project_id}/locations/global/recognizers/_",
              config=config,
              files=files,
              recognition_output_config=cloud_speech.RecognitionOutputConfig(
                  gcs_output_config=cloud_speech.GcsOutputConfig(
                      uri=gcs_output_path,
                  ),
              ),
          )
      
          # Transcribes the audio into text
          operation = client.batch_recognize(request=request)
      
          print("Waiting for operation to complete...")
          response = operation.result(timeout=120)
      
          print("Operation finished. Fetching results from:")
          for uri in gcs_uris:
              file_results = response.results[uri]
              print(f"  {file_results.uri}...")
              output_bucket, output_object = re.match(
                  r"gs://([^/]+)/(.*)", file_results.uri
              ).group(1, 2)
      
              # Instantiates a Cloud Storage client
              storage_client = storage.Client()
      
              # Fetch results from Cloud Storage
              bucket = storage_client.bucket(output_bucket)
              blob = bucket.blob(output_object)
              results_bytes = blob.download_as_bytes()
              batch_recognize_results = cloud_speech.BatchRecognizeResults.from_json(
                  results_bytes, ignore_unknown_fields=True
              )
      
              for result in batch_recognize_results.results:
                  print(f"     Transcript: {result.alternatives[0].transcript}")
      
          return response
      
      

      一括認識で動的一括処理を有効にする

      動的一括処理を使用すると、より高いレイテンシに対して低コストで音声文字変換を行うことができます。この機能はバッチ認識でのみ使用できます。

      次に、動的一括処理を有効にして Cloud Storage の音声ファイルに対して一括認識を実行する例を示します。

      Python

      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      def transcribe_batch_dynamic_batching_v2(
          project_id: str,
          gcs_uri: str,
      ) -> cloud_speech.BatchRecognizeResults:
          """Transcribes audio from a Google Cloud Storage URI.
      
          Args:
              project_id: The Google Cloud project ID.
              gcs_uri: The Google Cloud Storage URI.
      
          Returns:
              The RecognizeResponse.
          """
          # Instantiates a client
          client = SpeechClient()
      
          config = cloud_speech.RecognitionConfig(
              auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
              language_codes=["en-US"],
              model="long",
          )
      
          file_metadata = cloud_speech.BatchRecognizeFileMetadata(uri=gcs_uri)
      
          request = cloud_speech.BatchRecognizeRequest(
              recognizer=f"projects/{project_id}/locations/global/recognizers/_",
              config=config,
              files=[file_metadata],
              recognition_output_config=cloud_speech.RecognitionOutputConfig(
                  inline_response_config=cloud_speech.InlineOutputConfig(),
              ),
              processing_strategy=cloud_speech.BatchRecognizeRequest.ProcessingStrategy.DYNAMIC_BATCHING,
          )
      
          # Transcribes the audio into text
          operation = client.batch_recognize(request=request)
      
          print("Waiting for operation to complete...")
          response = operation.result(timeout=120)
      
          for result in response.results[gcs_uri].transcript.results:
              print(f"Transcript: {result.alternatives[0].transcript}")
      
          return response.results[gcs_uri].transcript
      
      

      ファイルごとに認識機能をオーバーライドする

      一括認識のデフォルトでは、バッチ認識リクエストのファイルごとに同じ認識構成が使用されます。さまざまなファイルで異なる構成や機能が必要な場合は、[BatchRecognizeFileMetadata][batch-file-metadata-grpc] メッセージの config フィールドを使用して、ファイルごとに構成をオーバーライドできます。認識機能をオーバーライドする例については、認識機能のドキュメントをご覧ください。

      クリーンアップ

      このページで使用したリソースについて、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

      次のステップ