Halaman ini menunjukkan cara mentranskripsikan file audio 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 maksimal 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
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Speech-to-Text APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles. -
Make sure that you have the following role or roles on the project: Cloud Speech Administrator
Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
-
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.
- For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.
Grant the roles
-
In the Google Cloud console, go to the IAM page.
Buka IAM - Pilih project.
- Klik Grant access.
-
Di kolom New principals, masukkan ID pengguna Anda. Biasanya, ini adalah ID untuk pengguna dalam workforce identity pool. Untuk mengetahui detailnya, lihat Merepresentasikan pengguna workforce pool dalam kebijakan IAM, atau hubungi administrator Anda.
- Di daftar Select a role, pilih peran.
- Untuk memberikan peran tambahan, klik Add another role, lalu tambahkan setiap peran tambahan.
- Klik Save.
Install the Google Cloud CLI.
Konfigurasi gcloud CLI agar menggunakan identitas gabungan Anda.
Untuk mengetahui informasi selengkapnya, lihat Login ke gcloud CLI dengan identitas gabungan Anda.
Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:
gcloud initLibrary 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 mengetahui informasi selengkapnya, lihat Melakukan autentikasi untuk menggunakan library klien.
Create local authentication credentials for your user account:
gcloud auth application-default login
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
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.Untuk mentranskripsikan file Cloud Storage di project lain, Anda dapat memberi akun layanan ini peran [Agen Layanan Speech-to-Text][speech-service-agent] di project lainnya:
gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech. \ --role=roles/speech.serviceAgentInformasi selengkapnya tentang kebijakan IAM project tersedia di [Mengelola akses ke project, folder, dan organisasi][manage-access].
Anda juga dapat memberi akun layanan akses yang lebih terperinci 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. \ --role=roles/storage.adminInformasi selengkapnya tentang cara mengelola akses ke Cloud Storage tersedia di bagian [Membuat dan Mengelola daftar kontrol akses][buckets-manage-acl] dalam dokumentasi Cloud Storage.
Melakukan pengenalan batch dengan hasil inline
Berikut adalah contoh cara melakukan 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. Such as 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="chirp_3", ) 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].transcriptMelakukan pengenalan batch dan menulis hasilnya ke Cloud Storage
Berikut adalah contoh cara 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
BatchRecognizeResultsdalam 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="chirp_3", ) 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_resultsMelakukan 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. Such as ["gs://[BUCKET]/[FILE]", "gs://[BUCKET]/[FILE]"] gcs_output_path (str): The Google Cloud Storage bucket URI where the output transcript is stored. Such as 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="chirp_3", ) 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 responseMengaktifkan 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="chirp_3", ) 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].transcriptMengganti 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
configdalam pesanBatchRecognizeFileMetadata. Lihat dokumentasi pengenal untuk mengetahui contoh penggantian fitur pengenalan.Pembersihan
Agar akun Google Cloud Anda tidak dikenai biaya untuk resource yang digunakan di halaman ini, ikuti langkah-langkah berikut.
-
Optional: Revoke the authentication credentials that you created, and delete the local credential file.
gcloud auth application-default revoke
-
Optional: Revoke credentials from the gcloud CLI.
gcloud auth revoke
Konsol
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
gcloud
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
Langkah berikutnya
- Lihat dokumentasi referensi untuk pengenalan batch.
- Pelajari cara mentranskripsikan audio streaming.
- Pelajari cara mentranskripsikan file audio panjang.
- Untuk performa terbaik, akurasi, dan tips lainnya, lihat dokumentasi praktik terbaik.
-