Update app.py
Browse files
app.py
CHANGED
|
@@ -1,90 +1,114 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import random
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
from datetime import datetime
|
| 6 |
from chatbot_nuti import buscar_respuesta
|
| 7 |
from coach_emocional import coach_emocional_inteligente
|
| 8 |
from retos_saludables import mostrar_retos, completar_reto
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
PERFIL_FILE = "perfil_usuario.json"
|
| 11 |
-
COMIDAS_FILE = "historial_comidas.json"
|
| 12 |
-
RECETAS_FILE = "recetas_nutribot.json"
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# ---------- ESTADO SIMPLE EN MEMORIA ---------- #
|
| 16 |
estado_app = {
|
| 17 |
-
"
|
| 18 |
-
"memoria_coach": [],
|
| 19 |
-
"calorias_totales": 0,
|
| 20 |
-
"calorias_restantes": 0
|
| 21 |
}
|
| 22 |
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
return json.load(f)
|
| 30 |
-
except json.JSONDecodeError:
|
| 31 |
-
return default
|
| 32 |
-
return default
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
def guardar_json(path, data):
|
| 36 |
-
with open(path, "w", encoding="utf-8") as f:
|
| 37 |
-
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
|
| 46 |
# ---------- CHATBOT NUTI ---------- #
|
| 47 |
def conversar_nuti(mensaje, historial):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if not mensaje or not mensaje.strip():
|
| 49 |
return historial, ""
|
| 50 |
|
| 51 |
if historial is None:
|
| 52 |
historial = []
|
| 53 |
|
| 54 |
-
|
|
|
|
| 55 |
historial.append({"role": "user", "content": mensaje})
|
| 56 |
|
| 57 |
-
respuesta = buscar_respuesta(mensaje,
|
| 58 |
-
estado_app["memoria_nuti"].append({"nuti": respuesta})
|
| 59 |
|
|
|
|
| 60 |
historial.append({"role": "assistant", "content": respuesta})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return historial, ""
|
| 62 |
|
| 63 |
|
| 64 |
# ---------- COACH EMOCIONAL ---------- #
|
| 65 |
def conversar_coach(mensaje, historial):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
if not mensaje or not mensaje.strip():
|
| 67 |
return historial, ""
|
| 68 |
|
| 69 |
if historial is None:
|
| 70 |
historial = []
|
| 71 |
|
| 72 |
-
|
|
|
|
| 73 |
historial.append({"role": "user", "content": mensaje})
|
| 74 |
|
| 75 |
-
respuesta = coach_emocional_inteligente(mensaje,
|
| 76 |
-
estado_app["memoria_coach"].append({"coach": respuesta})
|
| 77 |
|
|
|
|
| 78 |
historial.append({"role": "assistant", "content": respuesta})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
return historial, ""
|
| 80 |
|
| 81 |
|
| 82 |
# ---------- CÁLCULO DE CALORÍAS ---------- #
|
| 83 |
def calcular_calorias(edad, peso, altura, genero, actividad, meta):
|
| 84 |
if not all([edad, peso, altura, genero, actividad, meta]):
|
| 85 |
-
return "⚠️ Completa todos los datos para calcular tus calorías."
|
| 86 |
|
| 87 |
-
if genero.lower() == "mujer":
|
| 88 |
bmr = 655 + (9.6 * peso) + (1.8 * altura) - (4.7 * edad)
|
| 89 |
else:
|
| 90 |
bmr = 66 + (13.7 * peso) + (5 * altura) - (6.8 * edad)
|
|
@@ -97,26 +121,28 @@ def calcular_calorias(edad, peso, altura, genero, actividad, meta):
|
|
| 97 |
"muy activo": 1.9
|
| 98 |
}
|
| 99 |
|
| 100 |
-
calorias_base = bmr * factores.get(actividad.lower(), 1.55)
|
| 101 |
|
| 102 |
-
if meta.lower() == "bajar de peso":
|
| 103 |
calorias_totales = round(calorias_base * 0.8)
|
| 104 |
-
elif meta.lower() == "subir de peso":
|
| 105 |
calorias_totales = round(calorias_base * 1.15)
|
| 106 |
else:
|
| 107 |
calorias_totales = round(calorias_base)
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
return (
|
| 113 |
-
f"🎯 Tu meta es **{meta.lower()}**.\n"
|
| 114 |
f"🔥 Puedes consumir aproximadamente **{calorias_totales} calorías por día**."
|
| 115 |
)
|
|
|
|
| 116 |
|
| 117 |
|
| 118 |
# ---------- GUARDAR DATOS ---------- #
|
| 119 |
def guardar_informacion(nombre, edad, peso, altura, genero, actividad, meta, condicion, alergias):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
perfil = {
|
| 121 |
"nombre": nombre,
|
| 122 |
"edad": edad,
|
|
@@ -129,30 +155,39 @@ def guardar_informacion(nombre, edad, peso, altura, genero, actividad, meta, con
|
|
| 129 |
"alergias": alergias
|
| 130 |
}
|
| 131 |
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
|
| 135 |
f"✅ Información guardada.\n"
|
| 136 |
f"**Nombre:** {nombre or 'Sin nombre'}\n"
|
| 137 |
f"**Condición:** {condicion or 'ninguna'}\n"
|
| 138 |
-
f"**Alergias:** {alergias or 'ninguna'}"
|
|
|
|
| 139 |
)
|
| 140 |
|
| 141 |
-
mensaje_calorias = calcular_calorias(edad, peso, altura, genero, actividad, meta)
|
| 142 |
-
|
| 143 |
-
return f"{mensaje_guardado}\n\n{mensaje_calorias}"
|
| 144 |
-
|
| 145 |
|
| 146 |
# ---------- CALORÍAS DEL RELOJ ---------- #
|
| 147 |
def calorias_reloj(calorias_quemadas):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
if calorias_quemadas is None:
|
| 149 |
return "⚠️ Ingresa las calorías quemadas."
|
| 150 |
|
| 151 |
-
|
|
|
|
| 152 |
|
| 153 |
return (
|
| 154 |
f"⌚ Has quemado **{calorias_quemadas} kcal**.\n"
|
| 155 |
-
f"🔥 Te quedan **{
|
| 156 |
)
|
| 157 |
|
| 158 |
|
|
@@ -177,68 +212,78 @@ def analizar_foto(imagen):
|
|
| 177 |
|
| 178 |
|
| 179 |
def registrar_comida(imagen):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
info, calorias = analizar_foto(imagen)
|
| 181 |
|
| 182 |
if calorias == 0:
|
| 183 |
return info
|
| 184 |
|
| 185 |
-
|
| 186 |
-
estado_app["calorias_restantes"] = max(estado_app["calorias_restantes"], 0)
|
| 187 |
-
|
| 188 |
-
nombre_usuario = obtener_nombre_usuario()
|
| 189 |
-
datos = cargar_json(COMIDAS_FILE, {})
|
| 190 |
-
|
| 191 |
-
if nombre_usuario not in datos:
|
| 192 |
-
datos[nombre_usuario] = []
|
| 193 |
|
| 194 |
-
datos
|
|
|
|
| 195 |
"fecha": str(datetime.now()),
|
| 196 |
"comida": info,
|
| 197 |
"calorias": calorias
|
| 198 |
})
|
|
|
|
| 199 |
|
| 200 |
-
|
| 201 |
|
| 202 |
return (
|
| 203 |
f"{info}\n\n"
|
| 204 |
-
f"🔥 Calorías restantes del día: **{
|
| 205 |
)
|
| 206 |
|
| 207 |
|
| 208 |
def mostrar_historial():
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
| 212 |
|
| 213 |
if not historial:
|
| 214 |
-
return "📭 Aún no has registrado comidas
|
| 215 |
|
| 216 |
texto = "🍴 **Historial de comidas:**\n\n"
|
| 217 |
for i, item in enumerate(historial[-10:], 1):
|
| 218 |
texto += f"{i}. {item['comida']}\n"
|
| 219 |
|
| 220 |
-
texto += f"\n🔥 Te quedan **{
|
| 221 |
return texto
|
| 222 |
|
| 223 |
|
| 224 |
# ---------- RECETAS ---------- #
|
| 225 |
def subir_receta(nombre, descripcion, imagen):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
if not nombre or not descripcion:
|
| 227 |
return "⚠️ Ingresa nombre y descripción."
|
| 228 |
|
| 229 |
-
|
| 230 |
-
|
| 231 |
"nombre": nombre,
|
| 232 |
"descripcion": descripcion,
|
| 233 |
"imagen": str(imagen) if imagen is not None else None
|
| 234 |
})
|
| 235 |
-
|
| 236 |
|
|
|
|
| 237 |
return f"✅ Receta '{nombre}' añadida correctamente."
|
| 238 |
|
| 239 |
|
| 240 |
def mostrar_recetas():
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
if not recetas:
|
| 244 |
return "📭 No hay recetas cargadas aún."
|
|
@@ -304,39 +349,46 @@ def buscar_nutriologos(pais, estado, ciudad):
|
|
| 304 |
f"📱 {n['redes']}\n"
|
| 305 |
f"💬 {n['reseña']}\n\n"
|
| 306 |
)
|
| 307 |
-
|
| 308 |
return texto
|
| 309 |
|
| 310 |
|
| 311 |
-
# ---------- RESUMEN
|
| 312 |
def ver_resumen():
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
if not perfil:
|
| 315 |
return "📭 Aún no has guardado tus datos personales."
|
| 316 |
|
| 317 |
-
nombre = perfil.get("nombre", "Usuario")
|
| 318 |
-
meta = perfil.get("meta", "No definida")
|
| 319 |
-
actividad = perfil.get("actividad", "No definida")
|
| 320 |
-
condicion = perfil.get("condicion", "ninguna")
|
| 321 |
-
alergias = perfil.get("alergias", "ninguna")
|
| 322 |
-
|
| 323 |
return (
|
| 324 |
f"👤 **Resumen del usuario**\n\n"
|
| 325 |
-
f"**Nombre:** {nombre}\n"
|
| 326 |
-
f"**Meta:** {meta}\n"
|
| 327 |
-
f"**Actividad:** {actividad}\n"
|
| 328 |
-
f"**Condición:** {condicion or 'ninguna'}\n"
|
| 329 |
-
f"**Alergias:** {alergias or 'ninguna'}\n"
|
| 330 |
-
f"**Calorías objetivo:** {
|
| 331 |
-
f"**Calorías restantes:** {
|
| 332 |
)
|
| 333 |
|
| 334 |
|
| 335 |
-
# ---------- INTERFAZ
|
| 336 |
with gr.Blocks(title="NutriBot IA 🥗") as app:
|
| 337 |
gr.Markdown("# 🧠 Bienvenido a **NutriBot IA** 🍎")
|
| 338 |
gr.Markdown("Comer sano, inteligente y divertido. 🌿")
|
| 339 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
with gr.Tab("👤 Datos Personales"):
|
| 341 |
with gr.Row():
|
| 342 |
nombre = gr.Textbox(label="Nombre completo")
|
|
@@ -366,7 +418,6 @@ with gr.Blocks(title="NutriBot IA 🥗") as app:
|
|
| 366 |
|
| 367 |
guardar_datos = gr.Button("Guardar información 🧾")
|
| 368 |
salida_datos = gr.Markdown()
|
| 369 |
-
|
| 370 |
guardar_datos.click(
|
| 371 |
guardar_informacion,
|
| 372 |
inputs=[nombre, edad, peso, altura, genero, actividad, meta, condicion, alergias],
|
|
@@ -399,21 +450,13 @@ with gr.Blocks(title="NutriBot IA 🥗") as app:
|
|
| 399 |
chat_nuti = gr.Chatbot(label="Nuti - Tu guía de nutrición 🍎", type="messages")
|
| 400 |
entrada_nuti = gr.Textbox(label="Escribe algo para Nuti...")
|
| 401 |
boton_nuti = gr.Button("Enviar")
|
| 402 |
-
boton_nuti.click(
|
| 403 |
-
conversar_nuti,
|
| 404 |
-
inputs=[entrada_nuti, chat_nuti],
|
| 405 |
-
outputs=[chat_nuti, entrada_nuti]
|
| 406 |
-
)
|
| 407 |
|
| 408 |
with gr.Tab("🧘 Coach Emocional"):
|
| 409 |
chat_coach = gr.Chatbot(label="Coach Emocional 🌿", type="messages")
|
| 410 |
entrada_coach = gr.Textbox(label="Cuéntame cómo te sientes hoy...")
|
| 411 |
boton_coach = gr.Button("Enviar")
|
| 412 |
-
boton_coach.click(
|
| 413 |
-
conversar_coach,
|
| 414 |
-
inputs=[entrada_coach, chat_coach],
|
| 415 |
-
outputs=[chat_coach, entrada_coach]
|
| 416 |
-
)
|
| 417 |
|
| 418 |
with gr.Tab("🍽️ Recetas del Nutriólogo"):
|
| 419 |
nombre_rec = gr.Textbox(label="Nombre de la receta")
|
|
@@ -421,11 +464,7 @@ with gr.Blocks(title="NutriBot IA 🥗") as app:
|
|
| 421 |
imagen_receta = gr.Image(label="Imagen (opcional)", type="filepath")
|
| 422 |
boton_subir = gr.Button("Subir receta")
|
| 423 |
salida_subir = gr.Textbox(label="Estado")
|
| 424 |
-
boton_subir.click(
|
| 425 |
-
subir_receta,
|
| 426 |
-
inputs=[nombre_rec, descripcion, imagen_receta],
|
| 427 |
-
outputs=salida_subir
|
| 428 |
-
)
|
| 429 |
|
| 430 |
boton_ver = gr.Button("Ver recetas disponibles 🍲")
|
| 431 |
salida_recetas = gr.Markdown()
|
|
@@ -433,7 +472,6 @@ with gr.Blocks(title="NutriBot IA 🥗") as app:
|
|
| 433 |
|
| 434 |
with gr.Tab("🎯 Retos Saludables"):
|
| 435 |
salida_retos = gr.Markdown()
|
| 436 |
-
|
| 437 |
boton_ver_retos = gr.Button("Ver Retos del Día")
|
| 438 |
boton_ver_retos.click(mostrar_retos, outputs=salida_retos)
|
| 439 |
|
|
@@ -447,12 +485,9 @@ with gr.Blocks(title="NutriBot IA 🥗") as app:
|
|
| 447 |
ciudad = gr.Textbox(label="Ciudad")
|
| 448 |
boton_buscar = gr.Button("Buscar Nutriólogos 🌍")
|
| 449 |
salida_nutri = gr.Markdown()
|
| 450 |
-
boton_buscar.click(
|
| 451 |
-
buscar_nutriologos,
|
| 452 |
-
inputs=[pais, estado, ciudad],
|
| 453 |
-
outputs=salida_nutri
|
| 454 |
-
)
|
| 455 |
|
| 456 |
|
| 457 |
if __name__ == "__main__":
|
|
|
|
| 458 |
app.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import random
|
|
|
|
|
|
|
| 3 |
from datetime import datetime
|
| 4 |
from chatbot_nuti import buscar_respuesta
|
| 5 |
from coach_emocional import coach_emocional_inteligente
|
| 6 |
from retos_saludables import mostrar_retos, completar_reto
|
| 7 |
+
from usuarios import (
|
| 8 |
+
iniciar_o_crear_usuario,
|
| 9 |
+
obtener_usuario_actual,
|
| 10 |
+
obtener_datos_usuario,
|
| 11 |
+
actualizar_datos_usuario,
|
| 12 |
+
)
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
estado_app = {
|
| 15 |
+
"usuario_actual": ""
|
|
|
|
|
|
|
|
|
|
| 16 |
}
|
| 17 |
|
| 18 |
|
| 19 |
+
def cargar_usuario_en_estado():
|
| 20 |
+
usuario = obtener_usuario_actual()
|
| 21 |
+
estado_app["usuario_actual"] = usuario
|
| 22 |
+
return usuario
|
| 23 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
def asegurar_usuario():
|
| 26 |
+
usuario = estado_app.get("usuario_actual") or obtener_usuario_actual()
|
| 27 |
+
if not usuario:
|
| 28 |
+
return None, "⚠️ Primero entra con tu nombre en la pestaña Inicio."
|
| 29 |
+
datos = obtener_datos_usuario(usuario)
|
| 30 |
+
if not datos:
|
| 31 |
+
return None, "⚠️ No se pudo cargar ese usuario."
|
| 32 |
+
estado_app["usuario_actual"] = usuario
|
| 33 |
+
return datos, None
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# ---------- LOGIN SIMPLE ---------- #
|
| 37 |
+
def entrar_usuario(nombre):
|
| 38 |
+
mensaje = iniciar_o_crear_usuario(nombre)
|
| 39 |
+
usuario = obtener_usuario_actual()
|
| 40 |
+
estado_app["usuario_actual"] = usuario
|
| 41 |
+
return mensaje
|
| 42 |
|
| 43 |
+
|
| 44 |
+
def ver_usuario_actual():
|
| 45 |
+
usuario = obtener_usuario_actual()
|
| 46 |
+
if not usuario:
|
| 47 |
+
return "👤 No hay usuario activo."
|
| 48 |
+
estado_app["usuario_actual"] = usuario
|
| 49 |
+
return f"👤 Usuario actual: **{usuario}**"
|
| 50 |
|
| 51 |
|
| 52 |
# ---------- CHATBOT NUTI ---------- #
|
| 53 |
def conversar_nuti(mensaje, historial):
|
| 54 |
+
datos, error = asegurar_usuario()
|
| 55 |
+
if error:
|
| 56 |
+
return historial, error
|
| 57 |
+
|
| 58 |
if not mensaje or not mensaje.strip():
|
| 59 |
return historial, ""
|
| 60 |
|
| 61 |
if historial is None:
|
| 62 |
historial = []
|
| 63 |
|
| 64 |
+
memoria_nuti = datos.get("memoria_nuti", [])
|
| 65 |
+
memoria_nuti.append({"role": "user", "content": mensaje})
|
| 66 |
historial.append({"role": "user", "content": mensaje})
|
| 67 |
|
| 68 |
+
respuesta = buscar_respuesta(mensaje, memoria_nuti)
|
|
|
|
| 69 |
|
| 70 |
+
memoria_nuti.append({"role": "assistant", "content": respuesta})
|
| 71 |
historial.append({"role": "assistant", "content": respuesta})
|
| 72 |
+
|
| 73 |
+
datos["memoria_nuti"] = memoria_nuti[-20:]
|
| 74 |
+
actualizar_datos_usuario(datos)
|
| 75 |
+
|
| 76 |
return historial, ""
|
| 77 |
|
| 78 |
|
| 79 |
# ---------- COACH EMOCIONAL ---------- #
|
| 80 |
def conversar_coach(mensaje, historial):
|
| 81 |
+
datos, error = asegurar_usuario()
|
| 82 |
+
if error:
|
| 83 |
+
return historial, error
|
| 84 |
+
|
| 85 |
if not mensaje or not mensaje.strip():
|
| 86 |
return historial, ""
|
| 87 |
|
| 88 |
if historial is None:
|
| 89 |
historial = []
|
| 90 |
|
| 91 |
+
memoria_coach = datos.get("memoria_coach", [])
|
| 92 |
+
memoria_coach.append({"role": "user", "content": mensaje})
|
| 93 |
historial.append({"role": "user", "content": mensaje})
|
| 94 |
|
| 95 |
+
respuesta = coach_emocional_inteligente(mensaje, memoria_coach)
|
|
|
|
| 96 |
|
| 97 |
+
memoria_coach.append({"role": "assistant", "content": respuesta})
|
| 98 |
historial.append({"role": "assistant", "content": respuesta})
|
| 99 |
+
|
| 100 |
+
datos["memoria_coach"] = memoria_coach[-20:]
|
| 101 |
+
actualizar_datos_usuario(datos)
|
| 102 |
+
|
| 103 |
return historial, ""
|
| 104 |
|
| 105 |
|
| 106 |
# ---------- CÁLCULO DE CALORÍAS ---------- #
|
| 107 |
def calcular_calorias(edad, peso, altura, genero, actividad, meta):
|
| 108 |
if not all([edad, peso, altura, genero, actividad, meta]):
|
| 109 |
+
return None, "⚠️ Completa todos los datos para calcular tus calorías."
|
| 110 |
|
| 111 |
+
if str(genero).lower() == "mujer":
|
| 112 |
bmr = 655 + (9.6 * peso) + (1.8 * altura) - (4.7 * edad)
|
| 113 |
else:
|
| 114 |
bmr = 66 + (13.7 * peso) + (5 * altura) - (6.8 * edad)
|
|
|
|
| 121 |
"muy activo": 1.9
|
| 122 |
}
|
| 123 |
|
| 124 |
+
calorias_base = bmr * factores.get(str(actividad).lower(), 1.55)
|
| 125 |
|
| 126 |
+
if str(meta).lower() == "bajar de peso":
|
| 127 |
calorias_totales = round(calorias_base * 0.8)
|
| 128 |
+
elif str(meta).lower() == "subir de peso":
|
| 129 |
calorias_totales = round(calorias_base * 1.15)
|
| 130 |
else:
|
| 131 |
calorias_totales = round(calorias_base)
|
| 132 |
|
| 133 |
+
mensaje = (
|
| 134 |
+
f"🎯 Tu meta es **{str(meta).lower()}**.\n"
|
|
|
|
|
|
|
|
|
|
| 135 |
f"🔥 Puedes consumir aproximadamente **{calorias_totales} calorías por día**."
|
| 136 |
)
|
| 137 |
+
return calorias_totales, mensaje
|
| 138 |
|
| 139 |
|
| 140 |
# ---------- GUARDAR DATOS ---------- #
|
| 141 |
def guardar_informacion(nombre, edad, peso, altura, genero, actividad, meta, condicion, alergias):
|
| 142 |
+
datos, error = asegurar_usuario()
|
| 143 |
+
if error:
|
| 144 |
+
return error
|
| 145 |
+
|
| 146 |
perfil = {
|
| 147 |
"nombre": nombre,
|
| 148 |
"edad": edad,
|
|
|
|
| 155 |
"alergias": alergias
|
| 156 |
}
|
| 157 |
|
| 158 |
+
calorias_totales, mensaje_calorias = calcular_calorias(edad, peso, altura, genero, actividad, meta)
|
| 159 |
+
|
| 160 |
+
datos["perfil"] = perfil
|
| 161 |
+
if calorias_totales is not None:
|
| 162 |
+
datos["calorias_totales"] = calorias_totales
|
| 163 |
+
datos["calorias_restantes"] = calorias_totales
|
| 164 |
+
|
| 165 |
+
actualizar_datos_usuario(datos)
|
| 166 |
|
| 167 |
+
return (
|
| 168 |
f"✅ Información guardada.\n"
|
| 169 |
f"**Nombre:** {nombre or 'Sin nombre'}\n"
|
| 170 |
f"**Condición:** {condicion or 'ninguna'}\n"
|
| 171 |
+
f"**Alergias:** {alergias or 'ninguna'}\n\n"
|
| 172 |
+
f"{mensaje_calorias}"
|
| 173 |
)
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
# ---------- CALORÍAS DEL RELOJ ---------- #
|
| 177 |
def calorias_reloj(calorias_quemadas):
|
| 178 |
+
datos, error = asegurar_usuario()
|
| 179 |
+
if error:
|
| 180 |
+
return error
|
| 181 |
+
|
| 182 |
if calorias_quemadas is None:
|
| 183 |
return "⚠️ Ingresa las calorías quemadas."
|
| 184 |
|
| 185 |
+
datos["calorias_restantes"] = datos.get("calorias_restantes", 0) + calorias_quemadas
|
| 186 |
+
actualizar_datos_usuario(datos)
|
| 187 |
|
| 188 |
return (
|
| 189 |
f"⌚ Has quemado **{calorias_quemadas} kcal**.\n"
|
| 190 |
+
f"🔥 Te quedan **{datos['calorias_restantes']} kcal** disponibles hoy."
|
| 191 |
)
|
| 192 |
|
| 193 |
|
|
|
|
| 212 |
|
| 213 |
|
| 214 |
def registrar_comida(imagen):
|
| 215 |
+
datos, error = asegurar_usuario()
|
| 216 |
+
if error:
|
| 217 |
+
return error
|
| 218 |
+
|
| 219 |
info, calorias = analizar_foto(imagen)
|
| 220 |
|
| 221 |
if calorias == 0:
|
| 222 |
return info
|
| 223 |
|
| 224 |
+
datos["calorias_restantes"] = max(datos.get("calorias_restantes", 0) - calorias, 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
+
historial = datos.get("historial_comidas", [])
|
| 227 |
+
historial.append({
|
| 228 |
"fecha": str(datetime.now()),
|
| 229 |
"comida": info,
|
| 230 |
"calorias": calorias
|
| 231 |
})
|
| 232 |
+
datos["historial_comidas"] = historial[-20:]
|
| 233 |
|
| 234 |
+
actualizar_datos_usuario(datos)
|
| 235 |
|
| 236 |
return (
|
| 237 |
f"{info}\n\n"
|
| 238 |
+
f"🔥 Calorías restantes del día: **{datos['calorias_restantes']} kcal**."
|
| 239 |
)
|
| 240 |
|
| 241 |
|
| 242 |
def mostrar_historial():
|
| 243 |
+
datos, error = asegurar_usuario()
|
| 244 |
+
if error:
|
| 245 |
+
return error
|
| 246 |
+
|
| 247 |
+
historial = datos.get("historial_comidas", [])
|
| 248 |
|
| 249 |
if not historial:
|
| 250 |
+
return "📭 Aún no has registrado comidas."
|
| 251 |
|
| 252 |
texto = "🍴 **Historial de comidas:**\n\n"
|
| 253 |
for i, item in enumerate(historial[-10:], 1):
|
| 254 |
texto += f"{i}. {item['comida']}\n"
|
| 255 |
|
| 256 |
+
texto += f"\n🔥 Te quedan **{datos.get('calorias_restantes', 0)} kcal** por consumir hoy."
|
| 257 |
return texto
|
| 258 |
|
| 259 |
|
| 260 |
# ---------- RECETAS ---------- #
|
| 261 |
def subir_receta(nombre, descripcion, imagen):
|
| 262 |
+
datos, error = asegurar_usuario()
|
| 263 |
+
if error:
|
| 264 |
+
return error
|
| 265 |
+
|
| 266 |
if not nombre or not descripcion:
|
| 267 |
return "⚠️ Ingresa nombre y descripción."
|
| 268 |
|
| 269 |
+
recetas = datos.get("recetas", [])
|
| 270 |
+
recetas.append({
|
| 271 |
"nombre": nombre,
|
| 272 |
"descripcion": descripcion,
|
| 273 |
"imagen": str(imagen) if imagen is not None else None
|
| 274 |
})
|
| 275 |
+
datos["recetas"] = recetas[-20:]
|
| 276 |
|
| 277 |
+
actualizar_datos_usuario(datos)
|
| 278 |
return f"✅ Receta '{nombre}' añadida correctamente."
|
| 279 |
|
| 280 |
|
| 281 |
def mostrar_recetas():
|
| 282 |
+
datos, error = asegurar_usuario()
|
| 283 |
+
if error:
|
| 284 |
+
return error
|
| 285 |
+
|
| 286 |
+
recetas = datos.get("recetas", [])
|
| 287 |
|
| 288 |
if not recetas:
|
| 289 |
return "📭 No hay recetas cargadas aún."
|
|
|
|
| 349 |
f"📱 {n['redes']}\n"
|
| 350 |
f"💬 {n['reseña']}\n\n"
|
| 351 |
)
|
|
|
|
| 352 |
return texto
|
| 353 |
|
| 354 |
|
| 355 |
+
# ---------- RESUMEN ---------- #
|
| 356 |
def ver_resumen():
|
| 357 |
+
datos, error = asegurar_usuario()
|
| 358 |
+
if error:
|
| 359 |
+
return error
|
| 360 |
+
|
| 361 |
+
perfil = datos.get("perfil", {})
|
| 362 |
if not perfil:
|
| 363 |
return "📭 Aún no has guardado tus datos personales."
|
| 364 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
return (
|
| 366 |
f"👤 **Resumen del usuario**\n\n"
|
| 367 |
+
f"**Nombre:** {perfil.get('nombre', 'Usuario')}\n"
|
| 368 |
+
f"**Meta:** {perfil.get('meta', 'No definida')}\n"
|
| 369 |
+
f"**Actividad:** {perfil.get('actividad', 'No definida')}\n"
|
| 370 |
+
f"**Condición:** {perfil.get('condicion', 'ninguna') or 'ninguna'}\n"
|
| 371 |
+
f"**Alergias:** {perfil.get('alergias', 'ninguna') or 'ninguna'}\n"
|
| 372 |
+
f"**Calorías objetivo:** {datos.get('calorias_totales', 0)} kcal\n"
|
| 373 |
+
f"**Calorías restantes:** {datos.get('calorias_restantes', 0)} kcal"
|
| 374 |
)
|
| 375 |
|
| 376 |
|
| 377 |
+
# ---------- INTERFAZ ---------- #
|
| 378 |
with gr.Blocks(title="NutriBot IA 🥗") as app:
|
| 379 |
gr.Markdown("# 🧠 Bienvenido a **NutriBot IA** 🍎")
|
| 380 |
gr.Markdown("Comer sano, inteligente y divertido. 🌿")
|
| 381 |
|
| 382 |
+
with gr.Tab("🔐 Inicio"):
|
| 383 |
+
nombre_login = gr.Textbox(label="Escribe tu nombre para entrar")
|
| 384 |
+
boton_login = gr.Button("Entrar")
|
| 385 |
+
salida_login = gr.Markdown()
|
| 386 |
+
boton_login.click(entrar_usuario, inputs=nombre_login, outputs=salida_login)
|
| 387 |
+
|
| 388 |
+
boton_ver_usuario = gr.Button("Ver usuario actual")
|
| 389 |
+
salida_usuario = gr.Markdown()
|
| 390 |
+
boton_ver_usuario.click(ver_usuario_actual, outputs=salida_usuario)
|
| 391 |
+
|
| 392 |
with gr.Tab("👤 Datos Personales"):
|
| 393 |
with gr.Row():
|
| 394 |
nombre = gr.Textbox(label="Nombre completo")
|
|
|
|
| 418 |
|
| 419 |
guardar_datos = gr.Button("Guardar información 🧾")
|
| 420 |
salida_datos = gr.Markdown()
|
|
|
|
| 421 |
guardar_datos.click(
|
| 422 |
guardar_informacion,
|
| 423 |
inputs=[nombre, edad, peso, altura, genero, actividad, meta, condicion, alergias],
|
|
|
|
| 450 |
chat_nuti = gr.Chatbot(label="Nuti - Tu guía de nutrición 🍎", type="messages")
|
| 451 |
entrada_nuti = gr.Textbox(label="Escribe algo para Nuti...")
|
| 452 |
boton_nuti = gr.Button("Enviar")
|
| 453 |
+
boton_nuti.click(conversar_nuti, inputs=[entrada_nuti, chat_nuti], outputs=[chat_nuti, entrada_nuti])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
|
| 455 |
with gr.Tab("🧘 Coach Emocional"):
|
| 456 |
chat_coach = gr.Chatbot(label="Coach Emocional 🌿", type="messages")
|
| 457 |
entrada_coach = gr.Textbox(label="Cuéntame cómo te sientes hoy...")
|
| 458 |
boton_coach = gr.Button("Enviar")
|
| 459 |
+
boton_coach.click(conversar_coach, inputs=[entrada_coach, chat_coach], outputs=[chat_coach, entrada_coach])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
|
| 461 |
with gr.Tab("🍽️ Recetas del Nutriólogo"):
|
| 462 |
nombre_rec = gr.Textbox(label="Nombre de la receta")
|
|
|
|
| 464 |
imagen_receta = gr.Image(label="Imagen (opcional)", type="filepath")
|
| 465 |
boton_subir = gr.Button("Subir receta")
|
| 466 |
salida_subir = gr.Textbox(label="Estado")
|
| 467 |
+
boton_subir.click(subir_receta, inputs=[nombre_rec, descripcion, imagen_receta], outputs=salida_subir)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
| 469 |
boton_ver = gr.Button("Ver recetas disponibles 🍲")
|
| 470 |
salida_recetas = gr.Markdown()
|
|
|
|
| 472 |
|
| 473 |
with gr.Tab("🎯 Retos Saludables"):
|
| 474 |
salida_retos = gr.Markdown()
|
|
|
|
| 475 |
boton_ver_retos = gr.Button("Ver Retos del Día")
|
| 476 |
boton_ver_retos.click(mostrar_retos, outputs=salida_retos)
|
| 477 |
|
|
|
|
| 485 |
ciudad = gr.Textbox(label="Ciudad")
|
| 486 |
boton_buscar = gr.Button("Buscar Nutriólogos 🌍")
|
| 487 |
salida_nutri = gr.Markdown()
|
| 488 |
+
boton_buscar.click(buscar_nutriologos, inputs=[pais, estado, ciudad], outputs=salida_nutri)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
|
| 490 |
|
| 491 |
if __name__ == "__main__":
|
| 492 |
+
cargar_usuario_en_estado()
|
| 493 |
app.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
|