File size: 20,033 Bytes
91f9ab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f18a89c
 
 
 
91f9ab5
 
 
 
 
f18a89c
91f9ab5
 
 
 
 
 
f18a89c
91f9ab5
 
 
 
 
f18a89c
 
91f9ab5
 
f18a89c
 
91f9ab5
f18a89c
 
 
91f9ab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f18a89c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
import gradio as gr
import requests
import base64
from PIL import Image
import io
import json
import time
import re
import hashlib

# ========== CONFIGURACIÓN DE TUS SPACES ==========
GEMMA_API = "https://alejandrott24-mi-gemma-servidor.hf.space/preguntar"
PIPER_API = "https://alejandrott24-piper-tts-server.hf.space/tts"

# Cargar Moondream localmente
print("🌙 Cargando Moondream...")
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import warnings

# Suprimir advertencias de transformers
warnings.filterwarnings('ignore', category=UserWarning)

model_id = "vikhyatk/moondream2"
revision = "2024-08-26"

try:
    print("📦 Cargando tokenizer...")
    tokenizer = AutoTokenizer.from_pretrained(
        model_id,
        revision=revision,
        trust_remote_code=True
    )
    
    print("🧠 Cargando modelo Moondream (esto puede tomar 1-2 minutos)...")
    moondream_model = AutoModelForCausalLM.from_pretrained(
        model_id,
        revision=revision,
        trust_remote_code=True,
        torch_dtype=torch.float32,
        low_cpu_mem_usage=True,
        device_map="cpu"
    )
    moondream_model.eval()
    print("✅ Moondream cargado exitosamente en CPU!")
    
except Exception as e:
    print(f"❌ Error crítico cargando Moondream: {e}")
    import traceback
    traceback.print_exc()
    raise

# ========== CACHÉ PARA OPTIMIZACIÓN ==========
cache_analisis = {}

# ========== INSTRUCCIONES PARA GEMMA ==========
SYSTEM_PROMPT = """Eres un asistente visual conciso y natural.

REGLAS ESTRICTAS:
- Responde en máximo 2-3 oraciones cortas y claras
- NO uses onomatopeyas: jaja, jeje, mmm, uhm, ehh, ajá, etc.
- NO uses asteriscos ni acciones entre asteriscos: *sonríe*, *piensa*
- NO uses emojis
- Habla en primera persona cuando describes lo que ves
- Sé descriptivo pero extremadamente breve
- Evita repeticiones y palabras de relleno

EJEMPLOS BUENOS:
"Veo una persona con camisa azul sentada en un sofá gris. Hay una planta verde al fondo."
"Observo dos tazas de café sobre una mesa de madera. La habitación tiene buena iluminación natural."

EJEMPLOS MALOS:
"jaja pues ehh, *observa con atención* mmm veo como que una persona, ¿sabes? 😊"
"Bueno, este, déjame ver... uhm, hay como una mesa o algo así..."
"""

# ========== FUNCIONES DE UTILIDAD ==========

def limpiar_texto(texto):
    """Elimina onomatopeyas y formatos no deseados"""
    # Lista de onomatopeyas comunes
    onomatopeyas = [
        r'\bjaja+\b', r'\bjeje+\b', r'\bjiji+\b', r'\bjojo+\b',
        r'\bmmm+\b', r'\bhmm+\b', r'\buhm+\b', r'\behh+\b',
        r'\bahh+\b', r'\bohh+\b', r'\buff+\b', r'\bpfff+\b',
        r'\bajá\b', r'\baja\b', r'\bejem\b', r'\bups\b',
        r'\bguau\b', r'\bmiau\b', r'\bñam\b', r'\bwow\b'
    ]
    
    for ono in onomatopeyas:
        texto = re.sub(ono, '', texto, flags=re.IGNORECASE)
    
    # Eliminar contenido entre asteriscos
    texto = re.sub(r'\*[^*]+\*', '', texto)
    
    # Eliminar emojis
    texto = re.sub(r'[😀-🙏🌀-🗿🚀-🛿]', '', texto)
    
    # Limpiar espacios múltiples y saltos de línea excesivos
    texto = re.sub(r'\s+', ' ', texto)
    texto = re.sub(r'\n\s*\n', '\n', texto)
    
    return texto.strip()

