Spaces:
Runtime error
Runtime error
| """ | |
| BATUTO X ENTERPRISE - VERSIÓN COMPATIBLE HUGGING FACE SPACES | |
| """ | |
| import os | |
| import sys | |
| import subprocess | |
| import time | |
| # ==================== VERIFICACIÓN INICIAL OBLIGATORIA ==================== | |
| print("="*70) | |
| print("🚀 VERIFICANDO ENTORNO DE HUGGING FACE SPACES") | |
| print("="*70) | |
| # 1. Verificar Python | |
| print(f"Python: {sys.version}") | |
| # 2. Verificar/Instalar Gradio 4.x | |
| try: | |
| import gradio as gr | |
| if not gr.__version__.startswith("4."): | |
| print(f"⚠️ Versión incorrecta: {gr.__version__}") | |
| print("📦 Instalando Gradio 4.28.2...") | |
| subprocess.run([sys.executable, "--force-reinstall"], | |
| check=True) | |
| # Recargar módulo | |
| import importlib | |
| importlib.reload(gr) | |
| print(f"✅ Gradio {gr.__version__} correcto") | |
| except ImportError: | |
| print("📦 Instalando Gradio 4.28.2...") | |
| subprocess.run([sys.executable, "-m", "pip", "install", "gradio==4.28.2"], check=True) | |
| import gradio as gr | |
| # 3. Configurar variables de entorno desde Secrets de Hugging Face | |
| # NO USAR variables en requirements.txt - usar Secrets del Space | |
| API_KEY = os.environ.get("SAMBANOVA_API_KEY_2", "") | |
| REVE_KEY = os.environ.get("REVE_API_KEY", "") | |
| print(f"🔑 SAMBANOVA_API_KEY: {'✅' if API_KEY else '❌ No configurada'}") | |
| print(f"🎨 REVE_API_KEY: {'✅' if REVE_KEY else '❌ No configurada'}") | |
| # 4. Resto de imports DESPUÉS de verificar Gradio | |
| from datetime import datetime | |
| from pathlib import Path | |
| import json | |
| import asyncio | |
| from PIL import Image | |
| from typing import Dict, List, Tuple, Any, Generator | |
| # ==================== CONFIGURACIÓN ==================== | |
| OUTPUT_DIR = Path("batuto_generations") | |
| OUTPUT_DIR.mkdir(exist_ok=True) | |
| # ==================== MÓDULOS SIMULADOS (si no existen) ==================== | |
| try: | |
| from cognitive_kernel import IntentType, analyze_intent_detailed | |
| MODULES_LOADED = True | |
| except ImportError: | |
| MODULES_LOADED = False | |
| print("⚠️ Módulos personalizados no disponibles - usando simulación") | |
| class IntentType: | |
| IMAGE = "image" | |
| CODE = "code" | |
| GENERAL = "general" | |
| # ==================== APLICACIÓN PRINCIPAL ==================== | |
| def create_simple_interface(): | |
| """Interfaz simple y compatible con Hugging Face Spaces""" | |
| with gr.Blocks( | |
| title="BATUTO X - Hugging Face Spaces", | |
| theme=gr.themes.Soft() | |
| ) as interface: | |
| # Header | |
| gr.Markdown(""" | |
| # 🤖 BATUTO X Enterprise | |
| ### Versión compatible con Hugging Face Spaces | |
| """) | |
| # Chatbot | |
| chatbot = gr.Chatbot( | |
| label="Conversación", | |
| height=500 | |
| ) | |
| # Estado | |
| status = gr.Markdown("**Estado**: Listo") | |
| # Input | |
| msg = gr.Textbox( | |
| label="Mensaje", | |
| placeholder="Escribe tu mensaje aquí...", | |
| lines=3 | |
| ) | |
| # Botones | |
| with gr.Row(): | |
| submit_btn = gr.Button("Enviar", variant="primary") | |
| clear_btn = gr.Button("Limpiar", variant="secondary") | |
| # Funciones | |
| def respond(message, history): | |
| if not message.strip(): | |
| return history, "Escribe algo..." | |
| # Respuesta simulada | |
| response = f"**Simulación**: Recibí: '{message}'" | |
| # Formato CORRECTO para Gradio 4.x | |
| if not history: | |
| history = [] | |
| # Agregar mensaje usuario | |
| history.append({"role": "user", "content": message}) | |
| # Agregar respuesta asistente | |
| history.append({"role": "assistant", "content": response}) | |
| return history, f"Respondido a: {message[:20]}..." | |
| def clear(): | |
| return [], "Chat limpiado" | |
| # Eventos | |
| submit_btn.click( | |
| fn=respond, | |
| inputs=[msg, chatbot], | |
| outputs=[chatbot, status] | |
| ) | |
| msg.submit( | |
| fn=respond, | |
| inputs=[msg, chatbot], | |
| outputs=[chatbot, status] | |
| ) | |
| clear_btn.click( | |
| fn=clear, | |
| outputs=[chatbot, status] | |
| ) | |
| # Footer | |
| gr.Markdown(""" | |
| --- | |
| **Nota**: Esta es una versión simplificada para debugging. | |
| Para la versión completa, configura las variables de entorno: | |
| 1. `SAMBANOVA_API_KEY_2` en Settings > Repository secrets | |
| 2. `REVE_API_KEY` en Settings > Repository secrets | |
| """) | |
| return interface | |
| # ==================== EJECUCIÓN ==================== | |
| if __name__ == "__main__": | |
| print("\n" + "="*70) | |
| print("🚀 INICIANDO APLICACIÓN EN HUGGING FACE SPACES") | |
| print("="*70) | |
| # Crear interfaz | |
| app = create_simple_interface() | |
| # Configuración específica para Spaces | |
| app.launch( | |
| server_name="0.0.0.0", # Obligatorio para Spaces | |
| server_port=7860, # Puerto estándar de Spaces | |
| share=False, | |
| debug=False, | |
| show_error=True | |
| ) |