Esta página demonstra como transcrever ficheiros de áudio longos (com mais de um minuto) para texto através da API Speech-to-Text e do reconhecimento de voz assíncrono.
Acerca do reconhecimento de voz assíncrono
O reconhecimento de voz em lote inicia uma operação de processamento de áudio de longa duração. Use o reconhecimento de voz assíncrono para transcrever áudio com mais de 60 segundos. Para áudio mais curto, o reconhecimento de voz síncrono é mais rápido e simples. O limite máximo para o reconhecimento de voz assíncrono é de 480 minutos (8 horas).
O reconhecimento de voz em lote só consegue transcrever áudio armazenado no armazenamento na nuvem. O resultado da transcrição pode ser fornecido inline na resposta (para pedidos de reconhecimento em lote de ficheiro único) ou escrito no Cloud Storage.
O pedido de reconhecimento em lote devolve um Operation
que contém informações sobre o processamento de reconhecimento em curso do seu pedido. Pode consultar a operação para saber quando a operação está concluída e as transcrições estão disponíveis.
Antes de começar
-
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.
Aceder ao IAM - Selecione o projeto.
- Clique em Conceder acesso.
-
No campo Novos responsáveis, introduza o identificador do utilizador. Normalmente, este é o identificador de um utilizador num Workload Identity Pool. Para ver detalhes, consulte Represente utilizadores do pool de força de trabalho em políticas de IAM ou contacte o seu administrador.
- Clique em Selecionar uma função e, de seguida, pesquise a função.
- Para conceder funções adicionais, clique em Adicionar outra função e adicione cada função adicional.
- Clique em Guardar.
Install the Google Cloud CLI.
Configure a CLI gcloud para usar a sua identidade federada.
Para mais informações, consulte o artigo Inicie sessão na CLI gcloud com a sua identidade federada.
Para inicializar a CLI gcloud, execute o seguinte comando:
gcloud initAs bibliotecas cliente podem usar as Credenciais padrão da aplicação para fazer a autenticação facilmente com as APIs Google e enviar pedidos para essas APIs. Com as credenciais predefinidas da aplicação, pode testar a sua aplicação localmente e implementá-la sem alterar o código subjacente. Para mais informações, consulte o artigo Autentique-se para usar bibliotecas de cliente.
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.
Certifique-se também de que instalou a biblioteca de cliente.
Ative o acesso ao Cloud Storage
O Speech-to-Text usa uma conta de serviço para aceder aos seus ficheiros no Cloud Storage. Por predefinição, a conta de serviço tem acesso aos ficheiros do Cloud Storage no mesmo projeto.
O endereço de email da conta de serviço é o seguinte:
service-PROJECT_NUMBER@gcp-sa-speech.Para transcrever ficheiros do Cloud Storage noutro projeto, pode atribuir a esta conta de serviço a função [Agente do serviço Speech-to-Text][speech-service-agent] no outro projeto:
gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech. \ --role=roles/speech.serviceAgentPode encontrar mais informações sobre a política de IAM do projeto em [Gerir o acesso a projetos, pastas e organizações][manage-access].
Também pode conceder à conta de serviço um acesso mais detalhado, concedendo-lhe autorização para um contentor do Cloud Storage específico:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \ --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech. \ --role=roles/storage.adminPode encontrar mais informações sobre a gestão do acesso ao Cloud Storage em [Crie e faça a gestão de listas de controlo de acesso][buckets-manage-acl] na documentação do Cloud Storage.
Realize o reconhecimento em lote com resultados inline
Segue-se um exemplo de como realizar o reconhecimento de voz em lote num ficheiro de áudio no Cloud Storage e ler os resultados da transcrição inline a partir da resposta:
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].transcriptRealize o reconhecimento em lote e escreva os resultados no Cloud Storage
Segue-se um exemplo de como realizar o reconhecimento de voz em lote num ficheiro de áudio no Cloud Storage e ler os resultados da transcrição do ficheiro de saída no Cloud Storage. Tenha em atenção que o ficheiro escrito no Cloud Storage é uma mensagem
BatchRecognizeResultsno formato 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_resultsRealize o reconhecimento em lote em vários ficheiros
Segue-se um exemplo de como realizar o reconhecimento de voz em lote em vários ficheiros de áudio no Cloud Storage e ler os resultados da transcrição dos ficheiros de saída no 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 responseAtive o processamento em lote dinâmico no reconhecimento em lote
O processamento em lote dinâmico permite uma transcrição de menor custo para uma latência mais elevada. Esta funcionalidade só está disponível para o reconhecimento em lote.
Segue-se um exemplo de como realizar o reconhecimento em lote num ficheiro de áudio no Cloud Storage com o processamento em lote dinâmico ativado:
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].transcriptSubstitua as funcionalidades de reconhecimento por ficheiro
Por predefinição, o reconhecimento em lote usa a mesma configuração de reconhecimento para cada ficheiro no pedido de reconhecimento em lote. Se diferentes ficheiros exigirem uma configuração ou funcionalidades diferentes, a configuração pode ser substituída por ficheiro através do campo
configna mensagemBatchRecognizeFileMetadata. Consulte a documentação dos reconhecedores para ver um exemplo de substituição das funcionalidades de reconhecimento.Limpar
Para evitar incorrer em cobranças na sua Google Cloud conta pelos recursos usados nesta página, siga estes passos.
-
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
Consola
- 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.
O que se segue?
- Consulte a documentação de referência para o reconhecimento em lote.
- Saiba como transcrever áudio em streaming.
- Saiba como transcrever ficheiros de áudio curtos.
- Para ver o melhor desempenho, precisão e outras sugestões, consulte a documentação de práticas recomendadas.
-