def hash_imagen(imagen):
    """Genera un hash único para la imagen"""
    try:
        img_bytes = io.BytesIO()
        imagen.save(img_bytes, format='PNG')
        return hashlib.md5(img_bytes.getvalue()).hexdigest()
    except:
        return str(time.time())

def validar_conexion_api(url, timeout=5):
    """Verifica si una API está disponible"""
    try:
        response = requests.get(url, timeout=timeout)
        return response.status_code == 200
    except:
        return False

# ========== FUNCIONES PRINCIPALES ==========

def analizar_con_moondream(imagen, pregunta, usar_cache=True):
    """Analiza la imagen con Moondream (local) con caché"""
    try:
        if imagen is None:
            return "No hay imagen para analizar."
        
        if not isinstance(imagen, Image.Image):
            imagen = Image.fromarray(imagen)
        
        imagen = imagen.convert('RGB')
        
        # Verificar caché
        img_hash = hash_imagen(imagen)
        cache_key = f"{img_hash}_{pregunta}"
        
        if usar_cache and cache_key in cache_analisis:
            print("📦 Usando respuesta en caché")
            return cache_analisis[cache_key]
        
        # Pregunta optimizada para descripción breve
        if not pregunta or pregunta.strip() == "":
            pregunta = "Describe brevemente lo que ves, máximo 3 oraciones."
        else:
            pregunta = f"{pregunta} Responde de forma breve y clara."
        
        print(f"🔍 Analizando imagen con Moondream...")
        enc_image = moondream_model.encode_image(imagen)
        respuesta = moondream_model.answer_question(enc_image, pregunta, tokenizer)
        
        # Guardar en caché
        if usar_cache:
            cache_analisis[cache_key] = respuesta
            # Limitar tamaño del caché
            if len(cache_analisis) > 20:
                cache_analisis.pop(next(iter(cache_analisis)))
        
        return respuesta
    
    except Exception as e:
        print(f"❌ Error en Moondream: {e}")
        return f"Error en análisis visual: {str(e)}"

def responder_con_gemma(contexto_visual, pregunta_usuario, reintentos=2):
    """Genera respuesta con Gemma con reintentos automáticos"""
    try:
        # Construir prompt completo
        prompt_completo = f"""{SYSTEM_PROMPT}

CONTEXTO VISUAL: {contexto_visual}

PREGUNTA DEL USUARIO: {pregunta_usuario}

RESPUESTA:"""
        
        print(f"💬 Consultando Gemma...")
        
        # Intentar con reintentos
        for intento in range(reintentos):
            try:
                response = requests.get(
                    GEMMA_API,
                    params={"mensaje": prompt_completo},
                    timeout=20
                )
                
                if response.status_code == 200:
                    resultado = response.json()
                    respuesta = resultado.get("respuesta", "")
                    
                    if respuesta:
                        # Limpiar respuesta
                        respuesta_limpia = limpiar_texto(respuesta)
                        return respuesta_limpia
                    else:
                        return "Gemma no generó una respuesta válida."
                        
                elif response.status_code == 503:
                    if intento < reintentos - 1:
                        print(f"⏳ Gemma ocupado, reintentando en 3s...")
                        time.sleep(3)
                        continue
                    return "⚠️ Gemma está sobrecargado. Intenta de nuevo en un momento."
                else:
                    return f"⚠️ Error al conectar con Gemma (código {response.status_code})"
                    
            except requests.Timeout:
                if intento < reintentos - 1:
                    print(f"⏱️ Timeout, reintentando...")
                    time.sleep(2)
                    continue
                return "⏱️ Gemma tardó demasiado en responder. Intenta de nuevo."
                
        return "❌ No se pudo obtener respuesta de Gemma tras varios intentos."
    
    except requests.ConnectionError:
        return "🔌 No se pudo conectar con Gemma. Verifica que el servidor esté activo."
    except Exception as e:
        print(f"❌ Error en Gemma: {e}")
        return f"Error en Gemma: {str(e)}"

