Transcreva ficheiros de áudio longos em texto

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 superior 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 esta está concluída e 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. Verify 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 column 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.

      Aceder ao IAM
    2. Selecione o projeto.
    3. Clique em Conceder acesso.
    4. No campo Novos responsáveis, introduza o identificador do utilizador. Normalmente, este é o endereço de email de uma Conta Google.

    5. Na lista Selecionar uma função, selecione uma função.
    6. Para conceder funções adicionais, clique em Adicionar outra função e adicione cada função adicional.
    7. Clique em Guardar.
  6. Install the Google Cloud CLI.

  7. Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro, tem de iniciar sessão na CLI gcloud com a sua identidade federada.

  8. Para inicializar a CLI gcloud, execute o seguinte comando:

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

    Go to project selector

  10. Verify that billing is enabled for your Google Cloud project.

  11. Enable the Speech-to-Text APIs.

    Enable the APIs

  12. 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 column 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.

      Aceder ao IAM
    2. Selecione o projeto.
    3. Clique em Conceder acesso.
    4. No campo Novos responsáveis, introduza o identificador do utilizador. Normalmente, este é o endereço de email de uma Conta Google.

    5. Na lista Selecionar uma função, selecione uma função.
    6. Para conceder funções adicionais, clique em Adicionar outra função e adicione cada função adicional.
    7. Clique em Guardar.
  13. Install the Google Cloud CLI.

  14. Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro, tem de iniciar sessão na CLI gcloud com a sua identidade federada.

  15. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  16. As 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.

  17. 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.

    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.

  18. 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.iam.gserviceaccount.com
    

    Para transcrever ficheiros do Cloud Storage noutro projeto, pode atribuir a esta conta de serviço a função de agente do serviço 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

    Pode encontrar mais informações sobre a Política IAM do projeto em Faça a gestão do acesso a projetos, pastas e organizações.

    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.iam.gserviceaccount.com \
        --role=roles/storage.admin

    Pode encontrar mais informações sobre a gestão do acesso ao Cloud Storage no artigo Crie e faça a gestão de listas de controlo de acesso 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.
                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
    
    

    Realize 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 BatchRecognizeResults no 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="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
    
    

    Realize 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.
                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
    
    

    Ative 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="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
    
    

    Substitua 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 config na mensagem [BatchRecognizeFileMetadata][batch-file-metadata-grpc]. 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.

    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

    Consola

  19. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  20. In the project list, select the project that you want to delete, and then click Delete.
  21. In the dialog, type the project ID, and then click Shut down to delete the project.
  22. gcloud

  23. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  24. In the project list, select the project that you want to delete, and then click Delete.
  25. In the dialog, type the project ID, and then click Shut down to delete the project.
  26. O que se segue?