Strumenti di riconoscimento

Speech-to-Text V2 supporta una risorsa Google Cloud chiamata riconoscitori. I riconoscitori rappresentano la configurazione di riconoscimento archiviata e riutilizzabile. Puoi utilizzarli per raggruppare logicamente le trascrizioni o il traffico per la tua applicazione.

Prima di iniziare

  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.

      Vai a IAM
    2. Seleziona il progetto.
    3. Fai clic su Concedi l'accesso.
    4. Nel campo Nuove entità, inserisci il tuo identificatore utente. In genere si tratta dell'indirizzo email di un Account Google.

    5. Nell'elenco Seleziona un ruolo, seleziona un ruolo.
    6. Per concedere altri ruoli, fai clic su Aggiungi un altro ruolo e aggiungi ogni ruolo aggiuntivo.
    7. Fai clic su Salva.
  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.

      Vai a IAM
    2. Seleziona il progetto.
    3. Fai clic su Concedi l'accesso.
    4. Nel campo Nuove entità, inserisci il tuo identificatore utente. In genere si tratta dell'indirizzo email di un Account Google.

    5. Nell'elenco Seleziona un ruolo, seleziona un ruolo.
    6. Per concedere altri ruoli, fai clic su Aggiungi un altro ruolo e aggiungi ogni ruolo aggiuntivo.
    7. Fai clic su Salva.
  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. Le librerie client possono utilizzare le credenziali predefinite dell'applicazione per autenticarsi facilmente con le API di Google e inviare richieste a queste API. Con Credenziali predefinite dell'applicazione, puoi testare la tua applicazione localmente e implementarla senza modificare il codice sottostante. Per maggiori informazioni, vedi Autenticarsi per l'utilizzo delle librerie client.

  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. Assicurati inoltre di aver installato la libreria client.

    Informazioni sui riconoscitori

    I riconoscitori sono configurazioni di riconoscimento riutilizzabili e configurabili. La creazione di riconoscitori con configurazione di riconoscimento utilizzata di frequente consente di semplificare e ridurre le dimensioni delle richieste di riconoscimento.

    L'elemento principale di un riconoscitore è la sua configurazione predefinita. Questa è la configurazione per ogni richiesta di riconoscimento eseguita da questo riconoscitore. Puoi ignorare questo valore predefinito per ogni richiesta. Mantieni la configurazione predefinita per le funzionalità che ti servono in tutte le richieste per un determinato riconoscimento, mentre esegui l'override di funzionalità specifiche per richieste specifiche.

    Riutilizza i riconoscitori il più spesso possibile. La creazione di un elemento per ogni richiesta aumenta notevolmente la latenza dell'applicazione e consuma le quote delle risorse. Creali di rado durante l'integrazione e la configurazione, poi riutilizzali per le richieste di riconoscimento.

    Creare riconoscitori

    Ecco un esempio di creazione di un riconoscitore che può essere utilizzato per inviare richieste di riconoscimento:

    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 create_recognizer(recognizer_id: str) -> cloud_speech.Recognizer:
        """Сreates a recognizer with an unique ID and default recognition configuration.
        Args:
            recognizer_id (str): The unique identifier for the recognizer to be created.
        Returns:
            cloud_speech.Recognizer: The created recognizer object with configuration.
        """
        # Instantiates a client
        client = SpeechClient()
    
        request = cloud_speech.CreateRecognizerRequest(
            parent=f"projects/{PROJECT_ID}/locations/global",
            recognizer_id=recognizer_id,
            recognizer=cloud_speech.Recognizer(
                default_recognition_config=cloud_speech.RecognitionConfig(
                    language_codes=["en-US"], model="long"
                ),
            ),
        )
        # Sends the request to create a recognizer and waits for the operation to complete
        operation = client.create_recognizer(request=request)
        recognizer = operation.result()
    
        print("Created Recognizer:", recognizer.name)
        return recognizer
    
    

    Utilizzare un riconoscitore esistente per inviare richieste

    Ecco un esempio di invio di più richieste di riconoscimento utilizzando lo stesso riconoscitore:

    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_reuse_recognizer(
        audio_file: str,
        recognizer_id: str,
    ) -> cloud_speech.RecognizeResponse:
        """Transcribe an audio file using an existing recognizer.
        Args:
            audio_file (str): Path to the local audio file to be transcribed.
                Example: "resources/audio.wav"
            recognizer_id (str): The ID of the existing recognizer to be used for transcription.
        Returns:
            cloud_speech.RecognizeResponse: The response containing the transcription results.
        """
        # Instantiates a client
        client = SpeechClient()
    
        # Reads a file as bytes
        with open(audio_file, "rb") as f:
            audio_content = f.read()
    
        request = cloud_speech.RecognizeRequest(
            recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}",
            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
    
    

    Attivare le funzionalità in un riconoscimento

    I riconoscitori possono essere utilizzati per attivare varie funzionalità nel riconoscimento, ad esempio la punteggiatura automatica o il filtro volgarità.

    Ecco un esempio di attivazione della punteggiatura automatica in un riconoscitore, che consente di attivare la punteggiatura automatica nella richiesta di riconoscimento utilizzando questo riconoscitore:

    Python

    
    from google.cloud.speech_v2 import SpeechClient
    from google.cloud.speech_v2.types import cloud_speech
    
    from google.api_core.exceptions import NotFound
    
    # Instantiates a client
    client = SpeechClient()
    
    # TODO(developer): Update and un-comment below line
    # PROJECT_ID = "your-project-id"
    # recognizer_id = "id-recognizer"
    recognizer_name = (
        f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}"
    )
    try:
        # Use an existing recognizer
        recognizer = client.get_recognizer(name=recognizer_name)
        print("Using existing Recognizer:", recognizer.name)
    except NotFound:
        # Create a new recognizer
        request = cloud_speech.CreateRecognizerRequest(
            parent=f"projects/{PROJECT_ID}/locations/global",
            recognizer_id=recognizer_id,
            recognizer=cloud_speech.Recognizer(
                default_recognition_config=cloud_speech.RecognitionConfig(
                    auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
                    language_codes=["en-US"],
                    model="latest_long",
                    features=cloud_speech.RecognitionFeatures(
                        enable_automatic_punctuation=True,
                    ),
                ),
            ),
        )
        operation = client.create_recognizer(request=request)
        recognizer = operation.result()
        print("Created Recognizer:", recognizer.name)
    
    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()
    
    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}",
        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}")
    

    Eseguire l'override delle funzionalità di riconoscimento nelle richieste di riconoscimento

    Ecco un esempio di abilitazione di più funzionalità in un riconoscitore, ma disabilitazione della punteggiatura automatica per questa richiesta di riconoscimento:

    Python

    import os
    
    from google.cloud.speech_v2 import SpeechClient
    from google.cloud.speech_v2.types import cloud_speech
    from google.protobuf.field_mask_pb2 import FieldMask
    
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
    
    
    def transcribe_override_recognizer(
        audio_file: str,
        recognizer_id: str,
    ) -> cloud_speech.RecognizeResponse:
        """Transcribe an audio file using an existing recognizer with overridden settings for the recognition request.
        Args:
            audio_file (str): Path to the local audio file to be transcribed.
                Example: "resources/audio.wav"
            recognizer_id (str): The unique ID of the recognizer to be used for transcription.
        Returns:
            cloud_speech.RecognizeResponse: The response containing the transcription results.
        """
        # Instantiates a client
        client = SpeechClient()
    
        request = cloud_speech.CreateRecognizerRequest(
            parent=f"projects/{PROJECT_ID}/locations/global",
            recognizer_id=recognizer_id,
            recognizer=cloud_speech.Recognizer(
                default_recognition_config=cloud_speech.RecognitionConfig(
                    auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
                    language_codes=["en-US"],
                    model="latest_long",
                    features=cloud_speech.RecognitionFeatures(
                        enable_automatic_punctuation=True,
                        enable_word_time_offsets=True,
                    ),
                ),
            ),
        )
    
        operation = client.create_recognizer(request=request)
        recognizer = operation.result()
    
        print("Created Recognizer:", recognizer.name)
    
        # Reads a file as bytes
        with open(audio_file, "rb") as f:
            audio_content = f.read()
    
        request = cloud_speech.RecognizeRequest(
            recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}",
            config=cloud_speech.RecognitionConfig(
                features=cloud_speech.RecognitionFeatures(
                    enable_word_time_offsets=False,
                ),
            ),
            config_mask=FieldMask(paths=["features.enable_word_time_offsets"]),
            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
    
    

    Inviare richieste senza riconoscitori

    I riconoscitori sono facoltativi nelle richieste di riconoscimento. Per effettuare una richiesta senza un riconoscitore, utilizza semplicemente l'ID risorsa del riconoscitore _ nella posizione in cui stai effettuando una richiesta. Ecco un esempio:

    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 quickstart_v2(audio_file: str) -> cloud_speech.RecognizeResponse:
        """Transcribe an audio file.
        Args:
            audio_file (str): Path to the local audio file to be transcribed.
        Returns:
            cloud_speech.RecognizeResponse: The response from the recognize request, containing
            the transcription results
        """
        # Reads a file as bytes
        with open(audio_file, "rb") as f:
            audio_content = f.read()
    
        # Instantiates a client
        client = SpeechClient()
    
        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}")
    
        return response
    
    

    Esegui la pulizia

    Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questa pagina, segui questi passaggi.

    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

    Passaggi successivi