Maximofn's picture
feat(SRC): :rocket: Add logs as output to get from API
21368bb
import gradio as gr
from queries import (clustering_esfuerzo_dieta_response, clustering_objetivo_response, clustering_entrenamiento_response,
clustering_cumplimiento_dieta_response, clustering_compromiso_response, clustering_diferencia_peso_response,
make_query, get_min_max_mean_mode_macros_differences)
from find_matches import find_user_dates_matches, find_macros_that_match_dates_of_users
from input_options import (opciones_esfuerzo, opciones_objetivo, opciones_cumplimiento_entrenamiento,
opciones_cumplimiento_dieta, opciones_compromiso, diferencia_peso_options)
def clustering_responses(esfuerzo_dieta, objetivo, cumplimiento_entrenamiento,
cumplimiento_dieta, compromiso, variacion_peso):
cluster_esfuerzo_dieta = clustering_esfuerzo_dieta_response(esfuerzo_dieta)
cluster_objetivo = clustering_objetivo_response(objetivo)
cluster_entrenamiento = clustering_entrenamiento_response(cumplimiento_entrenamiento)
cluster_cumplimiento_dieta = clustering_cumplimiento_dieta_response(cumplimiento_dieta)
cluster_compromiso = clustering_compromiso_response(compromiso)
diff_peso_min, diff_peso_max = clustering_diferencia_peso_response(variacion_peso)
return cluster_esfuerzo_dieta, cluster_objetivo, cluster_entrenamiento, cluster_cumplimiento_dieta, cluster_compromiso, diff_peso_min, diff_peso_max
def calcular_macros(esfuerzo_dieta, objetivo, cumplimiento_entrenamiento,
cumplimiento_dieta, compromiso, peso_inicial, peso_final,
train_day_protein_initial, train_day_carbs_initial, train_day_fat_initial,
intratrain_protein_initial, intratrain_carbs_initial,
rest_day_protein_initial, rest_day_carbs_initial, rest_day_fat_initial):
# Logs
logs = ""
# Obtenemos los valores correspondientes a cada selección
valor_esfuerzo = next(list(opcion.values())[0]["value"]
for opcion in opciones_esfuerzo
if list(opcion.values())[0]["text"] == esfuerzo_dieta)
valor_objetivo = next(list(opcion.values())[0]["value"]
for opcion in opciones_objetivo
if list(opcion.values())[0]["text"] == objetivo)
valor_cumplimiento_entr = next(list(opcion.values())[0]["value"]
for opcion in opciones_cumplimiento_entrenamiento
if list(opcion.values())[0]["text"] == cumplimiento_entrenamiento)
valor_cumplimiento_dieta = next(list(opcion.values())[0]["value"]
for opcion in opciones_cumplimiento_dieta
if list(opcion.values())[0]["text"] == cumplimiento_dieta)
valor_compromiso = next(list(opcion.values())[0]["value"]
for opcion in opciones_compromiso
if list(opcion.values())[0]["text"] == compromiso)
# Clustering
variacion_peso = peso_final - peso_inicial
print(f"\n\nVariación de peso: {variacion_peso}")
logs += f"\n\nVariación de peso: {variacion_peso}"
(cluster_esfuerzo_dieta, cluster_objetivo, cluster_entrenamiento, cluster_cumplimiento_dieta,
cluster_compromiso, diff_peso_min, diff_peso_max) = clustering_responses(valor_esfuerzo, valor_objetivo,
valor_cumplimiento_entr,
valor_cumplimiento_dieta, valor_compromiso,
variacion_peso)
# Imprimimos los resultados
print(f"Respuestas formulario:")
logs += f"\n\nRespuestas formulario:"
print(f"\tEsfuerzo para cumplir dieta: {cluster_esfuerzo_dieta}")
logs += f"\n\tEsfuerzo para cumplir dieta: {cluster_esfuerzo_dieta}"
print(f"\tObjetivo: {cluster_objetivo}")
logs += f"\n\tObjetivo: {cluster_objetivo}"
print(f"\tEntrenamiento: {cluster_entrenamiento}")
logs += f"\n\tEntrenamiento: {cluster_entrenamiento}"
print(f"\tCumplimiento dieta: {cluster_cumplimiento_dieta}")
logs += f"\n\tCumplimiento dieta: {cluster_cumplimiento_dieta}"
print(f"\tCompromiso: {cluster_compromiso}")
logs += f"\n\tCompromiso: {cluster_compromiso}"
print(f"\tPeso inicial: {peso_inicial}, peso final: {peso_final} --> Diferencia: {variacion_peso:.1f}")
logs += f"\n\tPeso inicial: {peso_inicial}, peso final: {peso_final} --> Diferencia: {variacion_peso:.1f}"
print(f"\t{diff_peso_min} <= Diferencia peso <= {diff_peso_max}")
logs += f"\n\t{diff_peso_min} <= Diferencia peso <= {diff_peso_max}"
# Crear query
query = make_query(cluster_esfuerzo_dieta, cluster_objetivo, cluster_entrenamiento, cluster_cumplimiento_dieta, cluster_compromiso, diff_peso_min, diff_peso_max)
# Print query
print(f"Query:")
logs += f"\n\nQuery:"
for q in query:
print(f"\t{list(q.keys())[0]}", end=" --> ")
logs += f"\n\t{list(q.keys())[0]} --> "
for primary_key in q.keys():
primary_key_dict = q[primary_key]
for i, secondary_key in enumerate(primary_key_dict.keys()):
if i == len(primary_key_dict.keys()) - 1:
print(f"{secondary_key}: \"{primary_key_dict[secondary_key]}\"", end="")
logs += f"{secondary_key}: \"{primary_key_dict[secondary_key]}\""
else:
print(f"{secondary_key}: \"{primary_key_dict[secondary_key]}\"", end=", ")
logs += f"{secondary_key}: \"{primary_key_dict[secondary_key]}\", "
print()
# Crear diccionario de matches
matches_dict = find_user_dates_matches(query, debug=False)
num_matches = len(matches_dict)
# Si no hay matches, intentamos con una query más básica
if num_matches == 0:
print("No se han encontrado coincidencias con la query original, intentamos con una query más básica")
logs += "\n\nNo se han encontrado coincidencias con la query original, intentamos con una query más básica"
query = make_query(cluster_esfuerzo_dieta, cluster_objetivo, cluster_entrenamiento, cluster_cumplimiento_dieta, cluster_compromiso, diff_peso_min, diff_peso_max, basic_query=True)
# Print query
print(f"Query:")
logs += "\n\nQuery:"
for q in query:
print(f"\t{list(q.keys())[0]}", end=" --> ")
logs += f"\n\t{list(q.keys())[0]} --> "
for primary_key in q.keys():
primary_key_dict = q[primary_key]
for i, secondary_key in enumerate(primary_key_dict.keys()):
if i == len(primary_key_dict.keys()) - 1:
print(f"{secondary_key}: \"{primary_key_dict[secondary_key]}\"", end="")
logs += f"{secondary_key}: \"{primary_key_dict[secondary_key]}\""
else:
print(f"{secondary_key}: \"{primary_key_dict[secondary_key]}\"", end=", ")
logs += f"{secondary_key}: \"{primary_key_dict[secondary_key]}\", "
print()
logs += "\n"
# Find matches
matches_dict = find_user_dates_matches(query)
num_matches = len(matches_dict)
# Print matches
print(f"Matches ({num_matches})")
logs += f"\n\nMatches ({num_matches})"
for user, dates in matches_dict.items():
print(f"\t{user}", end=" --> ")
logs += f"\t{user} --> "
for date in dates:
print(f"{date}", end=", ")
logs += f"{date}, "
print()
logs += "\n"
# Find macros that match dates of users
macros_differences_list, macros_differences_dict = find_macros_that_match_dates_of_users(matches_dict)
# Print macros
print(f"Diferencia de macros ({len(macros_differences_dict)}):")
logs += f"\n\nDiferencia de macros ({len(macros_differences_dict)}):"
for user, macros_difference in macros_differences_dict.items():
print(f"\t{user} --> fecha de match: {macros_difference['date_of_match']}, fecha de asignación de macros: {macros_difference['date_of_macros_asignation']}, días entre match y asignación: {macros_difference['days_between_match_and_macros_asignation']}, diferencia de macros: {macros_difference['macros_difference']}")
logs += f"\n\t{user} --> fecha de match: {macros_difference['date_of_match']}, fecha de asignación de macros: {macros_difference['date_of_macros_asignation']}, días entre match y asignación: {macros_difference['days_between_match_and_macros_asignation']}, diferencia de macros: {macros_difference['macros_difference']}"
# Calculate macros min, max and mean
if len(macros_differences_list) > 0:
(train_day_protein_std, train_day_carbs_std, train_day_fat_std, intratrain_protein_std, intratrain_carbs_std,
rest_day_protein_std, rest_day_carbs_std, rest_day_fat_std) = get_min_max_mean_mode_macros_differences(macros_differences_list)
else:
train_day_protein_std = [0, 0, 0, 0]
train_day_carbs_std = [0, 0, 0, 0]
train_day_fat_std = [0, 0, 0, 0]
intratrain_protein_std = [0, 0, 0, 0]
intratrain_carbs_std = [0, 0, 0, 0]
rest_day_protein_std = [0, 0, 0, 0]
rest_day_carbs_std = [0, 0, 0, 0]
rest_day_fat_std = [0, 0, 0, 0]
# Print macros min, max and mean
print("Variación de macros:")
logs += "\n\nVariación de macros:"
print(f"\tproteína día de entreno: Min: {train_day_protein_std[0]}, Max: {train_day_protein_std[1]}, Mean: {train_day_protein_std[2]:.2f}, Mode: {train_day_protein_std[3]}")
logs += f"\n\tproteína día de entreno: Min: {train_day_protein_std[0]}, Max: {train_day_protein_std[1]}, Mean: {train_day_protein_std[2]:.2f}, Mode: {train_day_protein_std[3]}"
print(f"\tcarbohidratos día de entreno: Min: {train_day_carbs_std[0]}, Max: {train_day_carbs_std[1]}, Mean: {train_day_carbs_std[2]:.2f}, Mode: {train_day_carbs_std[3]}")
logs += f"\n\tcarbohidratos día de entreno: Min: {train_day_carbs_std[0]}, Max: {train_day_carbs_std[1]}, Mean: {train_day_carbs_std[2]:.2f}, Mode: {train_day_carbs_std[3]}"
print(f"\tgrasas día de entreno: Min: {train_day_fat_std[0]}, Max: {train_day_fat_std[1]}, Mean: {train_day_fat_std[2]:.2f}, Mode: {train_day_fat_std[3]}")
logs += f"\n\tgrasas día de entreno: Min: {train_day_fat_std[0]}, Max: {train_day_fat_std[1]}, Mean: {train_day_fat_std[2]:.2f}, Mode: {train_day_fat_std[3]}"
print(f"\tproteína intraentreno: Min: {intratrain_protein_std[0]}, Max: {intratrain_protein_std[1]}, Mean: {intratrain_protein_std[2]:.2f}, Mode: {intratrain_protein_std[3]}")
logs += f"\n\tproteína intraentreno: Min: {intratrain_protein_std[0]}, Max: {intratrain_protein_std[1]}, Mean: {intratrain_protein_std[2]:.2f}, Mode: {intratrain_protein_std[3]}"
print(f"\tcarbohidratos intraentreno: Min: {intratrain_carbs_std[0]}, Max: {intratrain_carbs_std[1]}, Mean: {intratrain_carbs_std[2]:.2f}, Mode: {intratrain_carbs_std[3]}")
logs += f"\n\tcarbohidratos intraentreno: Min: {intratrain_carbs_std[0]}, Max: {intratrain_carbs_std[1]}, Mean: {intratrain_carbs_std[2]:.2f}, Mode: {intratrain_carbs_std[3]}"
print(f"\tproteína día de descanso: Min: {rest_day_protein_std[0]}, Max: {rest_day_protein_std[1]}, Mean: {rest_day_protein_std[2]:.2f}, Mode: {rest_day_protein_std[3]}")
logs += f"\n\tproteína día de descanso: Min: {rest_day_protein_std[0]}, Max: {rest_day_protein_std[1]}, Mean: {rest_day_protein_std[2]:.2f}, Mode: {rest_day_protein_std[3]}"
print(f"\tcarbohidratos día de descanso: Min: {rest_day_carbs_std[0]}, Max: {rest_day_carbs_std[1]}, Mean: {rest_day_carbs_std[2]:.2f}, Mode: {rest_day_carbs_std[3]}")
logs += f"\n\tcarbohidratos día de descanso: Min: {rest_day_carbs_std[0]}, Max: {rest_day_carbs_std[1]}, Mean: {rest_day_carbs_std[2]:.2f}, Mode: {rest_day_carbs_std[3]}"
print(f"\tgrasas día de descanso: Min: {rest_day_fat_std[0]}, Max: {rest_day_fat_std[1]}, Mean: {rest_day_fat_std[2]:.2f}, Mode: {rest_day_fat_std[3]}")
logs += f"\n\tgrasas día de descanso: Min: {rest_day_fat_std[0]}, Max: {rest_day_fat_std[1]}, Mean: {rest_day_fat_std[2]:.2f}, Mode: {rest_day_fat_std[3]}"
# Get macros mode
train_day_protein_mode = train_day_protein_std[3]
train_day_carbs_mode = train_day_carbs_std[3]
train_day_fat_mode = train_day_fat_std[3]
intratrain_protein_mode = intratrain_protein_std[3]
intratrain_carbs_mode = intratrain_carbs_std[3]
rest_day_protein_mode = rest_day_protein_std[3]
rest_day_carbs_mode = rest_day_carbs_std[3]
rest_day_fat_mode = rest_day_fat_std[3]
# Calculate macros final
train_day_protein_final = train_day_protein_initial + train_day_protein_mode
train_day_carbs_final = train_day_carbs_initial + train_day_carbs_mode
train_day_fat_final = train_day_fat_initial + train_day_fat_mode
intratrain_protein_final = intratrain_protein_initial + intratrain_protein_mode
intratrain_carbs_final = intratrain_carbs_initial + intratrain_carbs_mode
rest_day_protein_final = rest_day_protein_initial + rest_day_protein_mode
rest_day_carbs_final = rest_day_carbs_initial + rest_day_carbs_mode
rest_day_fat_final = rest_day_fat_initial + rest_day_fat_mode
# Print macros
print("Macros finales:")
logs += "\n\nMacros finales:"
print(f"\tProteína día de entreno inicial: {train_day_protein_initial} --> final: {train_day_protein_final}")
logs += f"\n\tProteína día de entreno inicial: {train_day_protein_initial} --> final: {train_day_protein_final}"
print(f"\tCarbohidratos día de entreno inicial: {train_day_carbs_initial} --> final: {train_day_carbs_final}")
logs += f"\n\tCarbohidratos día de entreno inicial: {train_day_carbs_initial} --> final: {train_day_carbs_final}"
print(f"\tGrasas día de entreno inicial: {train_day_fat_initial} --> final: {train_day_fat_final}")
logs += f"\n\tGrasas día de entreno inicial: {train_day_fat_initial} --> final: {train_day_fat_final}"
print(f"\tProteína intraentreno inicial: {intratrain_protein_initial} --> final: {intratrain_protein_final}")
logs += f"\n\tProteína intraentreno inicial: {intratrain_protein_initial} --> final: {intratrain_protein_final}"
print(f"\tCarbohidratos intraentreno inicial: {intratrain_carbs_initial} --> final: {intratrain_carbs_final}")
logs += f"\n\tCarbohidratos intraentreno inicial: {intratrain_carbs_initial} --> final: {intratrain_carbs_final}"
print(f"\tProteína día de descanso inicial: {rest_day_protein_initial} --> final: {rest_day_protein_final}")
logs += f"\n\tProteína día de descanso inicial: {rest_day_protein_initial} --> final: {rest_day_protein_final}"
print(f"\tCarbohidratos día de descanso inicial: {rest_day_carbs_initial} --> final: {rest_day_carbs_final}")
logs += f"\n\tCarbohidratos día de descanso inicial: {rest_day_carbs_initial} --> final: {rest_day_carbs_final}"
print(f"\tGrasas día de descanso inicial: {rest_day_fat_initial} --> final: {rest_day_fat_final}")
logs += f"\n\tGrasas día de descanso inicial: {rest_day_fat_initial} --> final: {rest_day_fat_final}"
return (train_day_protein_final, train_day_carbs_final, train_day_fat_final,
intratrain_protein_final, intratrain_carbs_final,
rest_day_protein_final, rest_day_carbs_final, rest_day_fat_final,
logs)
# Definimos el color naranja
naranja = "#ea580b"
title = f"""
<h1 style="text-align: center; color: {naranja}; margin: 0; padding-bottom: 30px; font-size: 50px;">Macros evolution</h1>
"""
title_macros_iniciales_html = f"""
<h2 style="text-align: center; color: {naranja}; margin: 0; padding: 0;">Macros iniciales</h2>
"""
title_cuestionario_html = f"""
<h2 style="text-align: center; color: {naranja}; margin: 0; padding: 0;">Respuestas cuestionario</h2>
"""
title_macros_finales_html = f"""
<h2 style="text-align: center; color: {naranja}; margin: 0; padding: 0;">Macros finales</h2>
"""
style_css = f"""
<style>
.demo {{
background-color: {naranja};
}}
.input-group, .output-group {{
background-color: {naranja};
padding: 2px;
border-radius: 7px;
}}
.input-row .output-row {{
}}
.input-column {{
}}
.input-number {{
background-color: black;
color: white;
}}
.input-dropdown {{
background-color: black;
color: white;
}}
.calcular-btn {{
background-color: {naranja};
color: white;
border-radius: 7px;
margin-bottom: 70px;
}}
.output-number {{
background-color: black;
color: white;
}}
</style>
"""
# Creamos la interfaz
with gr.Blocks(css=style_css, elem_classes="demo") as demo:
# Procesamos las opciones para obtener solo los textos
textos_esfuerzo = [list(opcion.values())[0]["text"] for opcion in opciones_esfuerzo]
textos_objetivo = [list(opcion.values())[0]["text"] for opcion in opciones_objetivo]
textos_cumplimiento_entr = [list(opcion.values())[0]["text"] for opcion in opciones_cumplimiento_entrenamiento]
textos_cumplimiento_dieta = [list(opcion.values())[0]["text"] for opcion in opciones_cumplimiento_dieta]
textos_compromiso = [list(opcion.values())[0]["text"] for opcion in opciones_compromiso]
# Title
gr.Markdown(title)
# Entradas
gr.Markdown(title_macros_iniciales_html)
with gr.Group(elem_classes="input-group"):
with gr.Row(elem_classes="input-row"):
with gr.Column(elem_classes="input-column"):
train_day_protein_initial = gr.Number(
label="Proteína día de entreno (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
train_day_carbs_initial = gr.Number(
label="Carbohidratos día de entreno (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
train_day_fat_initial = gr.Number(
label="Grasas día de entreno (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
with gr.Column(elem_classes="input-column"):
intratrain_protein_initial = gr.Number(
label="Proteína intraentreno (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
intratrain_carbs_initial = gr.Number(
label="Carbohidratos intraentreno (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
with gr.Column(elem_classes="input-column"):
rest_day_protein_initial = gr.Number(
label="Proteína día de descanso (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
rest_day_carbs_initial = gr.Number(
label="Carbohidratos día de descanso (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
rest_day_fat_initial = gr.Number(
label="Grasas día de descanso (g)",
precision=0,
value=150,
step=10,
minimum=0,
elem_classes="input-number"
)
gr.Markdown(title_cuestionario_html)
with gr.Group(elem_classes="input-group"):
with gr.Row(elem_classes="input-row"):
esfuerzo = gr.Dropdown(
choices=textos_esfuerzo,
label="Esfuerzo dieta",
value="No costó nada",
elem_classes="input-dropdown"
)
cumplimiento_dieta = gr.Dropdown(
choices=textos_cumplimiento_dieta,
label="Cumplimiento de la dieta",
value="Perfecta",
elem_classes="input-dropdown"
)
objetivo = gr.Dropdown(
choices=textos_objetivo,
label="Objetivo",
value="volumen (nada cambia)",
elem_classes="input-dropdown"
)
with gr.Row(elem_classes="input-row"):
cumplimiento_entr = gr.Dropdown(
choices=textos_cumplimiento_entr,
label="Cumplimiento del entrenamiento",
value="Lo hice perfecto",
elem_classes="input-dropdown"
)
compromiso = gr.Dropdown(
choices=textos_compromiso,
label="Compromiso",
value="Máximo",
elem_classes="input-dropdown"
)
with gr.Row(elem_classes="input-row"):
peso_inicial = gr.Number(
label="Peso inicial (kg)",
precision=2,
value=70,
step=0.1,
elem_classes="input-number"
)
peso_final = gr.Number(
label="Peso final (kg)",
precision=2,
value=70.7,
step=0.1,
elem_classes="input-number"
)
# Versión simple del botón
calcular_btn = gr.Button(
"Calcular macros",
variant="primary",
size="lg",
elem_classes="calcular-btn"
)
# Salidas
gr.Markdown(title_macros_finales_html)
with gr.Group(elem_classes="output-group"):
with gr.Row(elem_classes="output-row"):
with gr.Column():
train_day_protein_final = gr.Number(label="Proteína día de entreno Final (g)", precision=0, elem_classes="output-number")
train_day_carbs_final = gr.Number(label="Carbohidratos día de entreno Final (g)", precision=0, elem_classes="output-number")
train_day_fat_final = gr.Number(label="Grasas día de entreno Final (g)", precision=0, elem_classes="output-number")
with gr.Column():
intratrain_protein_final = gr.Number(label="Proteína intraentreno Final (g)", precision=0, elem_classes="output-number")
intratrain_carbs_final = gr.Number(label="Carbohidratos intraentreno Final (g)", precision=0, elem_classes="output-number")
with gr.Column():
rest_day_protein_final = gr.Number(label="Proteína día de descanso Final (g)", precision=0, elem_classes="output-number")
rest_day_carbs_final = gr.Number(label="Carbohidratos día de descanso Final (g)", precision=0, elem_classes="output-number")
rest_day_fat_final = gr.Number(label="Grasas día de descanso Final (g)", precision=0, elem_classes="output-number")
# Logs
logs = gr.Textbox(label="Logs", lines=10, elem_classes="output-textbox", visible=False)
# Conectamos el botón con la función
calcular_btn.click(
fn=calcular_macros,
inputs=[esfuerzo, objetivo, cumplimiento_entr, cumplimiento_dieta,
compromiso, peso_inicial, peso_final,
train_day_protein_initial, train_day_carbs_initial, train_day_fat_initial,
intratrain_protein_initial, intratrain_carbs_initial,
rest_day_protein_initial, rest_day_carbs_initial, rest_day_fat_initial],
outputs=[train_day_protein_final, train_day_carbs_final, train_day_fat_final,
intratrain_protein_final, intratrain_carbs_final,
rest_day_protein_final, rest_day_carbs_final, rest_day_fat_final,
logs]
)
demo.launch()