Spaces:
Runtime error
Runtime error
File size: 5,122 Bytes
e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 ab237e7 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 9199563 e72d384 | 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 | """
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
) |