Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import random
|
| 3 |
import time
|
|
@@ -5,322 +8,535 @@ import json
|
|
| 5 |
from datetime import datetime, timedelta
|
| 6 |
import os
|
| 7 |
import asyncio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
# ---
|
|
|
|
| 10 |
import firebase_admin
|
| 11 |
from firebase_admin import credentials, firestore
|
| 12 |
|
| 13 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
class Config:
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
}
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
if not firebase_admin._apps:
|
| 32 |
firebase_credentials_json = os.getenv('GOOGLE_APPLICATION_CREDENTIALS_JSON')
|
| 33 |
if firebase_credentials_json:
|
| 34 |
cred_dict = json.loads(firebase_credentials_json)
|
|
|
|
| 35 |
if 'project_id' not in cred_dict:
|
| 36 |
-
cred_dict['project_id'] = 'mateai-815ca'
|
| 37 |
cred = credentials.Certificate(cred_dict)
|
| 38 |
firebase_admin.initialize_app(cred)
|
| 39 |
-
|
|
|
|
| 40 |
else:
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
except Exception as e:
|
| 43 |
-
|
| 44 |
-
print(f"Error al inicializar Firebase: {e}")
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
# --- MODELOS DE DATOS Y LÓGICA DE NEGOCIO ---
|
| 49 |
-
# --- (Omitidos por brevedad, son idénticos a los de la versión anterior. Se pegarán abajo para tener el script completo) ---
|
| 50 |
-
|
| 51 |
-
# --- MODELOS DE DATOS Y LÓGICA DE NEGOCIO ---
|
| 52 |
class User:
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
self.
|
| 56 |
-
|
| 57 |
-
self.
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
self.
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
self.
|
| 65 |
-
self.
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
return {
|
| 69 |
-
"user_id": self.user_id,
|
| 70 |
-
"
|
| 71 |
-
"
|
| 72 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
}
|
| 74 |
|
| 75 |
-
class Nudge:
|
| 76 |
-
def __init__(self, text_template, type, context_tags, cultural_tags):
|
| 77 |
-
self.text_template, self.type, self.context_tags, self.cultural_tags = text_template, type, context_tags, cultural_tags
|
| 78 |
-
|
| 79 |
-
class UserManager:
|
| 80 |
@classmethod
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
except Exception as e:
|
| 94 |
-
return None, f"Error al crear usuario en Firestore: {e}"
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
try:
|
|
|
|
| 101 |
doc = await asyncio.to_thread(user_doc_ref.get)
|
| 102 |
if doc.exists:
|
| 103 |
user_data = doc.to_dict()
|
| 104 |
-
#
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
# ... (El resto de UserManager, ContextEngine, NudgeGenerator, etc., son robustos y no necesitan cambios)
|
| 116 |
|
| 117 |
-
class ContextEngine:
|
| 118 |
@staticmethod
|
| 119 |
-
def
|
| 120 |
-
|
| 121 |
-
if
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
@staticmethod
|
| 125 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
self.
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
gr.Warning("¡Che, poné tu ID para cargar el perfil!")
|
| 144 |
-
return None, gr.update(), gr.update(), gr.update()
|
| 145 |
-
user
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
return None, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 150 |
-
user, msg = await UserManager.create_user(username, {"tipo_susurro": prefs_tipo})
|
| 151 |
|
| 152 |
if user:
|
| 153 |
gr.Success(msg)
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
return
|
| 158 |
-
gr.update(value=user.preferences.get("tipo_susurro", "ambos")),
|
| 159 |
-
gr.update(value=user.preferences.get("modo_che_tranqui", False)),
|
| 160 |
-
gr.update(value=user.preferences.get("voice_uri", "default")),
|
| 161 |
-
task_list, task_dropdown)
|
| 162 |
else:
|
| 163 |
-
gr.
|
| 164 |
-
return None,
|
| 165 |
|
| 166 |
-
async def
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
await UserManager.update_user_data(user)
|
| 174 |
-
gr.Success("¡Preferencias actualizadas, master!")
|
| 175 |
-
return user, f"¡Hola de nuevo, {user.name}! Eco-Puntos: {user.eco_points}"
|
| 176 |
-
|
| 177 |
-
async def get_task_updates(user):
|
| 178 |
-
if not user or not user.tasks:
|
| 179 |
-
return "No tenés tareas pendientes.", gr.Dropdown(choices=[], value=None, label="Seleccioná una tarea para completar")
|
| 180 |
-
task_list_str = "\n".join([f"• {t['task']}" for t in user.tasks])
|
| 181 |
-
task_choices = [t['task'] for t in user.tasks]
|
| 182 |
-
return task_list_str, gr.Dropdown(choices=task_choices, value=None, label="Seleccioná una tarea para completar")
|
| 183 |
-
|
| 184 |
-
async def add_task(user, task_name):
|
| 185 |
-
if not user: return user, gr.Warning("Iniciá sesión para agregar tareas."), gr.update(), gr.update()
|
| 186 |
-
if not task_name: return user, gr.Info("¿Qué tarea querés agregar?"), gr.update(), gr.update()
|
| 187 |
-
user.tasks.append({"task": task_name, "added_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')})
|
| 188 |
-
await UserManager.update_user_data(user)
|
| 189 |
-
task_list, task_dropdown = await get_task_updates(user)
|
| 190 |
-
return user, gr.Success(f"Tarea '{task_name}' agregada."), task_list, task_dropdown
|
| 191 |
-
|
| 192 |
-
async def complete_task(user, task_to_complete):
|
| 193 |
-
if not user: return user, gr.Warning("Iniciá sesión para completar tareas."), gr.update(), gr.update()
|
| 194 |
-
if not task_to_complete: return user, gr.Info("Seleccioná una tarea de la lista."), gr.update(), gr.update()
|
| 195 |
-
user.tasks = [t for t in user.tasks if t['task'] != task_to_complete]
|
| 196 |
-
await UserManager.update_user_data(user)
|
| 197 |
-
task_list, task_dropdown = await get_task_updates(user)
|
| 198 |
-
return user, gr.Success(f"¡Bien ahí! Tarea '{task_to_complete}' completada."), task_list, task_dropdown
|
| 199 |
-
|
| 200 |
-
async def get_oracle(user):
|
| 201 |
-
if not user: return gr.Warning("Iniciá sesión para consultar al Oráculo."), ""
|
| 202 |
-
revelation = await NudgeGenerator(UserManager, ContextEngine).get_daily_oracle_revelation(user.user_id)
|
| 203 |
-
return revelation, revelation
|
| 204 |
-
|
| 205 |
-
async def get_challenge(user):
|
| 206 |
-
if not user: return gr.Warning("Iniciá sesión para recibir un desafío."), ""
|
| 207 |
-
challenge = await NudgeGenerator(UserManager, ContextEngine).get_mateai_challenge(user.user_id)
|
| 208 |
-
return challenge, challenge
|
| 209 |
-
|
| 210 |
-
async def process_chat(user, message, chat_history, conv_context):
|
| 211 |
-
if not user:
|
| 212 |
-
gr.Warning("¡Che, para arrancar, cargá tu perfil en la pestaña 'Perfil y Configuración'!")
|
| 213 |
-
return user, chat_history, conv_context, "", gr.update(), gr.update(), gr.update()
|
| 214 |
-
|
| 215 |
-
# SOLUCIÓN: Usar el formato de `messages` para el historial de chat
|
| 216 |
chat_history.append({"role": "user", "content": message})
|
| 217 |
-
msg_lower = message.lower()
|
| 218 |
-
response, task_list, task_dropdown, notif = "", gr.update(), gr.update(), gr.update()
|
| 219 |
-
|
| 220 |
-
if "agregar tarea" in msg_lower or "anotá esto" in msg_lower:
|
| 221 |
-
task_name = message.replace("agregar tarea", "", 1).replace("anotá esto", "", 1).strip()
|
| 222 |
-
user, notif, task_list, task_dropdown = await add_task(user, task_name)
|
| 223 |
-
response = f"¡Listo! Tarea '{task_name}' agregada."
|
| 224 |
-
elif "oráculo" in msg_lower or "revelación" in msg_lower:
|
| 225 |
-
response, _ = await get_oracle(user)
|
| 226 |
-
elif "desafío" in msg_lower or "reto" in msg_lower:
|
| 227 |
-
response, _ = await get_challenge(user)
|
| 228 |
-
else:
|
| 229 |
-
location = random.choice(["Casa", "Oficina/Estudio", "Aire Libre/Calle"])
|
| 230 |
-
activity = random.choice(["Trabajando", "Relajado", "Ejercicio"])
|
| 231 |
-
response, _, _, _, _ = await NudgeGenerator(UserManager, ContextEngine).generate_nudge(user.user_id, location, activity, "Bien")
|
| 232 |
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
return user, chat_history, conv_context, (response, voice_uri), task_list, task_dropdown, notif
|
| 236 |
|
| 237 |
-
#
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
gr.HTML("""...""") # El JS para la voz no cambia
|
| 245 |
-
|
| 246 |
-
with gr.Row():
|
| 247 |
-
welcome_message = gr.Markdown("### 🧉 ¡Bienvenido a MateAI! Iniciá sesión o creá un perfil para empezar.")
|
| 248 |
-
|
| 249 |
-
with gr.Tabs() as tabs:
|
| 250 |
-
with gr.TabItem("💬 Conversar con MateAI", id=0):
|
| 251 |
-
# SOLUCIÓN: Corregir advertencias de Gradio
|
| 252 |
-
chatbot = gr.Chatbot(label="Conversación", height=450, type="messages")
|
| 253 |
-
with gr.Row():
|
| 254 |
-
chat_input = gr.Textbox(show_label=False, placeholder="Escribí acá o usá el micrófono...", scale=4)
|
| 255 |
-
send_button = gr.Button("Enviar", variant="primary", scale=1)
|
| 256 |
-
gr.Button("🎙️ Hablar con MateAI", elem_id="voice_btn")
|
| 257 |
-
|
| 258 |
-
with gr.TabItem("👤 Perfil y Configuración", id=1):
|
| 259 |
-
with gr.Row():
|
| 260 |
-
with gr.Column(scale=1):
|
| 261 |
-
gr.Markdown("#### 🧉 Usuario Nuevo")
|
| 262 |
-
username_input = gr.Textbox(label="Tu Nombre o Apodo")
|
| 263 |
-
prefs_tipo_inicial = gr.Dropdown(["ambos", "eco", "bienestar"], label="Preferencia de Susurros", value="ambos")
|
| 264 |
-
create_button = gr.Button("¡Crear Perfil!", variant="primary")
|
| 265 |
-
with gr.Column(scale=1):
|
| 266 |
-
gr.Markdown("#### 🧉 Cargar Perfil")
|
| 267 |
-
userid_input = gr.Textbox(label="Tu ID de Usuario")
|
| 268 |
-
login_button = gr.Button("Cargar Perfil")
|
| 269 |
-
|
| 270 |
-
with gr.Group(interactive=False) as prefs_group:
|
| 271 |
-
gr.Markdown("--- \n ### ⚙️ Tus Preferencias")
|
| 272 |
-
prefs_tipo_update = gr.Dropdown(["ambos", "eco", "bienestar"], label="Tipo de susurro preferido")
|
| 273 |
-
prefs_tranqui_update = gr.Checkbox(label="Activar 'Modo Che, Tranqui'")
|
| 274 |
-
# SOLUCIÓN: Permitir valor custom para evitar warning al inicio
|
| 275 |
-
voice_selector = gr.Dropdown(label="Selector de Voz (si la automática no te gusta)", choices=[], value="default", allow_custom_value=True)
|
| 276 |
-
update_prefs_button = gr.Button("Guardar Preferencias", variant="primary")
|
| 277 |
-
|
| 278 |
-
with gr.TabItem("📝 Gestor de Tareas", id=2):
|
| 279 |
-
with gr.Row():
|
| 280 |
-
with gr.Column():
|
| 281 |
-
gr.Markdown("#### ➕ **Agregar Tarea**")
|
| 282 |
-
new_task_input = gr.Textbox(label="Nombre de la nueva tarea")
|
| 283 |
-
add_task_button = gr.Button("Agregar", variant="primary")
|
| 284 |
-
with gr.Column():
|
| 285 |
-
gr.Markdown("#### ✔️ **Completar Tarea**")
|
| 286 |
-
task_to_complete_dd = gr.Dropdown(label="Seleccioná una tarea para completar", choices=[])
|
| 287 |
-
complete_task_button = gr.Button("¡Tarea Lista!")
|
| 288 |
-
gr.Markdown("--- \n ### 📋 Tus Tareas Pendientes")
|
| 289 |
-
task_list_output = gr.Markdown("No tenés tareas pendientes.")
|
| 290 |
-
|
| 291 |
-
with gr.TabItem("✨ Oráculo & Desafíos", id=3):
|
| 292 |
-
with gr.Row():
|
| 293 |
-
with gr.Column():
|
| 294 |
-
gr.Markdown("### ✨ La Revelación Diaria")
|
| 295 |
-
oracle_button = gr.Button("Consultar al Oráculo")
|
| 296 |
-
oracle_output = gr.Textbox(label="El Oráculo dice...", lines=5, interactive=False)
|
| 297 |
-
with gr.Column():
|
| 298 |
-
gr.Markdown("### 🎯 Desafío MateAI")
|
| 299 |
-
challenge_button = gr.Button("¡Dame un Desafío!")
|
| 300 |
-
challenge_output = gr.Textbox(label="Tu misión es...", lines=5, interactive=False)
|
| 301 |
-
|
| 302 |
-
# --- LÓGICA DE EVENTOS DE LA INTERFAZ ---
|
| 303 |
-
demo.load(fn=None, inputs=None, outputs=[voice_selector], js="async () => { return window.getVoices() }")
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
create_button.click(fn=login_or_create_user, inputs=[gr.State("create"), username_input, userid_input, prefs_tipo_inicial], outputs=login_outputs)
|
| 308 |
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
-
|
| 315 |
-
|
| 316 |
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 326 |
demo.launch(debug=True)
|
|
|
|
| 1 |
+
# app.py - MateAI v18.3: Conciencia Aumentada
|
| 2 |
+
# Arquitectura por un asistente de IA para un futuro colaborativo.
|
| 3 |
+
|
| 4 |
import gradio as gr
|
| 5 |
import random
|
| 6 |
import time
|
|
|
|
| 8 |
from datetime import datetime, timedelta
|
| 9 |
import os
|
| 10 |
import asyncio
|
| 11 |
+
import logging
|
| 12 |
+
from typing import Dict, Any, List, Optional, Tuple
|
| 13 |
+
|
| 14 |
+
# --- LIBRERÍAS DE IA Y NLP ---
|
| 15 |
+
# Usaremos pysentimiento para un análisis de sentimiento robusto en español.
|
| 16 |
+
from pysentimiento import create_analyzer
|
| 17 |
|
| 18 |
+
# --- INTEGRACIÓN CON FIREBASE ---
|
| 19 |
+
# Firebase se usará como nuestro "núcleo de memoria" persistente.
|
| 20 |
import firebase_admin
|
| 21 |
from firebase_admin import credentials, firestore
|
| 22 |
|
| 23 |
+
# ==============================================================================
|
| 24 |
+
# MÓDULO 1: CONFIGURACIÓN Y CONSTANTES DEL SISTEMA
|
| 25 |
+
# ==============================================================================
|
| 26 |
+
# Define el comportamiento global, los límites y las constantes de la aplicación.
|
| 27 |
+
# Es la "constitución" de MateAI.
|
| 28 |
+
# ==============================================================================
|
| 29 |
+
|
| 30 |
class Config:
|
| 31 |
+
"""Clase de configuración central para todos los parámetros de MateAI."""
|
| 32 |
+
APP_NAME = "MateAI v18.3: Conciencia Aumentada"
|
| 33 |
+
APP_VERSION = "18.3.0-alpha"
|
| 34 |
+
|
| 35 |
+
# --- Configuración de Base de Datos ---
|
| 36 |
+
FIREBASE_COLLECTION_USERS = "users_v18" # Nueva colección para la arquitectura avanzada.
|
| 37 |
+
|
| 38 |
+
# --- Parámetros del Motor de Personalidad (Basado en el Modelo OCEAN) ---
|
| 39 |
+
# Estos son los valores iniciales para un nuevo usuario.
|
| 40 |
+
# El rango de cada rasgo es de -1.0 (bajo) a 1.0 (alto).
|
| 41 |
+
DEFAULT_PSYCH_PROFILE = {
|
| 42 |
+
"openness": 0.0, # Apertura a nuevas experiencias
|
| 43 |
+
"conscientiousness": 0.0, # Organización y responsabilidad
|
| 44 |
+
"extraversion": 0.0, # Sociabilidad y energía
|
| 45 |
+
"agreeableness": 0.0, # Amabilidad y cooperación
|
| 46 |
+
"neuroticism": 0.0, # Estabilidad emocional (inversa)
|
| 47 |
}
|
| 48 |
+
|
| 49 |
+
# --- Parámetros del Motor de Gamificación ---
|
| 50 |
+
POINTS_PER_INSIGHT = 10 # Puntos por una reflexión profunda.
|
| 51 |
+
POINTS_PER_GOAL_COMPLETED = 25# Puntos por completar una meta a largo plazo.
|
| 52 |
+
POINTS_PER_FEEDBACK = 5 # Puntos por dar feedback a MateAI.
|
| 53 |
+
|
| 54 |
+
# --- Parámetros del Motor de Interacción ---
|
| 55 |
+
PROACTIVE_CHECKIN_HOURS = 6 # Horas antes de que MateAI considere un "check-in".
|
| 56 |
+
MAX_MEMORY_STREAM_ITEMS = 200 # Límite de recuerdos para no sobrecargar el perfil.
|
| 57 |
+
SENTIMENT_THRESHOLD_NEGATIVE = -0.3 # Umbral para detectar sentimiento negativo.
|
| 58 |
+
SENTIMENT_THRESHOLD_POSITIVE = 0.3 # Umbral para detectar sentimiento positivo.
|
| 59 |
|
| 60 |
+
# ==============================================================================
|
| 61 |
+
# MÓDULO 2: INICIALIZACIÓN DE SERVICIOS EXTERNOS
|
| 62 |
+
# ==============================================================================
|
| 63 |
+
# Conexión a la base de datos y carga de modelos de IA.
|
| 64 |
+
# Este bloque se ejecuta una sola vez al iniciar la aplicación.
|
| 65 |
+
# ==============================================================================
|
| 66 |
+
|
| 67 |
+
# --- Configuración de Logging ---
|
| 68 |
+
# Un buen logging es crucial para depurar un sistema complejo.
|
| 69 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 70 |
+
|
| 71 |
+
# --- Inicialización del Analizador de Sentimiento ---
|
| 72 |
+
# Cargamos el modelo una vez para no recargarlo en cada request.
|
| 73 |
+
try:
|
| 74 |
+
sentiment_analyzer = create_analyzer(task="sentiment", lang="es")
|
| 75 |
+
logging.info("Analizador de sentimiento cargado exitosamente.")
|
| 76 |
+
except Exception as e:
|
| 77 |
+
sentiment_analyzer = None
|
| 78 |
+
logging.error(f"No se pudo cargar el analizador de sentimiento: {e}")
|
| 79 |
+
|
| 80 |
+
# --- Inicialización de Firebase Admin SDK ---
|
| 81 |
+
db = None
|
| 82 |
try:
|
| 83 |
if not firebase_admin._apps:
|
| 84 |
firebase_credentials_json = os.getenv('GOOGLE_APPLICATION_CREDENTIALS_JSON')
|
| 85 |
if firebase_credentials_json:
|
| 86 |
cred_dict = json.loads(firebase_credentials_json)
|
| 87 |
+
# Aseguramos el project_id si no está en el JSON (común en algunos entornos)
|
| 88 |
if 'project_id' not in cred_dict:
|
| 89 |
+
cred_dict['project_id'] = 'mateai-815ca' # Reemplazar con tu project_id real si es diferente
|
| 90 |
cred = credentials.Certificate(cred_dict)
|
| 91 |
firebase_admin.initialize_app(cred)
|
| 92 |
+
db = firestore.client()
|
| 93 |
+
logging.info("Firebase Admin SDK inicializado correctamente. Conexión a Firestore establecida.")
|
| 94 |
else:
|
| 95 |
+
logging.warning("SECRET 'GOOGLE_APPLICATION_CREDENTIALS_JSON' no configurado. La persistencia de datos NO funcionará.")
|
| 96 |
+
else:
|
| 97 |
+
db = firestore.client()
|
| 98 |
+
logging.info("Firebase Admin SDK ya estaba inicializado.")
|
| 99 |
except Exception as e:
|
| 100 |
+
logging.error(f"Error CRÍTICO al inicializar Firebase: {e}")
|
|
|
|
| 101 |
|
| 102 |
+
# ==============================================================================
|
| 103 |
+
# MÓDULO 3: MODELOS DE DATOS Y CLASES CENTRALES
|
| 104 |
+
# ==============================================================================
|
| 105 |
+
# Definen la estructura de los datos con los que operamos. La clase User
|
| 106 |
+
# es el corazón del sistema, representando el estado completo de un individuo.
|
| 107 |
+
# ==============================================================================
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
class User:
|
| 110 |
+
"""Representa el estado completo de un usuario, incluyendo su personalidad y memoria."""
|
| 111 |
+
def __init__(self, user_id: str, name: str, **kwargs: Any):
|
| 112 |
+
self.user_id: str = user_id
|
| 113 |
+
self.name: str = name
|
| 114 |
+
self.created_at: datetime = kwargs.get('created_at', datetime.now())
|
| 115 |
+
self.last_login: datetime = kwargs.get('last_login', datetime.now())
|
| 116 |
+
|
| 117 |
+
# El perfil psicológico, la joya de la corona.
|
| 118 |
+
self.psych_profile: Dict[str, float] = kwargs.get('psych_profile', Config.DEFAULT_PSYCH_PROFILE.copy())
|
| 119 |
+
|
| 120 |
+
# Memoria a corto y largo plazo.
|
| 121 |
+
self.memory_stream: List[Dict[str, Any]] = kwargs.get('memory_stream', [])
|
| 122 |
+
self.short_term_context: Dict[str, Any] = {} # No se persiste, es para la sesión actual.
|
| 123 |
+
|
| 124 |
+
# Sistema de metas, reemplaza a las simples "tareas".
|
| 125 |
+
self.goals: List[Dict[str, Any]] = kwargs.get('goals', [])
|
| 126 |
|
| 127 |
+
# Gamificación con propósito.
|
| 128 |
+
self.connection_points: int = kwargs.get('connection_points', 0)
|
| 129 |
+
self.achievements: List[str] = kwargs.get('achievements', [])
|
| 130 |
+
|
| 131 |
+
# Metadata para la proactividad.
|
| 132 |
+
self.last_proactive_checkin: Optional[datetime] = kwargs.get('last_proactive_checkin')
|
| 133 |
+
|
| 134 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 135 |
+
"""Serializa el objeto User a un diccionario para guardarlo en Firestore."""
|
| 136 |
return {
|
| 137 |
+
"user_id": self.user_id,
|
| 138 |
+
"name": self.name,
|
| 139 |
+
"created_at": self.created_at.isoformat(),
|
| 140 |
+
"last_login": self.last_login.isoformat(),
|
| 141 |
+
"psych_profile": self.psych_profile,
|
| 142 |
+
"memory_stream": self.memory_stream,
|
| 143 |
+
"goals": self.goals,
|
| 144 |
+
"connection_points": self.connection_points,
|
| 145 |
+
"achievements": self.achievements,
|
| 146 |
+
"last_proactive_checkin": self.last_proactive_checkin.isoformat() if self.last_proactive_checkin else None
|
| 147 |
}
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
@classmethod
|
| 150 |
+
def from_dict(cls, data: Dict[str, Any]) -> 'User':
|
| 151 |
+
"""Crea una instancia de User a partir de un diccionario de Firestore."""
|
| 152 |
+
# Conversión de fechas de ISO string a datetime
|
| 153 |
+
data['created_at'] = datetime.fromisoformat(data.get('created_at', datetime.now().isoformat()))
|
| 154 |
+
data['last_login'] = datetime.fromisoformat(data.get('last_login', datetime.now().isoformat()))
|
| 155 |
+
last_checkin_str = data.get('last_proactive_checkin')
|
| 156 |
+
data['last_proactive_checkin'] = datetime.fromisoformat(last_checkin_str) if last_checkin_str else None
|
| 157 |
+
|
| 158 |
+
# Aseguramos que el perfil psicológico tenga todas las claves
|
| 159 |
+
profile = Config.DEFAULT_PSYCH_PROFILE.copy()
|
| 160 |
+
profile.update(data.get('psych_profile', {}))
|
| 161 |
+
data['psych_profile'] = profile
|
|
|
|
|
|
|
| 162 |
|
| 163 |
+
return cls(**data)
|
| 164 |
+
|
| 165 |
+
def add_memory(self, content: str, memory_type: str, sentiment: Dict[str, float], tags: List[str] = []):
|
| 166 |
+
"""Añade un nuevo recuerdo al flujo de memoria del usuario."""
|
| 167 |
+
if len(self.memory_stream) >= Config.MAX_MEMORY_STREAM_ITEMS:
|
| 168 |
+
self.memory_stream.pop(0) # Mantiene el tamaño del flujo de memoria
|
| 169 |
+
|
| 170 |
+
memory = {
|
| 171 |
+
"timestamp": datetime.now().isoformat(),
|
| 172 |
+
"content": content,
|
| 173 |
+
"type": memory_type, # 'chat', 'insight', 'goal_set', 'goal_completed'
|
| 174 |
+
"sentiment": sentiment,
|
| 175 |
+
"tags": tags
|
| 176 |
+
}
|
| 177 |
+
self.memory_stream.append(memory)
|
| 178 |
+
logging.info(f"Nuevo recuerdo añadido para {self.name}: {content[:50]}...")
|
| 179 |
+
|
| 180 |
+
# ==============================================================================
|
| 181 |
+
# MÓDULO 4: GESTOR DE DATOS DE USUARIO (CAPA DE PERSISTENCIA)
|
| 182 |
+
# ==============================================================================
|
| 183 |
+
# Abstrae toda la lógica de comunicación con Firestore. Permite cambiar
|
| 184 |
+
# de base de datos en el futuro sin alterar el resto del código.
|
| 185 |
+
# ==============================================================================
|
| 186 |
+
|
| 187 |
+
class UserManager:
|
| 188 |
+
"""Maneja la carga, creación y actualización de perfiles de usuario en Firestore."""
|
| 189 |
+
|
| 190 |
+
@staticmethod
|
| 191 |
+
async def get_user(user_id: str) -> Optional[User]:
|
| 192 |
+
"""Carga un usuario desde Firestore por su ID."""
|
| 193 |
+
if not db or not user_id: return None
|
| 194 |
try:
|
| 195 |
+
user_doc_ref = db.collection(Config.FIREBASE_COLLECTION_USERS).document(user_id)
|
| 196 |
doc = await asyncio.to_thread(user_doc_ref.get)
|
| 197 |
if doc.exists:
|
| 198 |
user_data = doc.to_dict()
|
| 199 |
+
user_data['user_id'] = doc.id # Aseguramos que el ID esté en los datos.
|
| 200 |
+
|
| 201 |
+
# Actualizar la fecha de último login y guardar inmediatamente.
|
| 202 |
+
user_obj = User.from_dict(user_data)
|
| 203 |
+
user_obj.last_login = datetime.now()
|
| 204 |
+
await UserManager.save_user(user_obj) # Guardado asíncrono
|
| 205 |
+
|
| 206 |
+
logging.info(f"Usuario '{user_obj.name}' ({user_id}) cargado y actualizado.")
|
| 207 |
+
return user_obj
|
| 208 |
+
else:
|
| 209 |
+
logging.warning(f"Intento de carga de usuario inexistente: {user_id}")
|
| 210 |
+
return None
|
| 211 |
except Exception as e:
|
| 212 |
+
logging.error(f"Error al cargar usuario {user_id} desde Firestore: {e}")
|
| 213 |
+
return None
|
|
|
|
| 214 |
|
|
|
|
| 215 |
@staticmethod
|
| 216 |
+
async def create_user(name: str) -> Tuple[Optional[User], str]:
|
| 217 |
+
"""Crea un nuevo usuario en Firestore."""
|
| 218 |
+
if not db: return None, "Error: La base de datos no está disponible."
|
| 219 |
+
if not name.strip(): return None, "El nombre no puede estar vacío."
|
| 220 |
+
|
| 221 |
+
try:
|
| 222 |
+
# Generamos un ID de usuario único y legible.
|
| 223 |
+
user_id = f"{name.lower().replace(' ', '_')}_{int(time.time())}"
|
| 224 |
+
new_user = User(user_id=user_id, name=name)
|
| 225 |
+
|
| 226 |
+
await UserManager.save_user(new_user)
|
| 227 |
+
msg = f"¡Bienvenido, {name}! Tu perfil ha sido creado. Guarda bien tu ID de Usuario: **{user_id}**"
|
| 228 |
+
logging.info(f"Nuevo usuario creado: {name} ({user_id})")
|
| 229 |
+
return new_user, msg
|
| 230 |
+
except Exception as e:
|
| 231 |
+
logging.error(f"Error al crear usuario en Firestore: {e}")
|
| 232 |
+
return None, f"Error inesperado al crear el perfil: {e}"
|
| 233 |
+
|
| 234 |
@staticmethod
|
| 235 |
+
async def save_user(user: User) -> bool:
|
| 236 |
+
"""Guarda el estado completo de un objeto User en Firestore."""
|
| 237 |
+
if not db: return False
|
| 238 |
+
try:
|
| 239 |
+
user_doc_ref = db.collection(Config.FIREBASE_COLLECTION_USERS).document(user.user_id)
|
| 240 |
+
await asyncio.to_thread(user_doc_ref.set, user.to_dict())
|
| 241 |
+
return True
|
| 242 |
+
except Exception as e:
|
| 243 |
+
logging.error(f"Error al guardar usuario {user.user_id} en Firestore: {e}")
|
| 244 |
+
return False
|
| 245 |
+
|
| 246 |
+
# ==============================================================================
|
| 247 |
+
# MÓDULO 5: MOTOR DE PERSONA Y LÓGICA DE IA
|
| 248 |
+
# ==============================================================================
|
| 249 |
+
# Este es el cerebro de MateAI. Aquí se toma el perfil del usuario,
|
| 250 |
+
# el contexto actual y el mensaje para generar una respuesta coherente,
|
| 251 |
+
# empática y personalizada.
|
| 252 |
+
# ==============================================================================
|
| 253 |
+
|
| 254 |
+
class PersonaEngine:
|
| 255 |
+
"""Orquesta la lógica de IA para generar respuestas y gestionar la interacción."""
|
| 256 |
+
|
| 257 |
+
def __init__(self, user: User):
|
| 258 |
+
self.user = user
|
| 259 |
+
|
| 260 |
+
async def analyze_sentiment(self, text: str) -> Dict[str, float]:
|
| 261 |
+
"""Analiza el sentimiento del texto del usuario."""
|
| 262 |
+
if not sentiment_analyzer:
|
| 263 |
+
# Fallback si el modelo no cargó.
|
| 264 |
+
return {"label": "NEU", "score": 1.0}
|
| 265 |
+
|
| 266 |
+
try:
|
| 267 |
+
# Ejecutamos el análisis en un hilo separado para no bloquear la app.
|
| 268 |
+
analysis = await asyncio.to_thread(sentiment_analyzer.predict, text)
|
| 269 |
+
return {"label": analysis.output, "score": analysis.probas[analysis.output]}
|
| 270 |
+
except Exception as e:
|
| 271 |
+
logging.error(f"Error en análisis de sentimiento: {e}")
|
| 272 |
+
return {"label": "NEU", "score": 1.0}
|
| 273 |
+
|
| 274 |
+
def _get_greeting(self) -> str:
|
| 275 |
+
"""Genera un saludo personalizado basado en la hora y el perfil."""
|
| 276 |
+
hour = datetime.now().hour
|
| 277 |
+
if 5 <= hour < 12: time_greeting = "Buen día"
|
| 278 |
+
elif 12 <= hour < 19: time_greeting = "Buenas tardes"
|
| 279 |
+
else: time_greeting = "Buenas noches"
|
| 280 |
|
| 281 |
+
# Personalización del saludo
|
| 282 |
+
if self.user.psych_profile['extraversion'] > 0.5:
|
| 283 |
+
return f"¡{time_greeting}, {self.user.name}! ¡Qué bueno verte! ¿En qué andamos hoy?"
|
| 284 |
+
elif self.user.psych_profile['neuroticism'] > 0.4:
|
| 285 |
+
return f"{time_greeting}, {self.user.name}. Espero que estés teniendo un día tranquilo. ¿Cómo te sentís?"
|
| 286 |
+
else:
|
| 287 |
+
return f"{time_greeting}, {self.user.name}. Un gusto conectar de nuevo."
|
| 288 |
+
|
| 289 |
+
async def generate_proactive_checkin(self) -> Optional[str]:
|
| 290 |
+
"""Genera un mensaje proactivo si ha pasado suficiente tiempo."""
|
| 291 |
+
now = datetime.now()
|
| 292 |
+
if self.user.last_proactive_checkin:
|
| 293 |
+
if now - self.user.last_proactive_checkin < timedelta(hours=Config.PROACTIVE_CHECKIN_HOURS):
|
| 294 |
+
return None # Aún no es tiempo.
|
| 295 |
+
|
| 296 |
+
# Lógica de check-in
|
| 297 |
+
self.user.last_proactive_checkin = now
|
| 298 |
+
await UserManager.save_user(self.user)
|
| 299 |
+
|
| 300 |
+
# Ejemplo de check-in personalizado
|
| 301 |
+
if self.user.psych_profile['conscientiousness'] > 0.5 and self.user.goals:
|
| 302 |
+
pending_goals = [g['name'] for g in self.user.goals if not g.get('completed')]
|
| 303 |
+
if pending_goals:
|
| 304 |
+
return f"¡Hola {self.user.name}! Solo pasaba a saludar y recordarte que tenés metas increíbles como '{pending_goals[0]}' en marcha. ¡Cualquier pasito cuenta!"
|
| 305 |
+
|
| 306 |
+
return self._get_greeting() + " Solo pasaba a ver cómo estabas."
|
| 307 |
+
|
| 308 |
+
async def generate_response(self, message: str) -> str:
|
| 309 |
+
"""El método principal que genera la respuesta de MateAI a un mensaje."""
|
| 310 |
+
# 1. Analizar el sentimiento del mensaje del usuario
|
| 311 |
+
sentiment = await self.analyze_sentiment(message)
|
| 312 |
+
|
| 313 |
+
# 2. Registrar el mensaje en la memoria del usuario
|
| 314 |
+
self.user.add_memory(content=message, memory_type="chat", sentiment=sentiment)
|
| 315 |
+
|
| 316 |
+
# 3. Lógica de respuesta basada en triggers y perfil
|
| 317 |
+
# TODO: Implementar un sistema de comandos más robusto (ej. /metas, /perfil)
|
| 318 |
+
|
| 319 |
+
# 3.1 Manejo de respuestas empáticas a sentimientos fuertes
|
| 320 |
+
if sentiment['label'] == 'NEG' and sentiment['score'] > 0.7:
|
| 321 |
+
return f"Noto que lo que decís tiene una carga fuerte, {self.user.name}. Si querés hablar de ello, acá estoy para escucharte sin juzgar."
|
| 322 |
+
|
| 323 |
+
# 3.2 Lógica de preguntas para construir el perfil (si aún es genérico)
|
| 324 |
+
# Esta es la parte de "tricky psychological questions"
|
| 325 |
+
if abs(sum(self.user.psych_profile.values())) < 0.1: # Perfil casi virgen
|
| 326 |
+
return await self._ask_profiling_question()
|
| 327 |
+
|
| 328 |
+
# 3.3 Respuesta por defecto (placeholder para lógica más compleja)
|
| 329 |
+
# Aquí se integraría con un LLM si lo tuviéramos.
|
| 330 |
+
# Por ahora, una respuesta reflexiva basada en el perfil.
|
| 331 |
+
|
| 332 |
+
response = self._craft_default_response(sentiment)
|
| 333 |
+
|
| 334 |
+
# 4. Guardar el estado actualizado del usuario
|
| 335 |
+
await UserManager.save_user(self.user)
|
| 336 |
+
|
| 337 |
+
return response
|
| 338 |
+
|
| 339 |
+
def _craft_default_response(self, sentiment: Dict[str, float]) -> str:
|
| 340 |
+
"""Crea una respuesta genérica pero personalizada."""
|
| 341 |
+
responses = [
|
| 342 |
+
f"Interesante lo que mencionás, {self.user.name}. Me hace pensar en...",
|
| 343 |
+
f"Entiendo tu punto, {self.user.name}. ¿Cómo se conecta eso con tus metas actuales?",
|
| 344 |
+
f"Gracias por compartir eso. Cada charla nos ayuda a entendernos mejor.",
|
| 345 |
+
]
|
| 346 |
+
|
| 347 |
+
if self.user.psych_profile['openness'] > 0.5:
|
| 348 |
+
responses.append(f"Eso abre una puerta a una idea nueva. ¿Qué pasaría si lo miramos desde otro ángulo?")
|
| 349 |
+
if sentiment['label'] == 'POS':
|
| 350 |
+
responses.append(f"¡Me encanta esa energía, {self.user.name}! Es genial verte así.")
|
| 351 |
+
|
| 352 |
+
return random.choice(responses)
|
| 353 |
|
| 354 |
+
async def _ask_profiling_question(self) -> str:
|
| 355 |
+
"""Selecciona y hace una pregunta sutil para definir el perfil psicológico."""
|
| 356 |
+
# Ejemplo de pregunta para medir "Apertura a la experiencia" vs "Consciencia"
|
| 357 |
+
question = (
|
| 358 |
+
f"Una pregunta curiosa, {self.user.name}: si tuvieras una tarde libre inesperada, "
|
| 359 |
+
"¿qué te tienta más? \n"
|
| 360 |
+
"A) Improvisar y ver a dónde te lleva el día, quizás descubrir un café nuevo o un parque. \n"
|
| 361 |
+
"B) Aprovechar para organizar esa pila de libros, planificar la semana o adelantar una tarea pendiente."
|
| 362 |
+
)
|
| 363 |
+
self.user.short_term_context['last_question'] = "openness_vs_conscientiousness"
|
| 364 |
+
await UserManager.save_user(self.user)
|
| 365 |
+
return question
|
| 366 |
|
| 367 |
+
def process_profiling_answer(self, answer: str):
|
| 368 |
+
"""Procesa la respuesta a una pregunta de perfilado y actualiza el psych_profile."""
|
| 369 |
+
question_type = self.user.short_term_context.get('last_question')
|
| 370 |
+
if not question_type: return
|
| 371 |
+
|
| 372 |
+
answer_lower = answer.lower()
|
| 373 |
+
if question_type == "openness_vs_conscientiousness":
|
| 374 |
+
if 'a' in answer_lower or 'improvisar' in answer_lower:
|
| 375 |
+
self.user.psych_profile['openness'] += 0.3
|
| 376 |
+
self.user.psych_profile['conscientiousness'] -= 0.1
|
| 377 |
+
elif 'b' in answer_lower or 'organizar' in answer_lower:
|
| 378 |
+
self.user.psych_profile['conscientiousness'] += 0.3
|
| 379 |
+
self.user.psych_profile['openness'] -= 0.1
|
| 380 |
+
|
| 381 |
+
# Limpiamos el contexto para no procesar de nuevo.
|
| 382 |
+
del self.user.short_term_context['last_question']
|
| 383 |
+
|
| 384 |
+
# Añadimos puntos por la introspección
|
| 385 |
+
self.user.connection_points += Config.POINTS_PER_INSIGHT
|
| 386 |
+
logging.info(f"Perfil de {self.user.name} actualizado. Puntos: {self.user.connection_points}")
|
| 387 |
|
| 388 |
+
|
| 389 |
+
# ==============================================================================
|
| 390 |
+
# MÓDULO 6: LÓGICA Y ESTRUCTURA DE LA INTERFAZ DE USUARIO (GRADIO)
|
| 391 |
+
# ==============================================================================
|
| 392 |
+
# Aquí se conectan todos los módulos anteriores con la interfaz gráfica.
|
| 393 |
+
# Las funciones aquí son "controladores" que reciben eventos de la UI
|
| 394 |
+
# y orquestan las acciones de los motores de backend.
|
| 395 |
+
# ==============================================================================
|
| 396 |
+
|
| 397 |
+
# --- Funciones de Lógica de la Interfaz ---
|
| 398 |
+
|
| 399 |
+
async def handle_login_or_creation(action: str, name: str, user_id: str) -> tuple:
|
| 400 |
+
"""Controlador para los botones de login y creación."""
|
| 401 |
+
if action == "create":
|
| 402 |
+
if not name:
|
| 403 |
+
gr.Warning("Para crear un perfil, necesito que me digas tu nombre.")
|
| 404 |
+
return None, gr.update(), gr.update(visible=True), gr.update(visible=False)
|
| 405 |
+
user, msg = await UserManager.create_user(name)
|
| 406 |
+
elif action == "login":
|
| 407 |
+
if not user_id:
|
| 408 |
gr.Warning("¡Che, poné tu ID para cargar el perfil!")
|
| 409 |
+
return None, gr.update(), gr.update(visible=True), gr.update(visible=False)
|
| 410 |
+
user = await UserManager.get_user(user_id)
|
| 411 |
+
msg = f"¡Hola de nuevo, {user.name}! Perfil cargado." if user else "ID de usuario no encontrado. Verificá que esté bien escrito."
|
| 412 |
+
else:
|
| 413 |
+
return None, "Acción desconocida.", gr.update(visible=True), gr.update(visible=False)
|
|
|
|
|
|
|
| 414 |
|
| 415 |
if user:
|
| 416 |
gr.Success(msg)
|
| 417 |
+
# Al loguearse, ocultamos el panel de login y mostramos el de chat.
|
| 418 |
+
initial_greeting = PersonaEngine(user)._get_greeting()
|
| 419 |
+
chat_history = [{"role": "assistant", "content": initial_greeting}]
|
| 420 |
+
return user, chat_history, gr.update(visible=False), gr.update(visible=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 421 |
else:
|
| 422 |
+
gr.Error(msg)
|
| 423 |
+
return None, gr.update(), gr.update(visible=True), gr.update(visible=False)
|
| 424 |
|
| 425 |
+
async def handle_chat_message(user_state: User, message: str, chat_history: List[Dict]) -> tuple:
|
| 426 |
+
"""Controlador principal para cada mensaje enviado por el usuario."""
|
| 427 |
+
if not user_state:
|
| 428 |
+
gr.Warning("¡Para empezar, creá un perfil o iniciá sesión!")
|
| 429 |
+
return user_state, chat_history, ""
|
| 430 |
+
|
| 431 |
+
# Agregamos el mensaje del usuario a la UI inmediatamente para dar feedback visual.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
chat_history.append({"role": "user", "content": message})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
+
# Creamos una instancia del motor de persona con el estado actual del usuario.
|
| 435 |
+
engine = PersonaEngine(user_state)
|
|
|
|
| 436 |
|
| 437 |
+
# Verificamos si la respuesta es a una pregunta de perfilado.
|
| 438 |
+
if user_state.short_term_context.get('last_question'):
|
| 439 |
+
engine.process_profiling_answer(message)
|
| 440 |
+
response = "¡Bárbaro! Gracias por compartirlo. Lo tengo en cuenta para que nos entendamos mejor."
|
| 441 |
+
else:
|
| 442 |
+
# Si no, generamos una respuesta normal.
|
| 443 |
+
response = await engine.generate_response(message)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
+
# Agregamos la respuesta de MateAI al historial.
|
| 446 |
+
chat_history.append({"role": "assistant", "content": response})
|
|
|
|
| 447 |
|
| 448 |
+
# El estado del usuario (user_state) ha sido modificado por el engine,
|
| 449 |
+
# así que lo devolvemos para actualizar el gr.State
|
| 450 |
+
return user_state, chat_history, "" # Limpiamos el textbox de input
|
| 451 |
+
|
| 452 |
+
def render_profile_info(user: Optional[User]) -> str:
|
| 453 |
+
"""Genera un texto Markdown con la información del perfil del usuario."""
|
| 454 |
+
if not user:
|
| 455 |
+
return "Cargá un perfil para ver tu información."
|
| 456 |
+
|
| 457 |
+
profile_md = f"### Perfil de {user.name}\n"
|
| 458 |
+
profile_md += f"**ID de Usuario:** `{user.user_id}`\n"
|
| 459 |
+
profile_md += f"**Puntos de Conexión:** {user.connection_points} 💠\n\n"
|
| 460 |
+
profile_md += "#### Modelo de Personalidad (inferido):\n"
|
| 461 |
+
for trait, value in user.psych_profile.items():
|
| 462 |
+
# Visualización simple del rasgo
|
| 463 |
+
bar = "■" * int((value + 1) * 5) # Escala de 0 a 10
|
| 464 |
+
profile_md += f"- **{trait.capitalize()}:** `{f'{value:.2f}'}` {bar}\n"
|
| 465 |
|
| 466 |
+
return profile_md
|
| 467 |
+
|
| 468 |
+
# --- Construcción de la Interfaz con Gradio Blocks ---
|
| 469 |
+
|
| 470 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal", secondary_hue="amber"), css="footer {display: none !important}") as demo:
|
| 471 |
|
| 472 |
+
# Estado de la aplicación: el objeto User se mantiene aquí durante toda la sesión.
|
| 473 |
+
current_user = gr.State(None)
|
| 474 |
|
| 475 |
+
gr.Markdown(f"# 🧉 {Config.APP_NAME}")
|
| 476 |
+
gr.Markdown(f"*{Config.APP_VERSION}* - Tu compañero de IA para la introspección y el crecimiento.")
|
| 477 |
+
|
| 478 |
+
with gr.Row():
|
| 479 |
+
# Columna de la izquierda: Chat y Perfil
|
| 480 |
+
with gr.Column(scale=2):
|
| 481 |
+
# Panel de Chat (inicialmente oculto)
|
| 482 |
+
with gr.Box(visible=False) as chat_panel:
|
| 483 |
+
chatbot = gr.Chatbot(label="Conversación con MateAI", height=600, type="messages")
|
| 484 |
+
with gr.Row():
|
| 485 |
+
chat_input = gr.Textbox(show_label=False, placeholder="Escribí acá con confianza...", scale=4)
|
| 486 |
+
send_button = gr.Button("Enviar", variant="primary", scale=1)
|
| 487 |
+
|
| 488 |
+
# Panel de Login (inicialmente visible)
|
| 489 |
+
with gr.Box(visible=True) as login_panel:
|
| 490 |
+
gr.Markdown("### 🌟 Para empezar...")
|
| 491 |
+
with gr.Tabs():
|
| 492 |
+
with gr.TabItem("Crear Perfil Nuevo"):
|
| 493 |
+
username_input = gr.Textbox(label="Tu Nombre o Apodo")
|
| 494 |
+
create_button = gr.Button("¡Crear mi MateAI!", variant="primary")
|
| 495 |
+
with gr.TabItem("Cargar Perfil Existente"):
|
| 496 |
+
userid_input = gr.Textbox(label="Tu ID de Usuario")
|
| 497 |
+
login_button = gr.Button("Cargar Perfil")
|
| 498 |
+
|
| 499 |
+
# Columna de la derecha: Información de contexto
|
| 500 |
+
with gr.Column(scale=1):
|
| 501 |
+
with gr.Box():
|
| 502 |
+
gr.Markdown("### 🧠 Tu Perfil")
|
| 503 |
+
profile_display = gr.Markdown("Cargá un perfil para ver tu información.")
|
| 504 |
+
|
| 505 |
+
# --- Lógica de Eventos de la Interfaz ---
|
| 506 |
+
|
| 507 |
+
# Acciones de Login y Creación
|
| 508 |
+
login_button.click(
|
| 509 |
+
fn=handle_login_or_creation,
|
| 510 |
+
inputs=[gr.State("login"), username_input, userid_input],
|
| 511 |
+
outputs=[current_user, chatbot, login_panel, chat_panel]
|
| 512 |
+
)
|
| 513 |
+
create_button.click(
|
| 514 |
+
fn=handle_login_or_creation,
|
| 515 |
+
inputs=[gr.State("create"), username_input, userid_input],
|
| 516 |
+
outputs=[current_user, chatbot, login_panel, chat_panel]
|
| 517 |
+
)
|
| 518 |
|
| 519 |
+
# Acción de enviar mensaje en el chat
|
| 520 |
+
chat_submit_action = send_button.click if send_button else chat_input.submit
|
| 521 |
+
chat_submit_action(
|
| 522 |
+
fn=handle_chat_message,
|
| 523 |
+
inputs=[current_user, chat_input, chatbot],
|
| 524 |
+
outputs=[current_user, chatbot, chat_input]
|
| 525 |
+
)
|
| 526 |
+
chat_input.submit(
|
| 527 |
+
fn=handle_chat_message,
|
| 528 |
+
inputs=[current_user, chat_input, chatbot],
|
| 529 |
+
outputs=[current_user, chatbot, chat_input]
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
# Actualización dinámica del panel de perfil cuando cambia el estado del usuario
|
| 533 |
+
current_user.change(
|
| 534 |
+
fn=render_profile_info,
|
| 535 |
+
inputs=[current_user],
|
| 536 |
+
outputs=[profile_display]
|
| 537 |
+
)
|
| 538 |
|
| 539 |
if __name__ == "__main__":
|
| 540 |
+
# Para lanzar la aplicación
|
| 541 |
+
# En un entorno de producción como Hugging Face Spaces, no es necesario debug=True
|
| 542 |
demo.launch(debug=True)
|