Mentranskripsikan file audio panjang menjadi teks

Halaman ini menunjukkan cara mentranskripsikan file audio yang panjang (dengan durasi lebih dari satu menit) ke teks menggunakan Speech-to-Text API dan pengenalan ucapan asinkron.

Tentang pengenalan ucapan asinkron

Pengenalan ucapan batch memulai operasi panjang pemrosesan audio. Gunakan pengenalan ucapan asinkron untuk mentranskripsikan audio yang berdurasi lebih dari 60 detik. Untuk audio berdurasi lebih pendek, pengenalan ucapan sinkron lebih cepat dan lebih mudah. Batas atas untuk pengenalan ucapan asinkron adalah 480 menit (8 jam).

Pengenalan ucapan batch hanya dapat mentranskripsikan audio yang disimpan di Cloud Storage. Output transkripsi dapat diberikan inline sebagai bagian dari respons (untuk permintaan pengenalan batch file tunggal) atau ditulis ke Cloud Storage.

Permintaan pengenalan batch menampilkan Operation yang berisi informasi tentang pemrosesan pengenalan yang sedang berlangsung atas permintaan Anda. Anda dapat melakukan polling operasi untuk mengetahui kapan operasi selesai dan transkripnya tersedia.

Sebelum memulai

  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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Speech-to-Text APIs.

    Enable the APIs

  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.

      Buka IAM
    2. Pilih project.
    3. Klik Berikan akses.
    4. Di kolom New principals, masukkan ID pengguna Anda. Ini biasanya adalah alamat email untuk Akun Google.

    5. Di daftar Pilih peran, pilih peran.
    6. Untuk memberikan peran tambahan, klik Tambahkan peran lain, lalu tambahkan setiap peran tambahan.
    7. Klik Simpan.
    8. Install the Google Cloud CLI.
    9. To initialize the gcloud CLI, run the following command:

      gcloud init
    10. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

      Go to project selector

    11. Make sure that billing is enabled for your Google Cloud project.

    12. Enable the Speech-to-Text APIs.

      Enable the APIs

    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.

        Buka IAM
      2. Pilih project.
      3. Klik Berikan akses.
      4. Di kolom New principals, masukkan ID pengguna Anda. Ini biasanya adalah alamat email untuk Akun Google.

      5. Di daftar Pilih peran, pilih peran.
      6. Untuk memberikan peran tambahan, klik Tambahkan peran lain, lalu tambahkan setiap peran tambahan.
      7. Klik Simpan.
      8. Install the Google Cloud CLI.
      9. To initialize the gcloud CLI, run the following command:

        gcloud init
      10. Library klien dapat menggunakan Kredensial Default Aplikasi untuk dengan mudah melakukan autentikasi dengan Google API dan mengirim permintaan ke API tersebut. Dengan Kredensial Default Aplikasi, Anda dapat menguji aplikasi secara lokal dan men-deploy aplikasi tanpa mengubah kode yang mendasarinya. Untuk informasi selengkapnya, lihat Lakukan autentikasi untuk menggunakan library klien.

      11. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      Selain itu, pastikan Anda telah menginstal library klien.

      Mengaktifkan akses ke Cloud Storage

      Speech-to-Text menggunakan akun layanan untuk mengakses file Anda di Cloud Storage. Secara default, akun layanan memiliki akses ke file Cloud Storage dalam project yang sama.

      Alamat email akun layanan adalah sebagai berikut:

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

      Untuk mentranskripsikan file Cloud Storage di project lain, Anda dapat memberikan peran Agen Layanan Speech-to-Text ke project layanan ini:

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

      Informasi selengkapnya tentang kebijakan IAM project tersedia di bagian Mengelola akses ke project, folder, dan organisasi.

      Anda juga dapat memberikan akses yang lebih terperinci kepada akun layanan dengan memberinya izin ke bucket Cloud Storage tertentu:

      gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
          --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com \
          --role=roles/storage.admin

      Informasi selengkapnya tentang cara mengelola akses ke Cloud Storage tersedia di bagian Membuat dan Mengelola daftar kontrol akses dalam dokumentasi Cloud Storage.

      Melakukan pengenalan batch dengan hasil inline

      Berikut adalah contoh menjalankan pengenalan ucapan batch pada file audio di Cloud Storage dan membaca hasil transkripsi secara inline dari respons:

      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 transcribe_batch_gcs_input_inline_output_v2(
          audio_uri: str,
      ) -> cloud_speech.BatchRecognizeResults:
          """Transcribes audio from a Google Cloud Storage URI using the Google Cloud Speech-to-Text API.
              The transcription results are returned inline in the response.
          Args:
              audio_uri (str): The Google Cloud Storage URI of the input audio file.
                  E.g., gs://[BUCKET]/[FILE]
          Returns:
              cloud_speech.BatchRecognizeResults: The response containing the transcription results.
          """
          # 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=audio_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[audio_uri].transcript.results:
              print(f"Transcript: {result.alternatives[0].transcript}")
      
          return response.results[audio_uri].transcript
      
      

      Melakukan pengenalan batch dan menulis hasilnya ke Cloud Storage

      Berikut adalah contoh melakukan pengenalan ucapan batch pada file audio di Cloud Storage dan membaca hasil transkripsi dari file output di Cloud Storage. Perhatikan bahwa file yang ditulis ke Cloud Storage adalah pesan BatchRecognizeResults dalam format JSON:

      Python

      import os
      
      import re
      
      from google.cloud import storage
      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
      
      
      def transcribe_batch_gcs_input_gcs_output_v2(
          audio_uri: str,
          gcs_output_path: str,
      ) -> cloud_speech.BatchRecognizeResults:
          """Transcribes audio from a Google Cloud Storage URI using the Google Cloud Speech-to-Text API.
          The transcription results are stored in another Google Cloud Storage bucket.
          Args:
              audio_uri (str): The Google Cloud Storage URI of the input audio file.
                  E.g., gs://[BUCKET]/[FILE]
              gcs_output_path (str): The Google Cloud Storage bucket URI where the output transcript will be stored.
                  E.g., gs://[BUCKET]
          Returns:
              cloud_speech.BatchRecognizeResults: The response containing the URI of the transcription results.
          """
          # 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=audio_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[audio_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
      
      

      Melakukan pengenalan batch pada beberapa file

      Berikut adalah contoh cara melakukan pengenalan ucapan batch pada beberapa file audio di Cloud Storage dan membaca hasil transkripsi dari file output di Cloud Storage:

      Python

      import os
      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
      
      PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
      
      
      def transcribe_batch_multiple_files_v2(
          audio_uris: List[str],
          gcs_output_path: str,
      ) -> cloud_speech.BatchRecognizeResponse:
          """Transcribes audio from multiple Google Cloud Storage URIs using the Google Cloud Speech-to-Text API.
          The transcription results are stored in another Google Cloud Storage bucket.
          Args:
              audio_uris (List[str]): The list of Google Cloud Storage URIs of the input audio files.
                  E.g., ["gs://[BUCKET]/[FILE]", "gs://[BUCKET]/[FILE]"]
              gcs_output_path (str): The Google Cloud Storage bucket URI where the output transcript will be stored.
                  E.g., gs://[BUCKET]
          Returns:
              cloud_speech.BatchRecognizeResponse: The response containing the URIs of the transcription results.
          """
          # 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 audio_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 audio_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
      
      

      Mengaktifkan pembuatan batch dinamis pada pengenalan batch

      Pembuatan batch dinamis memungkinkan transkripsi dengan biaya yang lebih rendah untuk latensi yang lebih tinggi. Fitur ini hanya tersedia untuk pengenalan batch.

      Berikut adalah contoh melakukan pengenalan batch pada file audio di Cloud Storage dengan mengaktifkan pembuatan batch dinamis:

      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 transcribe_batch_dynamic_batching_v2(
          audio_uri: str,
      ) -> cloud_speech.BatchRecognizeResults:
          """Transcribes audio from a Google Cloud Storage URI using dynamic batching.
          Args:
              audio_uri (str): The Cloud Storage URI of the input audio.
              E.g., gs://[BUCKET]/[FILE]
          Returns:
              cloud_speech.BatchRecognizeResults: The response containing the transcription results.
          """
          # 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=audio_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[audio_uri].transcript.results:
              print(f"Transcript: {result.alternatives[0].transcript}")
      
          return response.results[audio_uri].transcript
      
      

      Mengganti fitur pengenalan per file

      Pengenalan batch secara default menggunakan konfigurasi pengenalan yang sama untuk setiap file dalam permintaan pengenalan batch. Jika file yang berbeda memerlukan konfigurasi atau fitur yang berbeda, konfigurasi dapat diganti per file menggunakan kolom config dalam pesan [BatchRecognizeFileMetadata][batch-file -metadata-grpc]. Lihat dokumentasi pengenal untuk mengetahui contoh penggantian fitur pengenalan.

      Pembersihan

      Agar akun Google Cloud Anda tidak dikenai biaya untuk resource yang digunakan pada halaman ini, ikuti langkah-langkah berikut.

      1. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

        gcloud auth application-default revoke
      2. Optional: Revoke credentials from the gcloud CLI.

        gcloud auth revoke

      Konsol

    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

      Langkah berikutnya