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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import asyncio
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import base64
|
| 7 |
+
import io
|
| 8 |
+
import requests
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from functools import lru_cache
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
# ------------ CONFIGURACIÓN MEJORADA ------------
|
| 14 |
+
class Config:
|
| 15 |
+
def __init__(self):
|
| 16 |
+
# PRIMERO busca en secrets de Hugging Face, LUEGO en .env
|
| 17 |
+
self.SAMBANOVA_API_KEY = os.getenv("SAMBANOVA_API_KEY")
|
| 18 |
+
self.BRIA_API_TOKEN = os.getenv("BRIA_API_TOKEN")
|
| 19 |
+
self.HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
|
| 20 |
+
|
| 21 |
+
# Si no está en environment, intenta cargar desde huggingface_hub
|
| 22 |
+
if not self.SAMBANOVA_API_KEY:
|
| 23 |
+
try:
|
| 24 |
+
from huggingface_hub import HfFolder
|
| 25 |
+
self.SAMBANOVA_API_KEY = HfFolder.get_token()
|
| 26 |
+
except ImportError:
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
self.validate_keys()
|
| 30 |
+
|
| 31 |
+
def validate_keys(self):
|
| 32 |
+
if not self.SAMBANOVA_API_KEY:
|
| 33 |
+
print("❌ SAMBANOVA_API_KEY no encontrado")
|
| 34 |
+
print("💡 Configura el secret en Hugging Face Spaces:")
|
| 35 |
+
print(" - Ve a Settings → Repository secrets")
|
| 36 |
+
print(" - Agrega: SAMBANOVA_API_KEY = tu_api_key_real")
|
| 37 |
+
else:
|
| 38 |
+
print(f"✅ SAMBANOVA_API_KEY configurado (primeros 10 chars): {self.SAMBANOVA_API_KEY[:10]}...")
|
| 39 |
+
|
| 40 |
+
if not self.BRIA_API_TOKEN:
|
| 41 |
+
print("⚠️ BRIA_API_TOKEN no configurado - Imagen deshabilitada")
|
| 42 |
+
else:
|
| 43 |
+
print("✅ BRIA_API_TOKEN configurado")
|
| 44 |
+
|
| 45 |
+
config = Config()
|
| 46 |
+
|
| 47 |
+
# ------------ IMPORTACION CONDICIONAL ------------
|
| 48 |
+
try:
|
| 49 |
+
from sambanova import SambaNova
|
| 50 |
+
print("✅ SambaNova importado correctamente")
|
| 51 |
+
except ImportError as e:
|
| 52 |
+
print(f"❌ Error importando SambaNova: {e}")
|
| 53 |
+
print("💡 Instala con: pip install sambanova")
|
| 54 |
+
SambaNova = None
|
| 55 |
+
|
| 56 |
+
# ------------ MODELOS INTEGRADOS ------------
|
| 57 |
+
MODELS = {
|
| 58 |
+
"chat": {
|
| 59 |
+
"llama3": "NousResearch/Meta-Llama-3-8B-Instruct",
|
| 60 |
+
"qwen": "Qwen/Qwen1.5-32B-Chat",
|
| 61 |
+
"deepseek": "deepseek-ai/deepseek-llm-67b-chat",
|
| 62 |
+
"sambanova": {
|
| 63 |
+
"models": ["Llama-3.3-Swallow-70B-Instruct-v0.4", "Qwen3-32B", "DeepSeek-V3-0324"],
|
| 64 |
+
"api_key": config.SAMBANOVA_API_KEY
|
| 65 |
+
}
|
| 66 |
+
},
|
| 67 |
+
"code": {
|
| 68 |
+
"starcoder2": "bigcode/starcoder2-7b",
|
| 69 |
+
"deepseek-coder": "deepseek-ai/deepseek-coder-33b-instruct"
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
# ------------ CARGA DE MODELOS CON CUANTIZACIÓN INT8 ------------
|
| 74 |
+
class ModelLoader:
|
| 75 |
+
@lru_cache(maxsize=3)
|
| 76 |
+
def load_hf_model(self, model_name: str):
|
| 77 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 78 |
+
|
| 79 |
+
# Usar token en lugar de use_auth_token (deprecado)
|
| 80 |
+
token = config.HUGGINGFACE_TOKEN
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, token=token)
|
| 84 |
+
|
| 85 |
+
# Configuración mejorada de dispositivo
|
| 86 |
+
if torch.cuda.is_available():
|
| 87 |
+
device_map = "auto"
|
| 88 |
+
print(f"🚀 Usando GPU para {model_name}")
|
| 89 |
+
else:
|
| 90 |
+
device_map = {"": "cpu"}
|
| 91 |
+
print(f"⚡ Usando CPU para {model_name}")
|
| 92 |
+
|
| 93 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 94 |
+
model_name,
|
| 95 |
+
token=token,
|
| 96 |
+
load_in_8bit=True,
|
| 97 |
+
device_map=device_map,
|
| 98 |
+
low_cpu_mem_usage=True,
|
| 99 |
+
torch_dtype=torch.float16
|
| 100 |
+
)
|
| 101 |
+
model.eval()
|
| 102 |
+
return model, tokenizer
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
print(f"❌ Error cargando modelo {model_name}: {e}")
|
| 106 |
+
return None, None
|
| 107 |
+
|
| 108 |
+
model_loader = ModelLoader()
|
| 109 |
+
|
| 110 |
+
# ------------ HERRAMIENTAS MEJORADAS ------------
|
| 111 |
+
class AI_Tools:
|
| 112 |
+
def __init__(self):
|
| 113 |
+
self.sn_client = None
|
| 114 |
+
if SambaNova is not None and config.SAMBANOVA_API_KEY:
|
| 115 |
+
try:
|
| 116 |
+
self.sn_client = SambaNova(
|
| 117 |
+
api_key=config.SAMBANOVA_API_KEY,
|
| 118 |
+
base_url="https://api.sambanova.ai/v1"
|
| 119 |
+
)
|
| 120 |
+
print("✅ Cliente SambaNova inicializado correctamente")
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f"❌ Error inicializando SambaNova: {e}")
|
| 123 |
+
else:
|
| 124 |
+
print("❌ SambaNova no disponible - verifica API key")
|
| 125 |
+
|
| 126 |
+
async def generate_text(self, model_type: str, model_name: str, prompt: str) -> str:
|
| 127 |
+
try:
|
| 128 |
+
if model_type == "sambanova":
|
| 129 |
+
if self.sn_client is None:
|
| 130 |
+
return "❌ Cliente SambaNova no disponible. Verifica tu API key."
|
| 131 |
+
return await self._generate_sambanova(model_name, prompt)
|
| 132 |
+
else:
|
| 133 |
+
return await self._generate_hf(model_name, prompt)
|
| 134 |
+
except Exception as e:
|
| 135 |
+
return f"❌ Error en generación: {str(e)}"
|
| 136 |
+
|
| 137 |
+
async def _generate_sambanova(self, model_name: str, prompt: str) -> str:
|
| 138 |
+
try:
|
| 139 |
+
# CORREGIDO: Manejo adecuado de llamadas async
|
| 140 |
+
response = await asyncio.get_event_loop().run_in_executor(
|
| 141 |
+
None,
|
| 142 |
+
lambda: self.sn_client.chat.completions.create(
|
| 143 |
+
model=model_name,
|
| 144 |
+
messages=[{"role": "user", "content": prompt}],
|
| 145 |
+
temperature=0.7,
|
| 146 |
+
top_p=0.9,
|
| 147 |
+
max_tokens=500
|
| 148 |
+
)
|
| 149 |
+
)
|
| 150 |
+
return response.choices[0].message.content
|
| 151 |
+
except Exception as e:
|
| 152 |
+
return f"❌ Error SambaNova API: {str(e)}"
|
| 153 |
+
|
| 154 |
+
async def _generate_hf(self, model_name: str, prompt: str) -> str:
|
| 155 |
+
try:
|
| 156 |
+
model, tokenizer = model_loader.load_hf_model(model_name)
|
| 157 |
+
if model is None or tokenizer is None:
|
| 158 |
+
return "❌ Error cargando modelo local"
|
| 159 |
+
|
| 160 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 161 |
+
|
| 162 |
+
# Mover inputs al dispositivo del modelo
|
| 163 |
+
if hasattr(model, 'device'):
|
| 164 |
+
inputs = {k: v.to(model.device) for k, v in inputs.items()}
|
| 165 |
+
|
| 166 |
+
with torch.no_grad():
|
| 167 |
+
outputs = model.generate(
|
| 168 |
+
**inputs,
|
| 169 |
+
max_new_tokens=256,
|
| 170 |
+
do_sample=True,
|
| 171 |
+
temperature=0.7,
|
| 172 |
+
pad_token_id=tokenizer.eos_token_id
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 176 |
+
# Remover el prompt del response
|
| 177 |
+
return response[len(prompt):].strip()
|
| 178 |
+
except Exception as e:
|
| 179 |
+
return f"❌ Error en modelo local: {str(e)}"
|
| 180 |
+
|
| 181 |
+
async def generate_image(self, prompt: str) -> Optional[Image.Image]:
|
| 182 |
+
if not config.BRIA_API_TOKEN:
|
| 183 |
+
return None
|
| 184 |
+
|
| 185 |
+
url = "https://api.bria.ai/v1/generate"
|
| 186 |
+
headers = {
|
| 187 |
+
"Authorization": f"Bearer {config.BRIA_API_TOKEN}",
|
| 188 |
+
"Content-Type": "application/json"
|
| 189 |
+
}
|
| 190 |
+
json_data = {
|
| 191 |
+
"prompt": prompt,
|
| 192 |
+
"options": {"resolution": "512x512"}
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
try:
|
| 196 |
+
response = await asyncio.get_event_loop().run_in_executor(
|
| 197 |
+
None,
|
| 198 |
+
lambda: requests.post(url, headers=headers, json=json_data, timeout=60)
|
| 199 |
+
)
|
| 200 |
+
response.raise_for_status()
|
| 201 |
+
data = response.json()
|
| 202 |
+
|
| 203 |
+
if "image_base64" in data:
|
| 204 |
+
img_bytes = base64.b64decode(data["image_base64"])
|
| 205 |
+
return Image.open(io.BytesIO(img_bytes))
|
| 206 |
+
else:
|
| 207 |
+
return None
|
| 208 |
+
except Exception as e:
|
| 209 |
+
print(f"Error generando imagen BRIA: {e}")
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
+
# ------------ INTERFAZ MEJORADA ------------
|
| 213 |
+
tools = AI_Tools()
|
| 214 |
+
|
| 215 |
+
async def process_input(message: str, image: Optional[Image.Image], history: list) -> list:
|
| 216 |
+
try:
|
| 217 |
+
msg_lower = message.lower()
|
| 218 |
+
|
| 219 |
+
# Detección de generación de imágenes
|
| 220 |
+
if image or any(k in msg_lower for k in ["imagen", "genera imagen", "foto", "dibujo", "picture"]):
|
| 221 |
+
img = await tools.generate_image(message)
|
| 222 |
+
if img:
|
| 223 |
+
return history + [(message, ("Imagen generada:", img))]
|
| 224 |
+
return history + [(message, "❌ Error generando imagen o BRIA no configurado")]
|
| 225 |
+
|
| 226 |
+
# Detección de generación de código
|
| 227 |
+
elif any(k in msg_lower for k in ["código", "code", "programa", "script", "función", "function"]):
|
| 228 |
+
model_name = MODELS["code"]["starcoder2"]
|
| 229 |
+
response = await tools.generate_text("hf", model_name, message)
|
| 230 |
+
# CORREGIDO: Formato adecuado para código
|
| 231 |
+
return history + [(message, f"```python\n{response}\n```")]
|
| 232 |
+
|
| 233 |
+
# Chat normal - prioridad a SambaNova
|
| 234 |
+
else:
|
| 235 |
+
response = ""
|
| 236 |
+
sambanova_used = False
|
| 237 |
+
|
| 238 |
+
# Intentar SambaNova primero si está disponible
|
| 239 |
+
if tools.sn_client is not None:
|
| 240 |
+
for smodel in MODELS["chat"]["sambanova"]["models"]:
|
| 241 |
+
if smodel.lower() in msg_lower:
|
| 242 |
+
response = await tools.generate_text("sambanova", smodel, message)
|
| 243 |
+
sambanova_used = True
|
| 244 |
+
break
|
| 245 |
+
|
| 246 |
+
# Fallback a modelo local
|
| 247 |
+
if not sambanova_used:
|
| 248 |
+
model_name = MODELS["chat"]["llama3"]
|
| 249 |
+
response = await tools.generate_text("hf", model_name, message)
|
| 250 |
+
|
| 251 |
+
return history + [(message, response)]
|
| 252 |
+
|
| 253 |
+
except Exception as e:
|
| 254 |
+
return history + [(message, f"❌ Error: {str(e)}")]
|
| 255 |
+
|
| 256 |
+
# ------------ APLICACIÓN GRADIO ------------
|
| 257 |
+
with gr.Blocks(title="MultiModel AI Assistant (SambaNova + Local)", theme=gr.themes.Soft()) as app:
|
| 258 |
+
gr.Markdown("# 🤖 MultiModel AI Assistant")
|
| 259 |
+
gr.Markdown("**Características:** ✅ SambaNova API ✅ Modelos Locales ✅ Generación de Imágenes")
|
| 260 |
+
|
| 261 |
+
with gr.Row():
|
| 262 |
+
with gr.Column(scale=4):
|
| 263 |
+
chatbot = gr.Chatbot(
|
| 264 |
+
height=500,
|
| 265 |
+
placeholder="Envía un mensaje para comenzar...",
|
| 266 |
+
show_copy_button=True
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
with gr.Row():
|
| 270 |
+
msg = gr.Textbox(
|
| 271 |
+
label="Tu mensaje",
|
| 272 |
+
placeholder="Escribe tu pregunta aquí...",
|
| 273 |
+
scale=4
|
| 274 |
+
)
|
| 275 |
+
submit_btn = gr.Button("Enviar 🚀", variant="primary", scale=1)
|
| 276 |
+
|
| 277 |
+
img_input = gr.Image(
|
| 278 |
+
type="pil",
|
| 279 |
+
label="Subir imagen (opcional)",
|
| 280 |
+
height=100
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# Estado del sistema
|
| 284 |
+
status = "✅ SambaNova: " + ("Conectado" if tools.sn_client else "No disponible")
|
| 285 |
+
gr.Markdown(f"**Estado del sistema:** {status}")
|
| 286 |
+
|
| 287 |
+
submit_btn.click(
|
| 288 |
+
process_input,
|
| 289 |
+
inputs=[msg, img_input, chatbot],
|
| 290 |
+
outputs=chatbot
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
# Enter para enviar
|
| 294 |
+
msg.submit(
|
| 295 |
+
process_input,
|
| 296 |
+
inputs=[msg, img_input, chatbot],
|
| 297 |
+
outputs=chatbot
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
if __name__ == "__main__":
|
| 301 |
+
print("🚀 Iniciando aplicación...")
|
| 302 |
+
app.launch(server_port=7860, share=False)
|