import sqlite3, os, bcrypt, cohere, gradio as gr from huggingface_hub import InferenceClient from duckduckgo_search import DDGS # --- CONFIGURACIÓN DE APIS --- HF_TOKEN = os.getenv("HF_TOKEN") COHERE_KEY = os.getenv("COHERE_API_KEY") hf = InferenceClient(token=HF_TOKEN) if HF_TOKEN else None co = cohere.Client(api_key=COHERE_KEY) if COHERE_KEY else None # --- BASE DE DATOS (NUEVA VERSIÓN) --- DB_NAME = "chaty_v8.db" def init_db(): with sqlite3.connect(DB_NAME) as conn: conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT UNIQUE, pass TEXT)") init_db() def auth_handler(u, p, mode): if not u or not p: return "⚠️ Datos incompletos" try: with sqlite3.connect(DB_NAME) as conn: if mode == "Reg": h = bcrypt.hashpw(p.encode(), bcrypt.gensalt()).decode() try: conn.execute("INSERT INTO users (user, pass) VALUES (?, ?)", (u, h)) return "✅ Registro exitoso. ¡Entra ahora!" except: return "❌ El usuario ya existe." else: row = conn.execute("SELECT id, pass FROM users WHERE user = ?", (u,)).fetchone() if row and bcrypt.checkpw(p.encode(), row[1].encode()): return row[0] return None except: return "❌ Error de conexión con la base de datos." # --- MOTOR DE INTELIGENCIA --- def ai_logic(msg, hist, uid): if uid is None: return hist, None, "⚠️ Por favor, inicia sesión primero." hist = hist or [] m = msg.lower() try: # Modo Dibujo if any(w in m for w in ["dibuja", "imagen", "foto"]): img = hf.text_to_image(msg, model="stabilityai/stable-diffusion-xl-base-1.0") path = f"img_{uid}.png" img.save(path) hist.append((msg, "🎨 ¡Hecho! Aquí tienes tu dibujo:")) return hist, path, "" # Modo Búsqueda if any(w in m for w in ["busca", "noticias", "quien", "precio"]): with DDGS() as ddgs: res = list(ddgs.text(msg, max_results=3)) info = "🌐 **Última hora:**\n" + "\n".join([f"- {r['title']}" for r in res]) hist.append((msg, info)) return hist, None, "" # Modo Chat Normal res = co.chat(message=msg, model="command-r").text hist.append((msg, res)) return hist, None, "" except Exception as e: return hist, None, f"❌ Error de red: {str(e)[:50]}" # --- INTERFAZ DE USUARIO --- with gr.Blocks(theme=gr.themes.Soft(primary_hue="red"), css=".gradio-container {background-color: #050505}") as demo: gr.HTML("