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 Iniciando Asistente ESP32...")
|
| 8 |
+
|
| 9 |
+
# Cargar modelos optimizados para ESP32
|
| 10 |
+
try:
|
| 11 |
+
print("📥 Cargando modelo de voz...")
|
| 12 |
+
stt_pipeline = pipeline(
|
| 13 |
+
"automatic-speech-recognition",
|
| 14 |
+
model="openai/whisper-tiny",
|
| 15 |
+
device=-1 # Usar CPU
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
print("📥 Cargando modelo de chat...")
|
| 19 |
+
chat_pipeline = pipeline(
|
| 20 |
+
"text-generation",
|
| 21 |
+
model="microsoft/DialoGPT-small",
|
| 22 |
+
device=-1,
|
| 23 |
+
max_length=100
|
| 24 |
+
)
|
| 25 |
+
print("✅ Modelos cargados correctamente!")
|
| 26 |
+
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"❌ Error cargando modelos: {e}")
|
| 29 |
+
stt_pipeline = None
|
| 30 |
+
chat_pipeline = None
|
| 31 |
+
|
| 32 |
+
def process_audio(audio_file):
|
| 33 |
+
"""Procesar audio para ESP32"""
|
| 34 |
+
if stt_pipeline is None or chat_pipeline is None:
|
| 35 |
+
return "Models not loaded", "Please try again in a moment"
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
print("🎤 Procesando audio...")
|
| 39 |
+
|
| 40 |
+
# Transcripción
|
| 41 |
+
result = stt_pipeline(audio_file)
|
| 42 |
+
text = result["text"].strip()
|
| 43 |
+
print(f"📝 Transcripción: {text}")
|
| 44 |
+
|
| 45 |
+
if not text or text == "":
|
| 46 |
+
return "No se detectó audio", "Habla más claro por favor"
|
| 47 |
+
|
| 48 |
+
# Generar respuesta
|
| 49 |
+
print("🤖 Generando respuesta...")
|
| 50 |
+
chat_response = chat_pipeline(
|
| 51 |
+
f"Usuario: {text}\nAsistente:",
|
| 52 |
+
max_new_tokens=80,
|
| 53 |
+
temperature=0.7,
|
| 54 |
+
do_sample=True,
|
| 55 |
+
pad_token_id=chat_pipeline.tokenizer.eos_token_id
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
answer = chat_response[0]["generated_text"]
|
| 59 |
+
# Limpiar respuesta
|
| 60 |
+
if "Asistente:" in answer:
|
| 61 |
+
answer = answer.split("Asistente:")[-1].strip()
|
| 62 |
+
|
| 63 |
+
print(f"💬 Respuesta: {answer}")
|
| 64 |
+
return text, answer
|
| 65 |
+
|
| 66 |
+
except Exception as e:
|
| 67 |
+
error_msg = f"Error: {str(e)}"
|
| 68 |
+
print(error_msg)
|
| 69 |
+
return error_msg, "Error en el procesamiento"
|
| 70 |
+
|
| 71 |
+
# Interfaz mejorada para ESP32
|
| 72 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Asistente ESP32") as demo:
|
| 73 |
+
gr.Markdown(
|
| 74 |
+
"""
|
| 75 |
+
# 🎤 Asistente de Voz para ESP32
|
| 76 |
+
**Servicio optimizado para microcontroladores**
|
| 77 |
+
"""
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
with gr.Row():
|
| 81 |
+
with gr.Column():
|
| 82 |
+
gr.Markdown("### 📤 Subir Audio")
|
| 83 |
+
audio_input = gr.Audio(
|
| 84 |
+
sources=["upload"],
|
| 85 |
+
type="filepath",
|
| 86 |
+
label="Audio WAV (16kHz, mono, 16-bit)",
|
| 87 |
+
waveform_options={"show_controls": False}
|
| 88 |
+
)
|
| 89 |
+
process_btn = gr.Button("🚀 Procesar Audio", variant="primary")
|
| 90 |
+
|
| 91 |
+
gr.Markdown("### 📋 Especificaciones ESP32")
|
| 92 |
+
gr.Markdown("""
|
| 93 |
+
- **Formato:** WAV, 16kHz, mono, 16-bit
|
| 94 |
+
- **Duración:** 3-5 segundos máximo
|
| 95 |
+
- **Conexión:** HTTPS POST a esta URL
|
| 96 |
+
""")
|
| 97 |
+
|
| 98 |
+
with gr.Column():
|
| 99 |
+
gr.Markdown("### 📝 Resultados")
|
| 100 |
+
transcription = gr.Textbox(
|
| 101 |
+
label="Transcripción",
|
| 102 |
+
placeholder="El texto aparecerá aquí...",
|
| 103 |
+
lines=3
|
| 104 |
+
)
|
| 105 |
+
response = gr.Textbox(
|
| 106 |
+
label="Respuesta del Asistente",
|
| 107 |
+
placeholder="La respuesta aparecerá aquí...",
|
| 108 |
+
lines=4
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Ejemplos para probar
|
| 112 |
+
gr.Markdown("### 🧪 Ejemplos para Probar")
|
| 113 |
+
gr.Examples(
|
| 114 |
+
examples=[
|
| 115 |
+
["https://example.com/audio1.wav"], # Puedes subir ejemplos después
|
| 116 |
+
["https://example.com/audio2.wav"]
|
| 117 |
+
],
|
| 118 |
+
inputs=[audio_input],
|
| 119 |
+
outputs=[transcription, response],
|
| 120 |
+
fn=process_audio,
|
| 121 |
+
cache_examples=False
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# Procesar cuando se sube audio o se clickea el botón
|
| 125 |
+
process_btn.click(
|
| 126 |
+
fn=process_audio,
|
| 127 |
+
inputs=[audio_input],
|
| 128 |
+
outputs=[transcription, response]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Info del estado
|
| 132 |
+
gr.Markdown("### 🔍 Estado del Sistema")
|
| 133 |
+
status = gr.Textbox(
|
| 134 |
+
value="✅ Servicio listo para ESP32" if stt_pipeline else "⚠️ Cargando modelos...",
|
| 135 |
+
label="Estado",
|
| 136 |
+
interactive=False
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# Configuración del servidor
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
demo.launch(
|
| 142 |
+
server_name="0.0.0.0",
|
| 143 |
+
server_port=7860,
|
| 144 |
+
share=False,
|
| 145 |
+
debug=True
|
| 146 |
+
)
|