Trascrivere gli offset temporali delle parole

Questo esempio mostra come trascrivere l'audio con gli offset temporali delle parole utilizzando l'API Speech-to-Text.

Esempio di codice

Python

Per scoprire come installare e utilizzare la libreria client per Cloud STT, consulta la sezione Librerie client Cloud STT. Per saperne di più, consulta la documentazione di riferimento dell'API Cloud STT Python.

Per eseguire l'autenticazione in Cloud STT, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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_word_time_offsets_v2(
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribes an audio file into text using with word time offsets.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
            Example: "resources/audio.wav"
    Returns:
        cloud_speech.RecognizeResponse: The response containing the transcription results
            with word time offsets.
    """
    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as file:
        audio_content = file.read()

    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        language_codes=["en-US"],
        model="long",
        features=cloud_speech.RecognitionFeatures(
            enable_word_time_offsets=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

Passaggi successivi

Per cercare e filtrare gli esempi di codice per altri prodotti Google Cloud , consulta il browser degli esempi diGoogle Cloud .