Chaty12 commited on
Commit
45b0bdf
·
verified ·
1 Parent(s): 354c352

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -60
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
- # --- DATABASE ---
12
- DB_PATH = "chaty.db"
13
  def init_db():
14
- with sqlite3.connect(DB_PATH) 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_logic(u, p, mode):
19
- if not u or not p: return "⚠️ Completa los campos"
20
- with sqlite3.connect(DB_PATH) as conn:
21
- if mode == "Reg":
22
- h = bcrypt.hashpw(p.encode(), bcrypt.gensalt()).decode()
23
- try:
24
- conn.execute("INSERT INTO users (user, pass) VALUES (?, ?)", (u, h))
25
- return " Usuario listo. Ya puedes entrar."
26
- except: return " El nombre ya existe."
27
- else:
28
- row = conn.execute("SELECT id, pass FROM users WHERE user = ?", (u,)).fetchone()
29
- if row and bcrypt.checkpw(p.encode(), row[1].encode()): return row[0]
30
- return None
 
 
31
 
32
- # --- ENGINE ---
33
- def chat_engine(msg, hist, uid):
34
- if not uid: return hist, None, "⚠️ Error: Sesión no válida"
35
  hist = hist or []
36
  m = msg.lower()
37
  try:
38
- # IMAGEN
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"gen_{uid}.png"
42
  img.save(path)
43
- hist.append((msg, "🎨 Aquí tienes tu creación:"))
44
  return hist, path, ""
45
- # BÚSQUEDA
46
- if any(w in m for w in ["busca", "noticias", "quien"]):
 
47
  with DDGS() as ddgs:
48
- res = list(ddgs.text(msg, max_results=2))
49
- txt = "🌐 **Info Web:**\n" + "\n".join([f"- {r['title']}" for r in res])
50
- hist.append((msg, txt))
51
  return hist, None, ""
52
- # CHAT
 
53
  res = co.chat(message=msg, model="command-r").text
54
  hist.append((msg, res))
55
  return hist, None, ""
56
- except: return hist, None, "❌ Error de conexión"
 
57
 
58
- # --- INTERFAZ PLANA (SIN OCULTAR COLUMNAS) ---
59
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="red"), css="h1 {color: red;}") as demo:
60
- gr.HTML("<h1 style='text-align:center;'>🔴 CHATY PRO v7.0</h1>")
61
- user_session = gr.State(None)
62
 
63
- with gr.Tabs() as tabs:
64
- with gr.Tab("🔑 LOGIN", id=0):
65
- u_in = gr.Textbox(label="Usuario")
66
- p_in = gr.Textbox(label="Clave", type="password")
67
- with gr.Row():
68
- btn_reg = gr.Button("REGISTRAR")
69
- btn_log = gr.Button("ENTRAR", variant="primary")
70
- status = gr.Markdown("Inicia sesión para desbloquear el chat.")
 
 
71
 
72
- with gr.Tab("💬 CHAT", id=1):
 
73
  with gr.Row():
 
 
 
74
  with gr.Column(scale=2):
75
- chat_ui = gr.Chatbot(height=450)
76
- msg_in = gr.Textbox(placeholder="Escribe aquí...", show_label=False)
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
- # --- LÓGICA DE BOTONES ---
82
- def handle_login(u, p):
83
- res = auth_logic(u, p, "Log")
84
  if isinstance(res, int):
85
- # Cambia a la pestaña de chat y guarda el ID
86
- return res, " Acceso concedido", gr.Tabs(selected=1)
87
- return None, "❌ Credenciales incorrectas", gr.Tabs(selected=0)
88
 
89
- btn_log.click(handle_login, [u_in, p_in], [user_session, status, tabs], api_name="login_final")
90
- btn_reg.click(lambda u,p: auth_user(u,p,"Reg"), [u_in, p_in], status, api_name="reg_final")
 
91
 
92
- # Evento unificado de chat
93
- btn_run.click(chat_engine, [msg_in, chat_ui, user_session], [chat_ui, img_ui, msg_in], api_name="chat_final")
94
- msg_in.submit(chat_engine, [msg_in, chat_ui, user_session], [chat_ui, img_ui, msg_in], api_name="chat_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)