Transcrever arquivos de áudio curtos

Nesta página, descrevemos como transcrever um arquivo de áudio curto para texto usando o reconhecimento de fala síncrono.

O reconhecimento de fala síncrono converte o texto reconhecido para áudio curto (menos de 60 segundos).

O conteúdo de áudio pode ser enviado diretamente para a Speech-to-Text de um arquivo local, ou a Speech-to-Text pode processar conteúdo de áudio armazenado em um bucket do Cloud Storage. Consulte a página cotas e limites para ver os limites nas solicitações síncronas de reconhecimento de fala.

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

      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.
  6. Install the Google Cloud CLI.

  7. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  8. To initialize the gcloud CLI, run the following command:

    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. Make sure 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.

      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.
  13. Install the Google Cloud CLI.

  14. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  15. To initialize the gcloud CLI, run the following command:

    gcloud init
  16. 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. Para mais informações, consulte Autenticar 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. Verifique também se você instalou a biblioteca de cliente.

    Executar o reconhecimento de fala síncrono em um arquivo local

    Este é um exemplo de reconhecimento de fala síncrono em um arquivo de áudio local:

    Python

    
    from google.cloud.speech_v2 import SpeechClient
    from google.cloud.speech_v2.types import cloud_speech
    
    # TODO(developer): Update and un-comment below line
    # PROJECT_ID = "your-project-id"
    
    # Instantiates a client
    client = SpeechClient()
    
    # Reads a file as bytes
    with open("resources/audio.wav", "rb") as f:
        audio_content = f.read()
    
    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        language_codes=["en-US"],
        model="long",
    )
    
    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
        config=config,
        content=audio_content,
    )
    
    # Transcribes the audio into text
    response = client.recognize(request=request)
    
    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")
    

    Executar o reconhecimento de fala síncrono em um arquivo remoto

    Para sua comodidade, a API Speech-to-Text executa o reconhecimento de fala síncrono diretamente em um arquivo de áudio localizado no Cloud Storage, sem precisar enviar o conteúdo do arquivo de áudio no corpo da solicitação.

    A Speech-to-Text usa uma conta de serviço para acessar seus 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:

    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

    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.

    Este é um exemplo de reconhecimento de fala síncrono em um arquivo localizado no Cloud Storage:

    Python

    
    from google.cloud.speech_v2 import SpeechClient
    from google.cloud.speech_v2.types import cloud_speech
    
    # Instantiates a client
    client = SpeechClient()
    
    # TODO(developer): Update and un-comment below line
    # PROJECT_ID = "your-project-id"
    
    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        language_codes=["en-US"],
        model="long",
    )
    
    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
        config=config,
        uri="gs://cloud-samples-data/speech/audio.flac",  # URI of the audio file in GCS
    )
    
    # Transcribes the audio into text
    response = client.recognize(request=request)
    
    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")
    

    Limpar

    Para evitar cobranças na sua 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

  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

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

    A seguir