Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -18,7 +18,7 @@ client_options = ClientOptions(api_key=API_KEY)
|
|
18 |
client = speech.SpeechClient(client_options=client_options)
|
19 |
|
20 |
def get_audio_duration(file_path):
|
21 |
-
"""Obtiene la duración del archivo de audio en segundos."""
|
22 |
result = subprocess.run(
|
23 |
["ffprobe", "-i", file_path, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"],
|
24 |
capture_output=True, text=True
|
@@ -26,31 +26,42 @@ def get_audio_duration(file_path):
|
|
26 |
return float(result.stdout.strip())
|
27 |
|
28 |
def convert_to_wav(input_file):
|
29 |
-
"""
|
|
|
|
|
|
|
30 |
output_file = input_file + ".wav"
|
31 |
command = [
|
32 |
"ffmpeg", "-y", "-i", input_file,
|
33 |
-
"-acodec", "pcm_s16le", "-ar", "48000", "-ac", "1", output_file
|
34 |
]
|
35 |
subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
36 |
return output_file
|
37 |
|
|
|
|
|
|
|
|
|
|
|
38 |
def transcribe(audio_file=None):
|
39 |
"""Transcribe audio a texto usando Google Cloud Speech-to-Text."""
|
40 |
if audio_file is None:
|
41 |
return "No se ha seleccionado ningún archivo.", ""
|
42 |
|
43 |
-
#
|
44 |
if not audio_file.endswith(".wav"):
|
45 |
audio_file = convert_to_wav(audio_file)
|
46 |
|
|
|
|
|
|
|
47 |
# Obtener la duración del archivo
|
48 |
duration = get_audio_duration(audio_file)
|
49 |
|
50 |
-
# Configuración de la solicitud
|
51 |
config = speech.RecognitionConfig(
|
52 |
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
|
53 |
-
sample_rate_hertz=
|
54 |
audio_channel_count=1,
|
55 |
language_code="es-AR",
|
56 |
)
|
@@ -58,22 +69,22 @@ def transcribe(audio_file=None):
|
|
58 |
# Cargar el audio en binario
|
59 |
with io.open(audio_file, "rb") as file:
|
60 |
content = file.read()
|
61 |
-
|
62 |
|
|
|
63 |
if duration <= 60:
|
64 |
-
# Si el audio dura menos de 1 minuto, usamos transcripción síncrona
|
65 |
response = client.recognize(config=config, audio=audio)
|
66 |
else:
|
67 |
-
|
68 |
-
|
69 |
|
70 |
transcript = []
|
71 |
confidence = []
|
72 |
|
73 |
-
#
|
74 |
for result in response.results:
|
75 |
-
confidence.append(str(result.alternatives[0].confidence))
|
76 |
transcript.append(result.alternatives[0].transcript)
|
|
|
77 |
|
78 |
return ' '.join(transcript), '\n'.join(confidence)
|
79 |
|
@@ -86,8 +97,7 @@ demo = gr.Interface(
|
|
86 |
inputs=gr.Audio(sources=["microphone", "upload"], type="filepath", label="Subir o grabar audio"),
|
87 |
outputs=[output1, output2],
|
88 |
title='Demo Reconocimiento de Audio',
|
89 |
-
description='<p>
|
90 |
)
|
91 |
|
92 |
demo.launch()
|
93 |
-
|
|
|
18 |
client = speech.SpeechClient(client_options=client_options)
|
19 |
|
20 |
def get_audio_duration(file_path):
|
21 |
+
"""Obtiene la duración del archivo de audio en segundos usando ffprobe."""
|
22 |
result = subprocess.run(
|
23 |
["ffprobe", "-i", file_path, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"],
|
24 |
capture_output=True, text=True
|
|
|
26 |
return float(result.stdout.strip())
|
27 |
|
28 |
def convert_to_wav(input_file):
|
29 |
+
"""
|
30 |
+
Convierte el archivo de audio a WAV LINEAR16. Se fuerza la conversión a 48000 Hz.
|
31 |
+
Esto se aplica únicamente si el archivo no es ya un WAV.
|
32 |
+
"""
|
33 |
output_file = input_file + ".wav"
|
34 |
command = [
|
35 |
"ffmpeg", "-y", "-i", input_file,
|
36 |
+
"-acodec", "pcm_s16le", "-ar", "48000", "-ac", "1", output_file
|
37 |
]
|
38 |
subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
39 |
return output_file
|
40 |
|
41 |
+
def get_wav_sample_rate(file_path):
|
42 |
+
"""Obtiene la tasa de muestreo real del archivo WAV."""
|
43 |
+
with wave.open(file_path, 'rb') as wav_file:
|
44 |
+
return wav_file.getframerate()
|
45 |
+
|
46 |
def transcribe(audio_file=None):
|
47 |
"""Transcribe audio a texto usando Google Cloud Speech-to-Text."""
|
48 |
if audio_file is None:
|
49 |
return "No se ha seleccionado ningún archivo.", ""
|
50 |
|
51 |
+
# Si el archivo no es WAV, lo convertimos
|
52 |
if not audio_file.endswith(".wav"):
|
53 |
audio_file = convert_to_wav(audio_file)
|
54 |
|
55 |
+
# Obtener la tasa de muestreo real del archivo WAV
|
56 |
+
actual_sample_rate = get_wav_sample_rate(audio_file)
|
57 |
+
|
58 |
# Obtener la duración del archivo
|
59 |
duration = get_audio_duration(audio_file)
|
60 |
|
61 |
+
# Configuración de la solicitud usando la tasa real del audio
|
62 |
config = speech.RecognitionConfig(
|
63 |
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
|
64 |
+
sample_rate_hertz=actual_sample_rate,
|
65 |
audio_channel_count=1,
|
66 |
language_code="es-AR",
|
67 |
)
|
|
|
69 |
# Cargar el audio en binario
|
70 |
with io.open(audio_file, "rb") as file:
|
71 |
content = file.read()
|
72 |
+
audio = speech.RecognitionAudio(content=content)
|
73 |
|
74 |
+
# Si el audio dura menos de 1 minuto se usa transcripción síncrona
|
75 |
if duration <= 60:
|
|
|
76 |
response = client.recognize(config=config, audio=audio)
|
77 |
else:
|
78 |
+
return ("Error: El audio es muy largo para la transcripción síncrona. "
|
79 |
+
"Se necesita Google Cloud Storage.", "")
|
80 |
|
81 |
transcript = []
|
82 |
confidence = []
|
83 |
|
84 |
+
# Procesar la respuesta de la API
|
85 |
for result in response.results:
|
|
|
86 |
transcript.append(result.alternatives[0].transcript)
|
87 |
+
confidence.append(str(result.alternatives[0].confidence))
|
88 |
|
89 |
return ' '.join(transcript), '\n'.join(confidence)
|
90 |
|
|
|
97 |
inputs=gr.Audio(sources=["microphone", "upload"], type="filepath", label="Subir o grabar audio"),
|
98 |
outputs=[output1, output2],
|
99 |
title='Demo Reconocimiento de Audio',
|
100 |
+
description='<p>Graba o sube un archivo de audio para convertir voz a texto usando Google Cloud Speech-to-Text.</p>'
|
101 |
)
|
102 |
|
103 |
demo.launch()
|
|