speech-to-text / app.py
cesar's picture
Update app.py
636fe04 verified
raw
history blame
2.69 kB
import os
import io
import gradio as gr
import subprocess
from google.cloud import speech
from google.api_core.client_options import ClientOptions
# Obtener la API Key desde las variables de entorno
API_KEY = os.getenv("GOOGLE_API_KEY")
# Verificar si la API Key está configurada
if not API_KEY:
raise ValueError("La API Key de Google no está configurada. Configúrala en la variable de entorno GOOGLE_API_KEY.")
def convert_to_wav(input_file):
"""Convierte archivos de audio a formato WAV LINEAR16 si es necesario."""
output_file = input_file + ".wav"
command = [
"ffmpeg", "-y", "-i", input_file,
"-acodec", "pcm_s16le", "-ar", "44100", "-ac", "1", output_file
]
subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return output_file
def transcribe(file_path):
"""Transcribe audio a texto usando Google Cloud Speech-to-Text con API Key."""
if file_path is None:
return '', ''
# Convertir a formato WAV si es necesario
if not file_path.endswith(".wav"):
file_path = convert_to_wav(file_path)
# Configurar el cliente de Speech-to-Text con API Key
client_options = ClientOptions(api_key=API_KEY)
client = speech.SpeechClient(client_options=client_options)
# Configuración de la solicitud
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=44100,
audio_channel_count=1,
language_code="es-AR",
)
# Cargar el audio en binario
with io.open(file_path, "rb") as audio_file:
content = audio_file.read()
audio = speech.RecognitionAudio(content=content)
# Realiza la transcripción
response = client.recognize(config=config, audio=audio)
transcript = []
confidence = []
# Lee la respuesta de la API
for result in response.results:
confidence.append(str(result.alternatives[0].confidence))
transcript.append(result.alternatives[0].transcript)
return ' '.join(transcript), '\n'.join(confidence)
# Configuración de la interfaz Gradio con opciones de grabación y subida de archivos
output1 = gr.Textbox(label='Transcripción')
output2 = gr.Textbox(label='Confianza')
demo = gr.Interface(
transcribe,
[
gr.Audio(sources=["microphone"], type="filepath", label='Grabar audio aquí', streaming=False),
gr.File(label="Subir archivo de audio")
],
[output1, output2],
title='Demo Reconocimiento de Voz con Google',
description='<p>Grabar o subir un archivo de audio para convertir voz a texto usando Google Cloud Speech-to-Text.</p>'
)
demo.launch()