Transcrever arquivos de áudio longos em texto

Nesta página, veja como transcrever arquivos de áudio longos (com mais de um minuto) usando a API Speech-to-Text e o reconhecimento de fala assíncrono.

Sobre o reconhecimento de fala assíncrono

O reconhecimento de fala em lote inicia uma operação de processamento de áudio de longa duração. Use o reconhecimento de fala assíncrono para transcrever áudios com mais de 60 segundos. Para áudios mais curtos, o reconhecimento de fala síncrono é mais rápido e mais simples. O limite máximo para o reconhecimento de fala assíncrono é de 480 minutos (8 horas).

O reconhecimento de fala em lote só é capaz de transcrever áudio armazenado no Cloud Storage. A saída da transcrição pode ser fornecida inline na resposta (para solicitações de reconhecimento em lote de arquivo único) ou gravada no Cloud Storage.

A solicitação de reconhecimento em lote retorna um Operation que contém informações sobre o processamento do reconhecimento contínuo da solicitação. É possível pesquisar a operação para saber quando ela foi concluída e se as transcrições estão disponíveis.

Antes de começar

  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. Verifique se a cobrança está ativada para o seu projeto do Google Cloud.

  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.

      Acessar o IAM
    2. Selecionar um projeto.
    3. Clique em CONCEDER ACESSO.
    4. No campo Novos principais, insira seu identificador de usuário. Normalmente, é o endereço de e-mail de uma Conta do Google.

    5. Na lista Selecionar um papel, escolha um.
    6. Para conceder outros papéis, clique em Adicionar outro papel e adicione cada papel adicional.
    7. Clique em Salvar.
    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. Verifique se a cobrança está ativada para o seu projeto do Google Cloud.

    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.

        Acessar o IAM
      2. Selecionar um projeto.
      3. Clique em CONCEDER ACESSO.
      4. No campo Novos principais, insira seu identificador de usuário. Normalmente, é o endereço de e-mail de uma Conta do Google.

      5. Na lista Selecionar um papel, escolha um.
      6. Para conceder outros papéis, clique em Adicionar outro papel e adicione cada papel adicional.
      7. Clique em Salvar.
      8. Install the Google Cloud CLI.
      9. To initialize the gcloud CLI, run the following command:

        gcloud init
      10. As bibliotecas de cliente podem usar o Application Default Credentials para autenticar facilmente com as APIs do Google e enviar solicitações para essas APIs. Com esse serviço, é possível testar seu aplicativo localmente e implantá-lo sem alterar o código subjacente. Par amais informações, consulte Faça a autenticação para usar as bibliotecas do cliente.

      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.

      Verifique também se você instalou a biblioteca de cliente.

      Ativar acesso ao Cloud Storage

      O Speech-to-Text usa uma conta de serviço para acessar os arquivos no Cloud Storage. Por padrão, a conta de serviço tem acesso aos arquivos do Cloud Storage no mesmo projeto.

      O endereço de e-mail da conta de serviço é:

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

      Para transcrever arquivos do Cloud Storage em outro projeto, conceda a essa conta de serviço o papel Agente de serviço do Speech-to-Text no outro projeto:

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

      Mais informações sobre a política de IAM de projetos estão disponíveis em Gerenciar acesso a projetos, pastas e organizações.

      Também é possível atribuir à conta de serviço um acesso mais granular, concedendo permissão a um bucket específico do Cloud Storage:

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

      Mais informações sobre como gerenciar o acesso ao Cloud Storage estão disponíveis em Criar e gerenciar listas de controle de acesso na documentação do Cloud Storage.

      Executar reconhecimento em lote com resultados inline

      Veja um exemplo de reconhecimento de fala em lote em um arquivo de áudio no Cloud Storage e leitura dos resultados de transcrição inline da resposta:

      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
      
      

      Executar reconhecimento em lote e gravar resultados no Cloud Storage

      Veja um exemplo de reconhecimento de fala em lote em um arquivo de áudio no Cloud Storage e leitura dos resultados de transcrição do arquivo de saída no Cloud Storage. Observe que o arquivo gravado no Cloud Storage é uma mensagem BatchRecognizeResults no formato JSON:

      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
      
      

      Realizar reconhecimento em lote em vários arquivos

      Veja um exemplo de reconhecimento de fala em lote em vários arquivos de áudio no Cloud Storage e leitura dos resultados de transcrição dos arquivos de saída no 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
      
      

      Ativar lotes dinâmicos no reconhecimento em lote

      Os lotes dinâmicos permitem uma transcrição mais barata para maior latência. Esse recurso está disponível apenas para reconhecimento em lote.

      Veja um exemplo de reconhecimento em lote em um arquivo de áudio no Cloud Storage com lote dinâmico ativado:

      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
      
      

      Substituir recursos de reconhecimento por arquivo

      Por padrão, a identificação em lote usa a mesma configuração para cada arquivo na solicitação de identificação em lote. Se arquivos diferentes exigirem configurações ou recursos diferentes, a configuração poderá ser substituída por arquivo usando o campo config na mensagem [BatchRecognizeFileMetadata][batch-file-metadata-grpc]. Consulte a documentação dos identificadores para ver um exemplo de como substituir os recursos de identificação.

      Limpar

      Para evitar cobranças na conta do Google Cloud pelos recursos usados nesta página, siga estas etapas.

      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

      Console

    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

      A seguir