Spaces:
Runtime error
Runtime error
Download app.py from Alejandrott24/Asistentevisual: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/spaces/Alejandrott24/Asistentevisual/resolve/main/app.py
- Command line
-
hf download hf://spaces/Alejandrott24/Asistentevisual/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Alejandrott24/Asistentevisual/resolve/main/app.py
20 kB
| 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() |