Transcribir con confianza a nivel de palabra

En este ejemplo, se muestra cómo transcribir audio con confianza a nivel de palabra usando la API de Speech-to-Text.

Muestra de código

Python

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Speech-to-Text, consulta las bibliotecas cliente de Speech-to-Text. Para obtener más información, consulta la documentación de referencia de la API de Speech-to-Text de Python.

Para autenticar en Speech-to-Text, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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_level_confidence_v2(
    audio_file: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribes a local audio file into text with word-level confidence.
    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-level confidence.
    """
    # 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_confidence=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

¿Qué sigue?

Para buscar y filtrar muestras de código para otros Google Cloud productos, consulta el Google Cloud navegador de muestras.