Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,29 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline
|
| 3 |
-
import tempfile
|
| 4 |
import os
|
| 5 |
-
import
|
| 6 |
|
| 7 |
print("🚀 Iniciando Asistente ESP32...")
|
| 8 |
|
| 9 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
try:
|
| 11 |
print("📥 Cargando modelo de voz...")
|
| 12 |
stt_pipeline = pipeline(
|
| 13 |
"automatic-speech-recognition",
|
| 14 |
model="openai/whisper-tiny",
|
| 15 |
-
|
|
|
|
| 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 |
)
|
|
@@ -68,79 +73,140 @@ def process_audio(audio_file):
|
|
| 68 |
print(error_msg)
|
| 69 |
return error_msg, "Error en el procesamiento"
|
| 70 |
|
| 71 |
-
#
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
gr.Markdown(
|
| 74 |
"""
|
| 75 |
-
#
|
| 76 |
-
**
|
|
|
|
|
|
|
| 77 |
"""
|
| 78 |
)
|
| 79 |
|
| 80 |
-
with gr.
|
| 81 |
-
with gr.
|
| 82 |
-
gr.
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
gr.
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 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 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 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 |
)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline
|
|
|
|
| 3 |
import os
|
| 4 |
+
import tempfile
|
| 5 |
|
| 6 |
print("🚀 Iniciando Asistente ESP32...")
|
| 7 |
|
| 8 |
+
# Obtener token de las variables de entorno
|
| 9 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 10 |
+
print(f"🔑 Token disponible: {'Sí' if HF_TOKEN else 'No'}")
|
| 11 |
+
|
| 12 |
+
# Cargar modelos con token de autenticación
|
| 13 |
try:
|
| 14 |
print("📥 Cargando modelo de voz...")
|
| 15 |
stt_pipeline = pipeline(
|
| 16 |
"automatic-speech-recognition",
|
| 17 |
model="openai/whisper-tiny",
|
| 18 |
+
token=HF_TOKEN,
|
| 19 |
+
device=-1
|
| 20 |
)
|
| 21 |
|
| 22 |
print("📥 Cargando modelo de chat...")
|
| 23 |
chat_pipeline = pipeline(
|
| 24 |
"text-generation",
|
| 25 |
+
model="microsoft/DialoGPT-small",
|
| 26 |
+
token=HF_TOKEN,
|
| 27 |
device=-1,
|
| 28 |
max_length=100
|
| 29 |
)
|
|
|
|
| 73 |
print(error_msg)
|
| 74 |
return error_msg, "Error en el procesamiento"
|
| 75 |
|
| 76 |
+
# Función especial para ESP32 (recibe datos binarios)
|
| 77 |
+
def process_esp32_audio(audio_data):
|
| 78 |
+
"""Procesar audio directamente desde ESP32"""
|
| 79 |
+
if stt_pipeline is None:
|
| 80 |
+
return {"error": "Models not loaded"}
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
# Guardar datos temporales
|
| 84 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp:
|
| 85 |
+
if hasattr(audio_data, 'read'):
|
| 86 |
+
# Si es un file-like object
|
| 87 |
+
tmp.write(audio_data.read())
|
| 88 |
+
else:
|
| 89 |
+
# Si son bytes directamente
|
| 90 |
+
tmp.write(audio_data)
|
| 91 |
+
tmp_path = tmp.name
|
| 92 |
+
|
| 93 |
+
# Procesar
|
| 94 |
+
result = stt_pipeline(tmp_path)
|
| 95 |
+
text = result["text"].strip()
|
| 96 |
+
|
| 97 |
+
# Generar respuesta si hay texto
|
| 98 |
+
if text:
|
| 99 |
+
chat_response = chat_pipeline(
|
| 100 |
+
f"Usuario: {text}\nAsistente:",
|
| 101 |
+
max_new_tokens=60,
|
| 102 |
+
temperature=0.7
|
| 103 |
+
)
|
| 104 |
+
answer = chat_response[0]["generated_text"]
|
| 105 |
+
if "Asistente:" in answer:
|
| 106 |
+
answer = answer.split("Asistente:")[-1].strip()
|
| 107 |
+
else:
|
| 108 |
+
answer = "No pude entender el audio"
|
| 109 |
+
|
| 110 |
+
# Limpiar archivo temporal
|
| 111 |
+
os.unlink(tmp_path)
|
| 112 |
+
|
| 113 |
+
return {
|
| 114 |
+
"transcription": text,
|
| 115 |
+
"response": answer,
|
| 116 |
+
"success": True
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
return {"error": str(e), "success": False}
|
| 121 |
+
|
| 122 |
+
# Interfaz SIMPLIFICADA - sin ejemplos problemáticos
|
| 123 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Proyecto BMO - ESP32") as demo:
|
| 124 |
gr.Markdown(
|
| 125 |
"""
|
| 126 |
+
# 🤖 Proyecto BMO - Asistente ESP32
|
| 127 |
+
**by benjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa**
|
| 128 |
+
|
| 129 |
+
Servicio de voz inteligente para microcontroladores
|
| 130 |
"""
|
| 131 |
)
|
| 132 |
|
| 133 |
+
with gr.Tab("🎤 Interfaz Web"):
|
| 134 |
+
with gr.Row():
|
| 135 |
+
with gr.Column():
|
| 136 |
+
gr.Markdown("### 📤 Subir Audio")
|
| 137 |
+
audio_input = gr.Audio(
|
| 138 |
+
sources=["upload", "microphone"],
|
| 139 |
+
type="filepath",
|
| 140 |
+
label="Grabar o subir audio WAV",
|
| 141 |
+
waveform_options={"show_controls": True}
|
| 142 |
+
)
|
| 143 |
+
process_btn = gr.Button("🚀 Procesar Audio", variant="primary")
|
| 144 |
+
|
| 145 |
+
with gr.Column():
|
| 146 |
+
gr.Markdown("### 📝 Resultados")
|
| 147 |
+
transcription = gr.Textbox(
|
| 148 |
+
label="Transcripción",
|
| 149 |
+
placeholder="El texto transcribido aparecerá aquí...",
|
| 150 |
+
lines=3
|
| 151 |
+
)
|
| 152 |
+
response = gr.Textbox(
|
| 153 |
+
label="Respuesta del Asistente",
|
| 154 |
+
placeholder="La respuesta inteligente aparecerá aquí...",
|
| 155 |
+
lines=4
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# Procesar audio desde la interfaz web
|
| 159 |
+
process_btn.click(
|
| 160 |
+
fn=process_audio,
|
| 161 |
+
inputs=[audio_input],
|
| 162 |
+
outputs=[transcription, response]
|
| 163 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
with gr.Tab("📡 Para ESP32"):
|
| 166 |
+
gr.Markdown("### 🔌 Endpoint para Microcontrolador")
|
| 167 |
+
gr.Markdown("""
|
| 168 |
+
**URL para ESP32:** `https://benjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-ProyectoBMO.hf.space`
|
| 169 |
+
|
| 170 |
+
**Método:** POST
|
| 171 |
+
**Content-Type:** `audio/wav`
|
| 172 |
+
**Body:** Datos de audio WAV sin encabezado
|
| 173 |
+
|
| 174 |
+
**Formato de audio:**
|
| 175 |
+
- Sample rate: 16000 Hz
|
| 176 |
+
- Canales: Mono
|
| 177 |
+
- Bits: 16
|
| 178 |
+
- Duración: 3-5 segundos
|
| 179 |
+
|
| 180 |
+
**Ejemplo código Arduino:**
|
| 181 |
+
```cpp
|
| 182 |
+
HTTPClient http;
|
| 183 |
+
http.begin("https://benjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-ProyectoBMO.hf.space");
|
| 184 |
+
http.addHeader("Content-Type", "audio/wav");
|
| 185 |
+
int httpResponseCode = http.POST(audioData, audioSize);
|
| 186 |
+
```
|
| 187 |
+
""")
|
| 188 |
|
| 189 |
+
with gr.Tab("🔍 Estado"):
|
| 190 |
+
gr.Markdown("### 📊 Estado del Sistema")
|
| 191 |
+
status_text = "✅ Servicio listo para ESP32" if stt_pipeline else "⚠️ Cargando modelos..."
|
| 192 |
+
gr.Textbox(
|
| 193 |
+
value=status_text,
|
| 194 |
+
label="Estado de Modelos",
|
| 195 |
+
interactive=False
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
gr.Markdown("### 📈 Logs en Tiempo Real")
|
| 199 |
+
gr.Textbox(
|
| 200 |
+
value="Los logs aparecen en la consola del Space",
|
| 201 |
+
label="Logs",
|
| 202 |
+
interactive=False,
|
| 203 |
+
lines=3
|
| 204 |
+
)
|
| 205 |
|
| 206 |
# Configuración del servidor
|
| 207 |
if __name__ == "__main__":
|
| 208 |
demo.launch(
|
| 209 |
server_name="0.0.0.0",
|
| 210 |
server_port=7860,
|
| 211 |
+
share=False
|
|
|
|
| 212 |
)
|