def generar_audio_piper(texto):
    """Genera audio con Piper TTS optimizado"""
    try:
        # Limitar longitud del texto
        if len(texto) > 500:
            texto = texto[:500] + "..."
        
        # No generar audio para mensajes de error
        if any(x in texto for x in ["Error", "⚠️", "❌", "🔌", "⏱️"]):
            print("⭐️ Saltando TTS para mensaje de error")
            return None
        
        print(f"🔊 Generando audio con Piper...")
        
        # Configuración óptima para voz natural
        payload = {
            "text": texto,
            "model": "es_MX-claude-high.onnx",
            "speaker_id": 0,
            "length_scale": 1.0,
            "noise_scale": 0.667,
            "noise_w": 0.8,
            "sentence_silence": 0.2
        }
        
        response = requests.post(
            PIPER_API,
            json=payload,
            timeout=25
        )
        
        if response.status_code == 200:
            resultado = response.json()
            audio_base64 = resultado.get("audio", "")
            
            if audio_base64:
                # Decodificar base64 y guardar temporalmente
                audio_bytes = base64.b64decode(audio_base64)
                audio_path = f"/tmp/audio_{int(time.time() * 1000)}.wav"
                
                with open(audio_path, "wb") as f:
                    f.write(audio_bytes)
                
                print(f"✅ Audio generado: {audio_path}")
                return audio_path
        
        print(f"⚠️ Piper retornó código {response.status_code}")
        return None
    
    except requests.Timeout:
        print("⏱️ Piper TTS timeout")
        return None
    except Exception as e:
        print(f"❌ Error en TTS: {e}")
        return None

# ========== FUNCIÓN PRINCIPAL ==========

def procesar_pregunta(imagen, pregunta, historial):
    """Función principal que integra todo el sistema con mejor feedback"""
    
    if imagen is None:
        respuesta = "⚠️ Por favor, captura una imagen con la cámara primero."
        historial.append((pregunta or "Sin pregunta", respuesta))
        return historial, None, ""
    
    if not pregunta or pregunta.strip() == "":
        pregunta = "¿Qué ves en la imagen?"
    
    # Agregar pregunta al historial
    historial.append((f"👤 {pregunta}", "⏳ Analizando imagen..."))
    yield historial, None, pregunta
    time.sleep(0.1)  # Dar tiempo al UI para actualizar
    
    # PASO 1: Analizar imagen con Moondream
    descripcion_visual = analizar_con_moondream(imagen, pregunta)
    
    if "Error" in descripcion_visual:
        historial[-1] = (f"👤 {pregunta}", f"❌ {descripcion_visual}")
        yield historial, None, ""
        return
    
    # PASO 2: Generar respuesta con Gemma
    historial[-1] = (f"👤 {pregunta}", f"⏳ Generando respuesta inteligente...\n\n🔍 Análisis: {descripcion_visual}")
    yield historial, None, pregunta
    time.sleep(0.1)
    
    respuesta_final = responder_con_gemma(descripcion_visual, pregunta)
    
    # Actualizar historial con respuesta
    historial[-1] = (f"👤 {pregunta}", f"🤖 {respuesta_final}")
    yield historial, None, ""
    time.sleep(0.1)
    
    # PASO 3: Generar audio (solo si la respuesta es válida)
    audio_path = generar_audio_piper(respuesta_final)
    
    yield historial, audio_path, ""

# ========== INTERFAZ GRADIO ==========

# Definir CSS y theme para launch()
custom_css = """
    .camera-box {
        border: 2px solid #4CAF50; 
        border-radius: 10px; 
        padding: 10px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    .status-active {
        color: #4CAF50; 
        font-weight: bold;
        font-size: 1.1em;
    }
    .status-inactive {
        color: #f44336; 
        font-weight: bold;
        font-size: 1.1em;
    }
    .header-title {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 2em;
        font-weight: bold;
    }
"""

