File size: 3,624 Bytes
f452077
d9d94b1
ae874ba
cb9846d
636fe04
f452077
2c6849a
 
cb9846d
2c6849a
ae874ba
2c6849a
ae874ba
2c6849a
bdb0292
2c6849a
 
 
cb9846d
450515e
921dbf5
450515e
 
 
 
 
f452077
636fe04
921dbf5
 
 
 
636fe04
 
 
921dbf5
636fe04
 
 
 
921dbf5
 
 
 
 
bdb0292
2c6849a
bdb0292
 
636fe04
921dbf5
bdb0292
 
4de176d
921dbf5
 
 
450515e
 
f452077
921dbf5
2c6849a
 
921dbf5
2c6849a
 
 
 
 
 
 
921dbf5
2c6849a
921dbf5
450515e
 
 
921dbf5
 
2c6849a
 
 
4de176d
921dbf5
2c6849a
 
921dbf5
4de176d
2c6849a
cb9846d
bdb0292
7634404
e04c18e
 
cb9846d
bdb0292
 
 
4721cc4
921dbf5
cb9846d
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

import os
import io
import gradio as gr
import subprocess
import wave
from google.cloud import speech
from google.api_core.client_options import ClientOptions

# Obtener la API Key desde las variables de entorno
try:
    API_KEY = os.environ["GOOGLE_API_KEY"]
except KeyError:
    raise ValueError("La API Key de Google no está disponible. Configúrala en los Secrets como 'GOOGLE_API_KEY'.")

# Configurar cliente de Google Speech-to-Text con API Key
client_options = ClientOptions(api_key=API_KEY)
client = speech.SpeechClient(client_options=client_options)

def get_audio_duration(file_path):
    """Obtiene la duración del archivo de audio en segundos usando ffprobe."""
    result = subprocess.run(
        ["ffprobe", "-i", file_path, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"],
        capture_output=True, text=True
    )
    return float(result.stdout.strip())

def convert_to_wav(input_file):
    """
    Convierte el archivo de audio a WAV LINEAR16. Se fuerza la conversión a 48000 Hz.
    Esto se aplica únicamente si el archivo no es ya un WAV.
    """
    output_file = input_file + ".wav"
    command = [
        "ffmpeg", "-y", "-i", input_file,
        "-acodec", "pcm_s16le", "-ar", "48000", "-ac", "1", output_file
    ]
    subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return output_file

def get_wav_sample_rate(file_path):
    """Obtiene la tasa de muestreo real del archivo WAV."""
    with wave.open(file_path, 'rb') as wav_file:
        return wav_file.getframerate()

def transcribe(audio_file=None):
    """Transcribe audio a texto usando Google Cloud Speech-to-Text."""
    if audio_file is None:
        return "No se ha seleccionado ningún archivo.", ""

    # Si el archivo no es WAV, lo convertimos
    if not audio_file.endswith(".wav"):
        audio_file = convert_to_wav(audio_file)

    # Obtener la tasa de muestreo real del archivo WAV
    actual_sample_rate = get_wav_sample_rate(audio_file)

    # Obtener la duración del archivo
    duration = get_audio_duration(audio_file)

    # Configuración de la solicitud usando la tasa real del audio
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=actual_sample_rate,
        audio_channel_count=1,
        language_code="es-AR",
    )

    # Cargar el audio en binario
    with io.open(audio_file, "rb") as file:
        content = file.read()
    audio = speech.RecognitionAudio(content=content)

    # Si el audio dura menos de 1 minuto se usa transcripción síncrona
    if duration <= 60:
        response = client.recognize(config=config, audio=audio)
    else:
        return ("Error: El audio es muy largo para la transcripción síncrona. "
                "Se necesita Google Cloud Storage.", "")

    transcript = []
    confidence = []

    # Procesar la respuesta de la API
    for result in response.results:
        transcript.append(result.alternatives[0].transcript)
        confidence.append(str(result.alternatives[0].confidence))

    return ' '.join(transcript), '\n'.join(confidence)

# Configuración de la interfaz Gradio
output1 = gr.Textbox(label='Transcripción')
output2 = gr.Textbox(label='Confianza')

demo = gr.Interface(
    fn=transcribe,
    inputs=gr.Audio(sources=["microphone", "upload"], type="filepath", label="Subir o grabar audio"),
    outputs=[output1, output2],
    title='Demo Reconocimiento de Audio',
    description='<p>Graba o sube un archivo de audio para convertir voz a texto usando Google Cloud Speech-to-Text.</p>'
)

demo.launch()