Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,96 +2,104 @@ import sqlite3, os, bcrypt, cohere, gradio as gr
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
from duckduckgo_search import DDGS
|
| 4 |
|
| 5 |
-
# --- CONFIGURACIÓN ---
|
| 6 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 7 |
COHERE_KEY = os.getenv("COHERE_API_KEY")
|
| 8 |
hf = InferenceClient(token=HF_TOKEN) if HF_TOKEN else None
|
| 9 |
co = cohere.Client(api_key=COHERE_KEY) if COHERE_KEY else None
|
| 10 |
|
| 11 |
-
# ---
|
| 12 |
-
|
| 13 |
def init_db():
|
| 14 |
-
with sqlite3.connect(
|
| 15 |
conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT UNIQUE, pass TEXT)")
|
| 16 |
init_db()
|
| 17 |
|
| 18 |
-
def
|
| 19 |
-
if not u or not p: return "⚠️
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
# ---
|
| 33 |
-
def
|
| 34 |
-
if
|
| 35 |
hist = hist or []
|
| 36 |
m = msg.lower()
|
| 37 |
try:
|
| 38 |
-
#
|
| 39 |
if any(w in m for w in ["dibuja", "imagen", "foto"]):
|
| 40 |
img = hf.text_to_image(msg, model="stabilityai/stable-diffusion-xl-base-1.0")
|
| 41 |
-
path = f"
|
| 42 |
img.save(path)
|
| 43 |
-
hist.append((msg, "🎨 Aquí tienes tu
|
| 44 |
return hist, path, ""
|
| 45 |
-
|
| 46 |
-
|
|
|
|
| 47 |
with DDGS() as ddgs:
|
| 48 |
-
res = list(ddgs.text(msg, max_results=
|
| 49 |
-
|
| 50 |
-
hist.append((msg,
|
| 51 |
return hist, None, ""
|
| 52 |
-
|
|
|
|
| 53 |
res = co.chat(message=msg, model="command-r").text
|
| 54 |
hist.append((msg, res))
|
| 55 |
return hist, None, ""
|
| 56 |
-
except
|
|
|
|
| 57 |
|
| 58 |
-
# --- INTERFAZ
|
| 59 |
-
with gr.Blocks(theme=gr.themes.Soft(primary_hue="red"), css="
|
| 60 |
-
gr.HTML("<h1 style='text-align:center;'>🔴 CHATY PRO
|
| 61 |
-
|
| 62 |
|
| 63 |
-
with gr.Tabs() as
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
|
|
|
|
| 73 |
with gr.Row():
|
|
|
|
|
|
|
|
|
|
| 74 |
with gr.Column(scale=2):
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
with gr.Column(scale=1):
|
| 78 |
-
img_ui = gr.Image(label="Visual", height=300)
|
| 79 |
-
btn_run = gr.Button("ENVIAR", variant="primary")
|
| 80 |
|
| 81 |
-
# ---
|
| 82 |
-
def
|
| 83 |
-
res =
|
| 84 |
if isinstance(res, int):
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
return None, "❌ Credenciales incorrectas", gr.Tabs(selected=0)
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
|
| 94 |
-
msg_in.submit(
|
| 95 |
|
| 96 |
if __name__ == "__main__":
|
| 97 |
-
demo.queue().launch()
|
|
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
from duckduckgo_search import DDGS
|
| 4 |
|
| 5 |
+
# --- CONFIGURACIÓN DE APIS ---
|
| 6 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 7 |
COHERE_KEY = os.getenv("COHERE_API_KEY")
|
| 8 |
hf = InferenceClient(token=HF_TOKEN) if HF_TOKEN else None
|
| 9 |
co = cohere.Client(api_key=COHERE_KEY) if COHERE_KEY else None
|
| 10 |
|
| 11 |
+
# --- BASE DE DATOS (NUEVA VERSIÓN) ---
|
| 12 |
+
DB_NAME = "chaty_v8.db"
|
| 13 |
def init_db():
|
| 14 |
+
with sqlite3.connect(DB_NAME) as conn:
|
| 15 |
conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT UNIQUE, pass TEXT)")
|
| 16 |
init_db()
|
| 17 |
|
| 18 |
+
def auth_handler(u, p, mode):
|
| 19 |
+
if not u or not p: return "⚠️ Datos incompletos"
|
| 20 |
+
try:
|
| 21 |
+
with sqlite3.connect(DB_NAME) as conn:
|
| 22 |
+
if mode == "Reg":
|
| 23 |
+
h = bcrypt.hashpw(p.encode(), bcrypt.gensalt()).decode()
|
| 24 |
+
try:
|
| 25 |
+
conn.execute("INSERT INTO users (user, pass) VALUES (?, ?)", (u, h))
|
| 26 |
+
return "✅ Registro exitoso. ¡Entra ahora!"
|
| 27 |
+
except: return "❌ El usuario ya existe."
|
| 28 |
+
else:
|
| 29 |
+
row = conn.execute("SELECT id, pass FROM users WHERE user = ?", (u,)).fetchone()
|
| 30 |
+
if row and bcrypt.checkpw(p.encode(), row[1].encode()): return row[0]
|
| 31 |
+
return None
|
| 32 |
+
except: return "❌ Error de conexión con la base de datos."
|
| 33 |
|
| 34 |
+
# --- MOTOR DE INTELIGENCIA ---
|
| 35 |
+
def ai_logic(msg, hist, uid):
|
| 36 |
+
if uid is None: return hist, None, "⚠️ Por favor, inicia sesión primero."
|
| 37 |
hist = hist or []
|
| 38 |
m = msg.lower()
|
| 39 |
try:
|
| 40 |
+
# Modo Dibujo
|
| 41 |
if any(w in m for w in ["dibuja", "imagen", "foto"]):
|
| 42 |
img = hf.text_to_image(msg, model="stabilityai/stable-diffusion-xl-base-1.0")
|
| 43 |
+
path = f"img_{uid}.png"
|
| 44 |
img.save(path)
|
| 45 |
+
hist.append((msg, "🎨 ¡Hecho! Aquí tienes tu dibujo:"))
|
| 46 |
return hist, path, ""
|
| 47 |
+
|
| 48 |
+
# Modo Búsqueda
|
| 49 |
+
if any(w in m for w in ["busca", "noticias", "quien", "precio"]):
|
| 50 |
with DDGS() as ddgs:
|
| 51 |
+
res = list(ddgs.text(msg, max_results=3))
|
| 52 |
+
info = "🌐 **Última hora:**\n" + "\n".join([f"- {r['title']}" for r in res])
|
| 53 |
+
hist.append((msg, info))
|
| 54 |
return hist, None, ""
|
| 55 |
+
|
| 56 |
+
# Modo Chat Normal
|
| 57 |
res = co.chat(message=msg, model="command-r").text
|
| 58 |
hist.append((msg, res))
|
| 59 |
return hist, None, ""
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return hist, None, f"❌ Error de red: {str(e)[:50]}"
|
| 62 |
|
| 63 |
+
# --- INTERFAZ DE USUARIO ---
|
| 64 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="red"), css=".gradio-container {background-color: #050505}") as demo:
|
| 65 |
+
gr.HTML("<h1 style='text-align:center; color:red; text-shadow: 0 0 10px red;'>🔴 CHATY PRO v8.0</h1>")
|
| 66 |
+
user_id = gr.State(None)
|
| 67 |
|
| 68 |
+
with gr.Tabs() as main_tabs:
|
| 69 |
+
# PESTAÑA 1: LOGIN
|
| 70 |
+
with gr.Tab("🔑 ACCESO", id="tab_login"):
|
| 71 |
+
with gr.Column(variant="panel"):
|
| 72 |
+
u_txt = gr.Textbox(label="Usuario")
|
| 73 |
+
p_txt = gr.Textbox(label="Contraseña", type="password")
|
| 74 |
+
with gr.Row():
|
| 75 |
+
btn_reg = gr.Button("REGISTRAR")
|
| 76 |
+
btn_log = gr.Button("ENTRAR", variant="primary")
|
| 77 |
+
info_msg = gr.Markdown("Bienvenido. Registra un usuario o entra con el tuyo.")
|
| 78 |
|
| 79 |
+
# PESTAÑA 2: PANEL DE CONTROL
|
| 80 |
+
with gr.Tab("💬 CHAT & IA", id="tab_chat"):
|
| 81 |
with gr.Row():
|
| 82 |
+
with gr.Column(scale=3):
|
| 83 |
+
chat_bot = gr.Chatbot(height=400, label="Chaty Intelligence")
|
| 84 |
+
msg_in = gr.Textbox(placeholder="Pide un dibujo, una noticia o solo charla...", label="Tu mensaje")
|
| 85 |
with gr.Column(scale=2):
|
| 86 |
+
res_img = gr.Image(label="Resultado Visual")
|
| 87 |
+
btn_go = gr.Button("EJECUTAR ACCIÓN", variant="primary")
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
# --- EVENTOS ---
|
| 90 |
+
def start_session(u, p):
|
| 91 |
+
res = auth_handler(u, p, "Log")
|
| 92 |
if isinstance(res, int):
|
| 93 |
+
return res, "✅ Acceso correcto", gr.Tabs(selected="tab_chat")
|
| 94 |
+
return None, "❌ Usuario o clave incorrectos", gr.Tabs(selected="tab_login")
|
|
|
|
| 95 |
|
| 96 |
+
# Registro de eventos con nombres de API simplificados
|
| 97 |
+
btn_log.click(start_session, [u_txt, p_txt], [user_id, info_msg, main_tabs], api_name="do_login")
|
| 98 |
+
btn_reg.click(lambda u,p: auth_handler(u,p,"Reg"), [u_txt, p_txt], info_msg, api_name="do_reg")
|
| 99 |
|
| 100 |
+
# Ejecución de Chat
|
| 101 |
+
btn_go.click(ai_logic, [msg_in, chat_bot, user_id], [chat_bot, res_img, msg_in], api_name="do_chat")
|
| 102 |
+
msg_in.submit(ai_logic, [msg_in, chat_bot, user_id], [chat_bot, res_img, msg_in], api_name="do_submit")
|
| 103 |
|
| 104 |
if __name__ == "__main__":
|
| 105 |
+
demo.queue().launch(show_api=False)
|