custom_theme = gr.themes.Soft(
    primary_hue="blue",
    secondary_hue="green",
)

with gr.Blocks(title="Asistente Visual Inteligente") as demo:
    
    # Estado de la cámara
    camara_encendida = gr.State(False)
    imagen_actual = gr.State(None)
    
    gr.Markdown("""
    <div style="text-align: center;">
        <h1 class="header-title">📸 Asistente Visual Inteligente</h1>
        <p><strong>Integración completa:</strong> Moondream (Visión) + Gemma (Chat) + Piper TTS (Voz)</p>
    </div>
    
    <div style="background-color: #f0f0f0; padding: 15px; border-radius: 10px; margin: 10px 0;">
        <h3>💡 Cómo usar:</h3>
        <ol>
            <li>🟢 <strong>Enciende la cámara</strong> con el botón verde</li>
            <li>📸 <strong>Captura una imagen</strong> de lo que quieres analizar</li>
            <li>✏️ <strong>Haz tu pregunta</strong> sobre la imagen (o déjalo vacío para descripción general)</li>
            <li>🔊 <strong>Escucha la respuesta</strong> en voz sintetizada</li>
        </ol>
    </div>
    """)
    
    with gr.Row():
        # COLUMNA IZQUIERDA: CÁMARA
        with gr.Column(scale=1):
            gr.Markdown("### 📹 Control de Cámara")
            
            camara = gr.Image(
                sources=["webcam"],
                type="pil",
                label="Vista de cámara en vivo",
                streaming=False,
                visible=False,
                height=300
            )
            
            with gr.Row():
                btn_encender = gr.Button(
                    "🟢 Encender Cámara", 
                    variant="primary", 
                    size="sm"
                )
                btn_apagar = gr.Button(
                    "🔴 Apagar Cámara", 
                    variant="stop", 
                    size="sm"
                )
            
            btn_capturar = gr.Button(
                "📸 Capturar Imagen", 
                variant="secondary", 
                size="lg",
                scale=2
            )
            
            estado_txt = gr.Markdown(
                "**Estado:** 🔴 Cámara apagada", 
                elem_classes="status-inactive"
            )
            
            imagen_capturada = gr.Image(
                label="📷 Última captura",
                type="pil",
                interactive=False,
                height=250
            )
            
            gr.Markdown("""
            <div style="background-color: #e3f2fd; padding: 10px; border-radius: 5px; margin-top: 10px;">
                <strong>💡 Tip:</strong> Asegúrate de tener buena iluminación para mejores resultados
            </div>
            """)
        
        # COLUMNA DERECHA: CHAT
        with gr.Column(scale=2):
            gr.Markdown("### 💬 Conversación con el Asistente")
            
            chatbot = gr.Chatbot(
                label="Historial de conversación",
                height=450,
                avatar_images=(None, "🤖")
            )
            
            with gr.Row():
                pregunta_txt = gr.Textbox(
                    placeholder="Ejemplo: ¿Qué objetos ves? ¿De qué color es? ¿Hay personas?",
                    label="Tu pregunta",
                    scale=4,
                    show_label=False,
                    lines=2
                )
                btn_enviar = gr.Button(
                    "📤 Enviar", 
                    variant="primary", 
                    scale=1,
                    size="lg"
                )
            
            audio_output = gr.Audio(
                label="🔊 Respuesta en audio",
                autoplay=True,
                visible=True,
                show_download_button=True
            )
            
            with gr.Accordion("💡 Ejemplos de preguntas", open=False):
                gr.Markdown("""
                **Preguntas generales:**
                - ¿Qué ves en la imagen?
                - Describe esta escena
                - ¿Qué está pasando aquí?
                
                **Preguntas específicas:**
                - ¿Qué objetos hay?
                - ¿De qué colores son las cosas?
                - ¿Cuántas personas hay?
                - ¿Hay animales?
                - ¿Qué texto puedes leer?
                
                **Preguntas contextuales:**
                - ¿Dónde crees que fue tomada?
                - ¿Qué hora del día parece ser?
                - ¿Qué está haciendo la persona?
                """)
            
            with gr.Row():
                btn_limpiar = gr.Button(
                    "🗑️ Limpiar conversación", 
                    variant="secondary",
                    size="sm"
                )
                btn_ejemplo = gr.Button(
                    "🎲 Pregunta aleatoria",
                    variant="secondary",
                    size="sm"
                )
    
    gr.Markdown("""
    ---
    <div style="text-align: center; color: #666; font-size: 0.9em;">
        <p>⚡ Powered by: <strong>Moondream Vision</strong> | <strong>Gemma 2B</strong> | <strong>Piper TTS</strong></p>
        <p>🚀 Creado con Gradio y Hugging Face Spaces</p>
    </div>
    """)
    
    # ========== FUNCIONES DE EVENTOS ==========
    
    def encender_camara():
        return (
            gr.update(visible=True),
            gr.Markdown("**Estado:** 🟢 Cámara encendida y lista", elem_classes="status-active"),
            True
        )
    
    def apagar_camara():
        return (
            gr.update(visible=False),
            gr.Markdown("**Estado:** 🔴 Cámara apagada", elem_classes="status-inactive"),
            False,
            None
        )
    
    def capturar_imagen(img, estado):
        if not estado:
            return None, None, "⚠️ Primero enciende la cámara con el botón verde"
        if img is None:
            return None, None, "⚠️ No hay imagen disponible para capturar. Asegúrate de que la cámara esté funcionando"
        return img, img, None
    
    def limpiar_todo():
        global cache_analisis
        cache_analisis.clear()  # Limpiar caché también
        return [], None, ""
    
    def pregunta_aleatoria():
        import random
        preguntas = [
            "¿Qué objetos ves en la imagen?",
            "¿De qué colores son las cosas?",
            "Describe esta escena brevemente",
            "¿Hay personas? ¿Qué están haciendo?",
            "¿Qué elementos destacan más?",
            "¿Dónde crees que fue tomada esta foto?"
        ]
        return random.choice(preguntas)
    
    # ========== CONECTAR EVENTOS ==========
    
    btn_encender.click(
        fn=encender_camara,
        outputs=[camara, estado_txt, camara_encendida]
    )
    
    btn_apagar.click(
        fn=apagar_camara,
        outputs=[camara, estado_txt, camara_encendida, imagen_capturada]
    )
    
    btn_capturar.click(
        fn=capturar_imagen,
        inputs=[camara, camara_encendida],
        outputs=[imagen_actual, imagen_capturada, estado_txt]
    )
    
    btn_enviar.click(
        fn=procesar_pregunta,
        inputs=[imagen_actual, pregunta_txt, chatbot],
        outputs=[chatbot, audio_output, pregunta_txt]
    )
    
    pregunta_txt.submit(
        fn=procesar_pregunta,
        inputs=[imagen_actual, pregunta_txt, chatbot],
        outputs=[chatbot, audio_output, pregunta_txt]
    )
    
    btn_limpiar.click(
        fn=limpiar_todo,
        outputs=[chatbot, audio_output, pregunta_txt]
    )
    
    btn_ejemplo.click(
        fn=pregunta_aleatoria,
        outputs=pregunta_txt
    )

# Lanzar la aplicación con theme y css
if __name__ == "__main__":
    try:
        print("🚀 Iniciando interfaz Gradio...")
        demo.launch(
            share=False,
            show_error=True,
            favicon_path=None,
            theme=custom_theme,
            css=custom_css,
            server_name="0.0.0.0",  # Necesario para Hugging Face Spaces
            server_port=7860  # Puerto estándar de Spaces
        )
    except Exception as e:
        print(f"❌ Error al lanzar Gradio: {e}")
        import traceback
        traceback.print_exc()