Ativar pontuação automática

Nesta página, veja como aplicar a pontuação automática nos resultados de transcrição do Speech-to-Text. Quando você ativa esse recurso, o Speech-to-Text infere automaticamente a presença de pontos, vírgulas e pontos de interrogação nos dados de áudio e os adiciona à transcrição.

Por padrão, o Speech-to-Text não inclui sinais de pontuação nos resultados do reconhecimento de fala. No entanto, é possível solicitar que o Speech-to-Text detecte e insira a pontuação nos resultados da transcrição. Quando você ativa a pontuação automática, o Speech-to-Text também coloca em maiúscula a primeira letra após cada ponto e ponto de interrogação.

Antes de começar

  1. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

  3. 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 the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  4. 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. Selecione o projeto.
    3. Clique em Conceder acesso.
    4. No campo Novos principais, digite seu identificador de usuário. Normalmente, é o identificador de um usuário em um pool de identidades de força de trabalho. Saiba mais em Representar usuários do pool de força de trabalho nas políticas do IAM ou entre em contato com seu administrador.

    5. Na lista Selecionar papel, escolha um.
    6. Para conceder outros papéis, adicione-os clicando em Adicionar outro papel.
    7. Clique em Salvar.
  5. Install the Google Cloud CLI.

  6. Configure a gcloud CLI para usar sua identidade federada.

    Para mais informações, consulte Fazer login na gcloud CLI com sua identidade federada.

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

    gcloud init

    As bibliotecas de cliente podem usar o Application Default Credentials para se autenticar facilmente nas APIs do Google e enviar solicitações para elas. Com o Application Default Credentials, é possível testar seu aplicativo localmente e implantá-lo sem alterar o código. Para mais informações, consulte Autenticação para usar bibliotecas de cliente.

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

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

    Fazer uma solicitação de transcrição com pontuação automática

    Os exemplos de código a seguir demonstram como detectar os detalhes da pontuação em uma solicitação de transcrição.

    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_auto_punctuation_v2(audio_file: str) -> cloud_speech.RecognizeResponse:
        """Transcribe an audio file with automatically detect and insert punctuation in transcription results.
        Args:
            audio_file (str): Path to the local audio file to be transcribed.
        """
        # Instantiates a client
        client = SpeechClient()
    
        # Reads a file as bytes
        with open(audio_file, "rb") as f:
            audio_content = f.read()
    
        config = cloud_speech.RecognitionConfig(
            auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
            language_codes=["en-US"],
            model="long",
            features=cloud_speech.RecognitionFeatures(
                # Enable automatic punctuation
                enable_automatic_punctuation=True,
            ),
        )
    
        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}")
    
        return response
    
    

    Consulte a documentação de referência RecognitionFeatures para mais informações sobre como configurar recursos diferentes.

    Limpeza

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

    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

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

    Go to Manage resources

  11. In the project list, select the project that you want to delete, and then click Delete.
  12. In the dialog, type the project ID, and then click Shut down to delete the project.
  13. gcloud

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