ChatyPro / app.py
Chaty12's picture
Update app.py
45b0bdf verified
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("<h1 style='text-align:center; color:red; text-shadow: 0 0 10px red;'>🔴 CHATY PRO v8.0</h1>")
user_id = gr.State(None)
with gr.Tabs() as main_tabs:
# PESTAÑA 1: LOGIN
with gr.Tab("🔑 ACCESO", id="tab_login"):
with gr.Column(variant="panel"):
u_txt = gr.Textbox(label="Usuario")
p_txt = gr.Textbox(label="Contraseña", type="password")
with gr.Row():
btn_reg = gr.Button("REGISTRAR")
btn_log = gr.Button("ENTRAR", variant="primary")
info_msg = gr.Markdown("Bienvenido. Registra un usuario o entra con el tuyo.")
# PESTAÑA 2: PANEL DE CONTROL
with gr.Tab("💬 CHAT & IA", id="tab_chat"):
with gr.Row():
with gr.Column(scale=3):
chat_bot = gr.Chatbot(height=400, label="Chaty Intelligence")
msg_in = gr.Textbox(placeholder="Pide un dibujo, una noticia o solo charla...", label="Tu mensaje")
with gr.Column(scale=2):
res_img = gr.Image(label="Resultado Visual")
btn_go = gr.Button("EJECUTAR ACCIÓN", variant="primary")
# --- EVENTOS ---
def start_session(u, p):
res = auth_handler(u, p, "Log")
if isinstance(res, int):
return res, "✅ Acceso correcto", gr.Tabs(selected="tab_chat")
return None, "❌ Usuario o clave incorrectos", gr.Tabs(selected="tab_login")
# Registro de eventos con nombres de API simplificados
btn_log.click(start_session, [u_txt, p_txt], [user_id, info_msg, main_tabs], api_name="do_login")
btn_reg.click(lambda u,p: auth_handler(u,p,"Reg"), [u_txt, p_txt], info_msg, api_name="do_reg")
# Ejecución de Chat
btn_go.click(ai_logic, [msg_in, chat_bot, user_id], [chat_bot, res_img, msg_in], api_name="do_chat")
msg_in.submit(ai_logic, [msg_in, chat_bot, user_id], [chat_bot, res_img, msg_in], api_name="do_submit")
if __name__ == "__main__":
demo.queue().launch(show_api=False)