Spaces:
Sleeping
Sleeping
Commit ·
c89bc90
1
Parent(s): 7cf93e8
Update app, data and requirements
Browse files- DEP.csv +0 -0
- app.py +440 -0
- requirements.txt +3 -0
DEP.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import plotly.express as px
|
| 6 |
+
import plotly.graph_objects as go
|
| 7 |
+
|
| 8 |
+
# -------------------------------------------------------------
|
| 9 |
+
# Configuración: nombres de columnas (ajusta si tu CSV difiere)
|
| 10 |
+
# -------------------------------------------------------------
|
| 11 |
+
CSV_PATH = "DEP.csv"
|
| 12 |
+
|
| 13 |
+
# Columnas clave según tus encabezados
|
| 14 |
+
COL_SX = "SEXO"
|
| 15 |
+
COL_OWNER = "ULTIMOPROPIETARIO"
|
| 16 |
+
COL_ID = "NUMEROHATO" # ID animal
|
| 17 |
+
COL_REG = "REGISTRO" # Registro (opcional)
|
| 18 |
+
COL_MGT = "MGT" # Mérito genético total
|
| 19 |
+
|
| 20 |
+
# Métricas solicitadas (mapping etiqueta -> columna)
|
| 21 |
+
METRIC_MAP = {
|
| 22 |
+
"Peso al nacimiento": "DEPN",
|
| 23 |
+
"Peso al destete (205d)": "DEPP205",
|
| 24 |
+
"Leche": "DEPLECHE",
|
| 25 |
+
"Materno total": "DEPMATERNOTOTAL",
|
| 26 |
+
"Peso al año (365d)": "DEPP365",
|
| 27 |
+
"CE al año": "DEPCEA",
|
| 28 |
+
"Peso a 18 meses (550d)": "DEPP550",
|
| 29 |
+
"CE a 18 meses (550d)": "DEPCE550",
|
| 30 |
+
"Mérito genético total": "MGT",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# Mapeo de columnas EX por métrica (None si no existe EX)
|
| 34 |
+
EX_MAP = {
|
| 35 |
+
"Peso al nacimiento": "EXPN",
|
| 36 |
+
"Peso al destete (205d)": "EXP205",
|
| 37 |
+
"Leche": "EXLECHE",
|
| 38 |
+
"Materno total": None, # no presente en tu lista
|
| 39 |
+
"Peso al año (365d)": "EXP365",
|
| 40 |
+
"CE al año": "EXCEA",
|
| 41 |
+
"Peso a 18 meses (550d)": "EXP550",
|
| 42 |
+
"CE a 18 meses (550d)": "EXCE550",
|
| 43 |
+
"Mérito genético total": None, # sin EX
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# Orden de métricas para la telaraña (en el mismo orden que verás en el gráfico)
|
| 47 |
+
RADAR_ORDER = list(METRIC_MAP.keys())
|
| 48 |
+
|
| 49 |
+
# Columnas a mostrar en tablas
|
| 50 |
+
BASE_COLS = [COL_ID, COL_REG, COL_SX, COL_OWNER, COL_MGT]
|
| 51 |
+
TABLE_METRIC_COLS = [METRIC_MAP[k] for k in RADAR_ORDER if METRIC_MAP[k] != COL_MGT] + [COL_MGT]
|
| 52 |
+
DISPLAY_COLS = BASE_COLS + [c for c in TABLE_METRIC_COLS if c not in BASE_COLS]
|
| 53 |
+
|
| 54 |
+
# Paleta
|
| 55 |
+
COLOR_A = "#46973d" # verde
|
| 56 |
+
COLOR_B = "#ddb516" # amarillo
|
| 57 |
+
NEUTRAL = "#dcdcdc" # gris claro para métricas sin EX
|
| 58 |
+
|
| 59 |
+
# -------------------------------------------------------------
|
| 60 |
+
# Utilidades
|
| 61 |
+
# -------------------------------------------------------------
|
| 62 |
+
def _coerce_numeric(df, cols):
|
| 63 |
+
for c in cols:
|
| 64 |
+
if c in df.columns:
|
| 65 |
+
df[c] = pd.to_numeric(df[c], errors="coerce")
|
| 66 |
+
return df
|
| 67 |
+
|
| 68 |
+
def _normalize_minmax(x, gmin, gmax):
|
| 69 |
+
"""
|
| 70 |
+
Normaliza x a [0,1] usando min-max global. Acepta x escalar o Series.
|
| 71 |
+
Devuelve SIEMPRE una Series (para que .iloc[0] funcione aguas arriba).
|
| 72 |
+
"""
|
| 73 |
+
s = x if isinstance(x, pd.Series) else pd.Series([x])
|
| 74 |
+
|
| 75 |
+
# Broadcast de min/max si vienen como escalares
|
| 76 |
+
if np.isscalar(gmin):
|
| 77 |
+
min_s = pd.Series([gmin] * len(s), index=s.index)
|
| 78 |
+
elif isinstance(gmin, pd.Series):
|
| 79 |
+
min_s = gmin.reindex(s.index, fill_value=gmin.iloc[0] if len(gmin) else 0)
|
| 80 |
+
else:
|
| 81 |
+
min_s = pd.Series([0] * len(s), index=s.index)
|
| 82 |
+
|
| 83 |
+
if np.isscalar(gmax):
|
| 84 |
+
max_s = pd.Series([gmax] * len(s), index=s.index)
|
| 85 |
+
elif isinstance(gmax, pd.Series):
|
| 86 |
+
max_s = gmax.reindex(s.index, fill_value=gmax.iloc[0] if len(gmax) else 1)
|
| 87 |
+
else:
|
| 88 |
+
max_s = pd.Series([1] * len(s), index=s.index)
|
| 89 |
+
|
| 90 |
+
rng = max_s - min_s
|
| 91 |
+
rng = rng.replace(0, 1) # evita división por cero
|
| 92 |
+
norm = (s - min_s) / rng
|
| 93 |
+
return norm.fillna(0.0).clip(0, 1)
|
| 94 |
+
|
| 95 |
+
def _hex_to_rgb(hex_color):
|
| 96 |
+
hex_color = hex_color.lstrip("#")
|
| 97 |
+
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
|
| 98 |
+
|
| 99 |
+
def _rgb_to_hex(rgb):
|
| 100 |
+
return "#%02x%02x%02x" % rgb
|
| 101 |
+
|
| 102 |
+
def _lerp_color(hex_a, hex_b, t):
|
| 103 |
+
"""Interpolación lineal entre COLOR_A y COLOR_B. t en [0,1]."""
|
| 104 |
+
a = _hex_to_rgb(hex_a)
|
| 105 |
+
b = _hex_to_rgb(hex_b)
|
| 106 |
+
c = tuple(int(round(a[i] + (b[i]-a[i]) * float(t))) for i in range(3))
|
| 107 |
+
return _rgb_to_hex(c)
|
| 108 |
+
|
| 109 |
+
def _build_radar_with_accuracy(values_dict, acc_dict, title):
|
| 110 |
+
"""
|
| 111 |
+
values_dict: {etiqueta_métrica: valor_normalizado_0_1}
|
| 112 |
+
acc_dict: {etiqueta_métrica: exactitud (0-100) o None}
|
| 113 |
+
Construye un plot polar con:
|
| 114 |
+
- Barras (anillo) coloreadas por exactitud EX (0->verde ... 100->amarillo)
|
| 115 |
+
- Polígono de valores normalizados
|
| 116 |
+
"""
|
| 117 |
+
labels = list(values_dict.keys())
|
| 118 |
+
values = [values_dict[k] for k in labels]
|
| 119 |
+
|
| 120 |
+
# Ángulos y cierre del polígono
|
| 121 |
+
theta = labels + [labels[0]]
|
| 122 |
+
r_vals = values + [values[0]]
|
| 123 |
+
|
| 124 |
+
# Colores de exactitud por barra
|
| 125 |
+
bar_colors = []
|
| 126 |
+
for lab in labels:
|
| 127 |
+
ex = acc_dict.get(lab, None)
|
| 128 |
+
if ex is None or np.isnan(ex):
|
| 129 |
+
bar_colors.append(NEUTRAL)
|
| 130 |
+
else:
|
| 131 |
+
# Normalizamos EX esperando rango 0-100
|
| 132 |
+
t = max(0.0, min(1.0, float(ex) / 100.0))
|
| 133 |
+
bar_colors.append(_lerp_color(COLOR_A, COLOR_B, t))
|
| 134 |
+
|
| 135 |
+
fig = go.Figure()
|
| 136 |
+
|
| 137 |
+
# Anillo por exactitud (una barra por métrica)
|
| 138 |
+
fig.add_trace(
|
| 139 |
+
go.Barpolar(
|
| 140 |
+
r=[1.0] * len(labels),
|
| 141 |
+
theta=labels,
|
| 142 |
+
marker=dict(color=bar_colors, line=dict(color="white", width=1)),
|
| 143 |
+
opacity=0.6,
|
| 144 |
+
name="Exactitud (EX)",
|
| 145 |
+
hovertemplate="<b>%{theta}</b><br>Exactitud: %{marker.color}<extra></extra>"
|
| 146 |
+
)
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Polígono del valor normalizado
|
| 150 |
+
fig.add_trace(
|
| 151 |
+
go.Scatterpolar(
|
| 152 |
+
r=r_vals,
|
| 153 |
+
theta=theta,
|
| 154 |
+
mode="lines+markers",
|
| 155 |
+
fill="toself",
|
| 156 |
+
name="Valor normalizado",
|
| 157 |
+
line=dict(color=COLOR_A, width=3),
|
| 158 |
+
marker=dict(size=6, color=COLOR_B),
|
| 159 |
+
hovertemplate="<b>%{theta}</b><br>Valor: %{r:.2f}<extra></extra>"
|
| 160 |
+
)
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
fig.update_layout(
|
| 164 |
+
title=title,
|
| 165 |
+
showlegend=True,
|
| 166 |
+
paper_bgcolor="white",
|
| 167 |
+
polar=dict(
|
| 168 |
+
bgcolor="white",
|
| 169 |
+
radialaxis=dict(
|
| 170 |
+
visible=True,
|
| 171 |
+
range=[0, 1],
|
| 172 |
+
gridcolor="#eeeeee",
|
| 173 |
+
linecolor=COLOR_A
|
| 174 |
+
),
|
| 175 |
+
angularaxis=dict(
|
| 176 |
+
gridcolor="#f2f2f2",
|
| 177 |
+
linecolor=COLOR_A
|
| 178 |
+
)
|
| 179 |
+
),
|
| 180 |
+
margin=dict(l=10, r=10, t=60, b=10),
|
| 181 |
+
legend=dict(
|
| 182 |
+
orientation="h",
|
| 183 |
+
yanchor="bottom",
|
| 184 |
+
y=1.05,
|
| 185 |
+
xanchor="center",
|
| 186 |
+
x=0.5
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
return fig
|
| 190 |
+
|
| 191 |
+
# -------------------------------------------------------------
|
| 192 |
+
# Carga de datos
|
| 193 |
+
# -------------------------------------------------------------
|
| 194 |
+
def load_data():
|
| 195 |
+
# Si tu CSV tiene tildes/ñ raras, usa: pd.read_csv(CSV_PATH, encoding="latin-1")
|
| 196 |
+
df = pd.read_csv(CSV_PATH)
|
| 197 |
+
|
| 198 |
+
# Normaliza formatos básicos
|
| 199 |
+
if COL_SX in df.columns:
|
| 200 |
+
df[COL_SX] = df[COL_SX].astype(str).str.upper().str.strip()
|
| 201 |
+
if COL_OWNER in df.columns:
|
| 202 |
+
df[COL_OWNER] = df[COL_OWNER].astype(str).str.strip()
|
| 203 |
+
|
| 204 |
+
# A numérico
|
| 205 |
+
df = _coerce_numeric(df, list(set(TABLE_METRIC_COLS + [COL_MGT])))
|
| 206 |
+
|
| 207 |
+
# También a numérico las EX (si existen)
|
| 208 |
+
ex_cols = [c for c in EX_MAP.values() if c]
|
| 209 |
+
df = _coerce_numeric(df, ex_cols)
|
| 210 |
+
|
| 211 |
+
# Propietarios
|
| 212 |
+
owners = (
|
| 213 |
+
df[COL_OWNER].dropna().unique().tolist()
|
| 214 |
+
if COL_OWNER in df.columns else []
|
| 215 |
+
)
|
| 216 |
+
owners = sorted([o for o in owners if o not in ["", "nan"]])
|
| 217 |
+
|
| 218 |
+
# Mínimos y máximos globales para normalizar radar
|
| 219 |
+
metric_cols_present = [METRIC_MAP[k] for k in RADAR_ORDER if METRIC_MAP[k] in df.columns]
|
| 220 |
+
global_mins = df[metric_cols_present].min(numeric_only=True)
|
| 221 |
+
global_maxs = df[metric_cols_present].max(numeric_only=True)
|
| 222 |
+
|
| 223 |
+
return df, owners, global_mins, global_maxs
|
| 224 |
+
|
| 225 |
+
# -------------------------------------------------------------
|
| 226 |
+
# Lógica de filtros y salidas
|
| 227 |
+
# -------------------------------------------------------------
|
| 228 |
+
def _promedios_y_exactitud(df_subset, global_mins, global_maxs):
|
| 229 |
+
"""Devuelve (values_dict_normalized, acc_dict) para un subconjunto de df."""
|
| 230 |
+
valores = {}
|
| 231 |
+
ex_vals = {}
|
| 232 |
+
for label in RADAR_ORDER:
|
| 233 |
+
dep_col = METRIC_MAP[label]
|
| 234 |
+
ex_col = EX_MAP.get(label, None)
|
| 235 |
+
|
| 236 |
+
# valor (usa promedio del subconjunto)
|
| 237 |
+
if dep_col in df_subset.columns:
|
| 238 |
+
prom_val = pd.to_numeric(df_subset[dep_col], errors="coerce").mean()
|
| 239 |
+
valores[label] = float(_normalize_minmax(
|
| 240 |
+
prom_val,
|
| 241 |
+
global_mins.get(dep_col, 0),
|
| 242 |
+
global_maxs.get(dep_col, 1)
|
| 243 |
+
).iloc[0])
|
| 244 |
+
else:
|
| 245 |
+
valores[label] = 0.0
|
| 246 |
+
|
| 247 |
+
# exactitud (promedio EX si existe)
|
| 248 |
+
if ex_col and ex_col in df_subset.columns:
|
| 249 |
+
ex_prom = pd.to_numeric(df_subset[ex_col], errors="coerce").mean()
|
| 250 |
+
ex_vals[label] = float(ex_prom) if pd.notnull(ex_prom) else None
|
| 251 |
+
else:
|
| 252 |
+
ex_vals[label] = None
|
| 253 |
+
return valores, ex_vals
|
| 254 |
+
|
| 255 |
+
def _valores_y_exactitud_fila(row, df_cols, global_mins, global_maxs):
|
| 256 |
+
"""Devuelve (values_dict_normalized, acc_dict) para una fila concreta."""
|
| 257 |
+
valores = {}
|
| 258 |
+
ex_vals = {}
|
| 259 |
+
for label in RADAR_ORDER:
|
| 260 |
+
dep_col = METRIC_MAP[label]
|
| 261 |
+
ex_col = EX_MAP.get(label, None)
|
| 262 |
+
|
| 263 |
+
# Valor del individuo
|
| 264 |
+
if dep_col in df_cols:
|
| 265 |
+
val = pd.to_numeric(row.get(dep_col, np.nan), errors="coerce")
|
| 266 |
+
val = np.nan_to_num(val, nan=0.0)
|
| 267 |
+
valores[label] = float(_normalize_minmax(
|
| 268 |
+
val, global_mins.get(dep_col, 0), global_maxs.get(dep_col, 1)
|
| 269 |
+
).iloc[0])
|
| 270 |
+
else:
|
| 271 |
+
valores[label] = 0.0
|
| 272 |
+
|
| 273 |
+
# Exactitud del individuo
|
| 274 |
+
if ex_col and ex_col in df_cols:
|
| 275 |
+
exv = pd.to_numeric(row.get(ex_col, np.nan), errors="coerce")
|
| 276 |
+
ex_vals[label] = float(exv) if pd.notnull(exv) else None
|
| 277 |
+
else:
|
| 278 |
+
ex_vals[label] = None
|
| 279 |
+
return valores, ex_vals
|
| 280 |
+
|
| 281 |
+
def top_hembras_por_owner(df, owner, global_mins, global_maxs):
|
| 282 |
+
# Filtra por propietario y hembras
|
| 283 |
+
dff = df.copy()
|
| 284 |
+
if owner and owner != "—":
|
| 285 |
+
dff = dff[dff[COL_OWNER] == owner]
|
| 286 |
+
dff = dff[dff[COL_SX] == "H"]
|
| 287 |
+
|
| 288 |
+
# Ordena por MGT desc y limita a 30
|
| 289 |
+
dff = dff.sort_values(by=COL_MGT, ascending=False, na_position="last").head(30)
|
| 290 |
+
|
| 291 |
+
# Prepara tabla (muestra solo columnas útiles si existen)
|
| 292 |
+
cols_exist = [c for c in DISPLAY_COLS if c in dff.columns]
|
| 293 |
+
tabla = dff[cols_exist].reset_index(drop=True)
|
| 294 |
+
|
| 295 |
+
# Promedios para radar y exactitud
|
| 296 |
+
valores, ex_vals = _promedios_y_exactitud(dff, global_mins, global_maxs)
|
| 297 |
+
|
| 298 |
+
titulo = f"Promedio Hembras • {owner}" if owner else "Promedio Hembras"
|
| 299 |
+
fig = _build_radar_with_accuracy(valores, ex_vals, titulo)
|
| 300 |
+
return tabla, fig
|
| 301 |
+
|
| 302 |
+
def top_machos_por_metrica(df, metric_label):
|
| 303 |
+
met_col = METRIC_MAP.get(metric_label, COL_MGT)
|
| 304 |
+
dff = df.copy()
|
| 305 |
+
dff = dff[dff[COL_SX] == "M"]
|
| 306 |
+
dff = dff.sort_values(by=met_col, ascending=False, na_position="last").head(50)
|
| 307 |
+
cols_exist = [c for c in DISPLAY_COLS if c in dff.columns]
|
| 308 |
+
tabla = dff[cols_exist].reset_index(drop=True)
|
| 309 |
+
return tabla
|
| 310 |
+
|
| 311 |
+
# --- Callback del select (usa variables globales de normalización) ---
|
| 312 |
+
def radar_individual_from_selection(evt: gr.SelectData, df_machos_current):
|
| 313 |
+
"""
|
| 314 |
+
evt.index -> (row, col) seleccionado en la tabla de machos
|
| 315 |
+
"""
|
| 316 |
+
# Accede a las normalizaciones globales ya calculadas
|
| 317 |
+
global global_mins, global_maxs
|
| 318 |
+
|
| 319 |
+
if df_machos_current is None or len(df_machos_current) == 0:
|
| 320 |
+
return gr.update(value=None)
|
| 321 |
+
|
| 322 |
+
# Índice de fila seleccionada (puede ser int o (row, col))
|
| 323 |
+
try:
|
| 324 |
+
row_idx = evt.index[0] if isinstance(evt.index, (list, tuple)) else evt.index
|
| 325 |
+
except Exception:
|
| 326 |
+
return gr.update(value=None)
|
| 327 |
+
|
| 328 |
+
if row_idx is None or row_idx >= len(df_machos_current):
|
| 329 |
+
return gr.update(value=None)
|
| 330 |
+
|
| 331 |
+
row = df_machos_current.iloc[int(row_idx)]
|
| 332 |
+
|
| 333 |
+
valores, ex_vals = _valores_y_exactitud_fila(
|
| 334 |
+
row, df_machos_current.columns, global_mins, global_maxs
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
ident = str(row.get(COL_ID, "")) or "(sin ID)"
|
| 338 |
+
titulo = f"Radar individuo • {ident}"
|
| 339 |
+
fig = _build_radar_with_accuracy(valores, ex_vals, titulo)
|
| 340 |
+
return fig
|
| 341 |
+
|
| 342 |
+
# -------------------------------------------------------------
|
| 343 |
+
# Interfaz Gradio
|
| 344 |
+
# -------------------------------------------------------------
|
| 345 |
+
df_global, owners_global, global_mins, global_maxs = load_data()
|
| 346 |
+
|
| 347 |
+
# Valores iniciales
|
| 348 |
+
init_owner = owners_global[0] if owners_global else None
|
| 349 |
+
init_tabla_h, init_fig_h = top_hembras_por_owner(df_global, init_owner, global_mins, global_maxs)
|
| 350 |
+
init_tabla_m = top_machos_por_metrica(df_global, "Mérito genético total")
|
| 351 |
+
|
| 352 |
+
with gr.Blocks(title="Dashboard DEP's") as demo:
|
| 353 |
+
# CSS de estilo (fondo blanco y paleta)
|
| 354 |
+
gr.HTML(f"""
|
| 355 |
+
<style>
|
| 356 |
+
body {{ background: #ffffff !important; }}
|
| 357 |
+
.gradio-container {{ background: #ffffff !important; }}
|
| 358 |
+
h1, h2, h3, .prose h1, .prose h2, .prose h3 {{ color: {COLOR_A}; }}
|
| 359 |
+
.prose p, label, .label {{ color: #222222; }}
|
| 360 |
+
.gr-button, button {{ border-radius: 10px; }}
|
| 361 |
+
.gr-input, .gr-textbox, .gr-dropdown {{ border-color: {COLOR_A}; }}
|
| 362 |
+
.gradio-container a {{ color: {COLOR_B}; }}
|
| 363 |
+
</style>
|
| 364 |
+
""")
|
| 365 |
+
|
| 366 |
+
gr.Markdown(f"# <span style='color:{COLOR_A}'>Dashboard DEP's</span>")
|
| 367 |
+
gr.Markdown(
|
| 368 |
+
"Filtra **hembras** por **ULTIMOPROPIETARIO** (top 30 por MGT) y compara con telaraña de promedios. "
|
| 369 |
+
"Debajo, ordena **machos** por la métrica seleccionada (top 50) y haz **clic** en una fila para ver la telaraña del individuo."
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
# Estados compartidos
|
| 373 |
+
machos_state = gr.State(value=init_tabla_m) # guarda el DF mostrado actualmente en la tabla de machos
|
| 374 |
+
|
| 375 |
+
# --- Bloque HEMBRAS (por propietario) ---
|
| 376 |
+
with gr.Group():
|
| 377 |
+
gr.Markdown(f"## <span style='color:{COLOR_A}'>Hembras por ULTIMOPROPIETARIO</span> (Top 30 por MGT)")
|
| 378 |
+
with gr.Row():
|
| 379 |
+
dd_owner = gr.Dropdown(
|
| 380 |
+
choices=(["—"] + owners_global) if owners_global else ["—"],
|
| 381 |
+
value=(init_owner if init_owner else "—"),
|
| 382 |
+
label=f"ULTIMOPROPIETARIO (texto en {COLOR_B})"
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
with gr.Row():
|
| 386 |
+
out_tabla_hembras = gr.Dataframe(value=init_tabla_h, label="Hembras (Top 30 por MGT)", interactive=False)
|
| 387 |
+
out_radar_hembras = gr.Plot(value=init_fig_h, label="Telaraña: Promedios Hembras (anillo = EX)")
|
| 388 |
+
|
| 389 |
+
# --- Bloque MACHOS (ranking por métrica) ---
|
| 390 |
+
with gr.Group():
|
| 391 |
+
gr.Markdown(f"## <span style='color:{COLOR_A}'>Machos Top 50 por métrica</span> (clic en una fila para ver su telaraña)")
|
| 392 |
+
metrica_rank = gr.Dropdown(
|
| 393 |
+
choices=list(METRIC_MAP.keys()),
|
| 394 |
+
value="Mérito genético total",
|
| 395 |
+
label="Métrica para rankear machos"
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
# IMPORTANTE: interactive=False (no editable) y el .select sigue funcionando
|
| 399 |
+
out_tabla_machos = gr.Dataframe(value=init_tabla_m, label="Machos (Top 50)", interactive=False)
|
| 400 |
+
out_radar_macho = gr.Plot(label="Telaraña: Individuo (anillo = EX)")
|
| 401 |
+
|
| 402 |
+
# ---- Funciones de actualización ----
|
| 403 |
+
def update_hembras(owner):
|
| 404 |
+
tabla, fig = top_hembras_por_owner(df_global, owner if owner != "—" else None, global_mins, global_maxs)
|
| 405 |
+
return tabla, fig
|
| 406 |
+
|
| 407 |
+
def update_machos(metric_label):
|
| 408 |
+
tabla_m = top_machos_por_metrica(df_global, metric_label)
|
| 409 |
+
return tabla_m, tabla_m # devolvemos también para machos_state
|
| 410 |
+
|
| 411 |
+
# Disparadores: cambio de propietario -> actualiza tabla y radar hembras
|
| 412 |
+
dd_owner.change(
|
| 413 |
+
fn=update_hembras,
|
| 414 |
+
inputs=[dd_owner],
|
| 415 |
+
outputs=[out_tabla_hembras, out_radar_hembras]
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# Cambio de métrica -> actualiza machos y guarda en estado
|
| 419 |
+
metrica_rank.change(
|
| 420 |
+
fn=update_machos,
|
| 421 |
+
inputs=[metrica_rank],
|
| 422 |
+
outputs=[out_tabla_machos, machos_state]
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
# Click en tabla de machos -> radar del individuo (usa EX del registro)
|
| 426 |
+
out_tabla_machos.select(
|
| 427 |
+
fn=radar_individual_from_selection,
|
| 428 |
+
inputs=[machos_state],
|
| 429 |
+
outputs=[out_radar_macho]
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
# Crédito / pie de página
|
| 433 |
+
gr.Markdown(
|
| 434 |
+
f"<div style='text-align:center; font-size: 14px; margin-top: 12px; opacity:0.85;'>"
|
| 435 |
+
f"Elaborado por <b>Luis Arturo Arrieta</b> • Paleta <span style='color:{COLOR_A}'>{COLOR_A}</span> / <span style='color:{COLOR_B}'>{COLOR_B}</span>"
|
| 436 |
+
f"</div>"
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
if __name__ == "__main__":
|
| 440 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.36
|
| 2 |
+
pandas>=2.0
|
| 3 |
+
plotly>=5.20
|