Update app.py
Browse files3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738395 unmodified lines45464748495051525354555657585960616263644 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812934 unmodified lines1641651661671681691701711721731741751761771 unmodified line1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092105 unmodified lines2162172182192202212222236 unmodified lines2302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832846 unmodified lines2912922932942952962972982993001 unmodified line3023033043053063073081 unmodified line3103113123133 unmodified linesfrom dataclasses import dataclass, fieldfrom typing import Dict, Tuple, List# ==============================================================================# 1. ESPECIFICACIONES DE INGENIERÍA: HUSQVARNA HC3 (CORE S1+ / EP6)# ==============================================================================@dataclass(frozen=True)class BatterySpecs:"""Configuración de Hardware Inmutable."""MODELO: str = 'Husqvarna Hard Cross HC3'MOTOR: str = 'Shimano EP6 (85Nm)'# ENERGÍA (Simplo Core S1+)CAPACIDAD_NOMINAL_AH: float = 17.5VOLTAJE_NOMINAL: float = 36.0BUFFER_SEGURIDAD_BMS: float = 0.05 # 5% Reserva intocable# FÍSICAPESO_BICI_KG: float = 24.5PESO_EQUIPO_KG: float = 4.5AMPERAJE_CARGADOR: float = 4.0# CURVAS FÍSICAS (NMC 21700)OCV_X: Tuple[float, ...] = (0.0, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0)OCV_Y: Tuple[float, ...] = (31.0, 32.5, 34.0, 35.1, 35.8, 36.3, 36.7, 37.2, 38.0, 39.2, 40.8, 41.5, 42.0)TEMP_X: Tuple[float, ...] = (-10.0, -5.0, 0.0, 5.0, 10.0, 20.0, 40.0)TEMP_Y: Tuple[float, ...] = (0.70, 0.78, 0.85, 0.92, 0.97, 1.00, 1.00)# PERFILES DE RENDIMIENTOPERFILES_TORQUE: Dict[str, List[float]] = field(default_factory=lambda: {'ECO (Nvl 1)': [27, 5.0, 0.40, 0.96],'Nivel 2': [34, 6.8, 0.50, 0.95],5 unmodified linesSPECS = BatterySpecs()# ==============================================================================# 2. KERNEL FÍSICO DE SIMULACIÓN (V54)# ==============================================================================def get_voltage(soc: float) -> float:return float(np.interp(soc, SPECS.OCV_X, SPECS.OCV_Y))def calcular_salud(km: float, ciclos_drift: int) -> dict:# Degradación Cíclicaciclos = max(0.0, float(km) / 75.0)degradacion = (0.03 * (1 - np.exp(-0.05 * ciclos))) + (0.0002 * ciclos)soh = max(0.60, min(1.0, 1.0 - degradacion))# Drift (Desbalanceo)drift_pct = 0.0if ciclos_drift > 5:x = ciclos_drift - 54 unmodified linesdef factor_clima_ruta(temp: float) -> float:return float(np.interp(temp, SPECS.TEMP_X, SPECS.TEMP_Y))def simulador_master_v54(km, ciclos_drift, inicio, fin, temp_trastero):# Validacionesif temp_trastero < -5 or temp_trastero > 50:return {"estado": "ERROR_TEMP"}salud = calcular_salud(km, ciclos_drift)soh = salud["soh"]cap_total = SPECS.CAPACIDAD_NOMINAL_AH * soh# CASO 1: SOBRECARGA (Usuario pide menos de lo que tiene)if inicio > fin:exceso_ah = cap_total * ((inicio - fin) / 100.0)exceso_wh = exceso_ah * SPECS.VOLTAJE_NOMINALreturn {"estado": "DRENAR","soh": soh,"drift": salud["drift"],"tiempo": 0,"energia": -exceso_wh, # Energía negativa (a gastar)"cap_final_wh": cap_total * (inicio / 100.0) * SPECS.VOLTAJE_NOMINAL}# CASO 2: YA LISTA (Iguales)if inicio == fin:return {"estado": "CARGADO","soh": soh,"drift": salud["drift"],"tiempo": 0,"energia": 0,"cap_final_wh": cap_total * (inicio / 100.0) * SPECS.VOLTAJE_NOMINAL}# CASO 3: CARGA NECESARIAah_actual = cap_total * (inicio / 100.0)ah_objetivo = cap_total * (fin / 100.0)t_min = 0.0e_wh = 0.0# Arrhenius (Velocidad de Carga)if temp_trastero < 15: f_temp = max(0.15, 0.4 + (0.04 * temp_trastero))elif temp_trastero > 35: f_temp = 0.92else: f_temp = 1.0dt = 1.0 / 60.0# Integraciónwhile ah_actual < ah_objetivo:soc_now = ah_actual / cap_totalv_now = get_voltage(soc_now)i_target = SPECS.AMPERAJE_CARGADOR * f_temp# Simulación CV (Saturación)if v_now >= (SPECS.OCV_Y[-1] - 0.25):diff = v_now - (SPECS.OCV_Y[-1] - 0.6)i_real = i_target * np.exp(-4.5 * max(0, diff))34 unmodified lines"cap_final_wh": ah_actual * SPECS.VOLTAJE_NOMINAL}# ==============================================================================# 3. INTERFAZ VISUAL MAESTRA (V54 - PLATINUM UI)# ==============================================================================def generar_interfaz_final(km_val, temp_trastero, temp_ruta, elev_val, peso_piloto, ciclos_drift, inicio_val, fin_val):try:# Ejecutar Simulaciónres = simulador_master_v54(float(km_val), int(ciclos_drift),float(inicio_val), float(fin_val), float(temp_trastero))1 unmodified lineif res["estado"] == "ERROR_TEMP":return "<div style='background:#fee2e2; padding:20px; color:#991b1b; text-align:center;'>⛔ <b>ERROR:</b> Temperatura insegura.</div>"# --- GESTIÓN DE DATOS ---drift_pct = res["drift"]soh = res["soh"]pct_objetivo = float(fin_val)pct_inicio = float(inicio_val)# Lógica de Visualización de Cargaif res["estado"] == "DRENAR":tiempo_display = "EXCESO"# Mostramos la energía negativa en rojoenergia_display = f"{int(res['energia'])} Wh"cap_bruta = res['cap_final_wh']elif res["estado"] == "CARGADO":tiempo_display = "LISTA"energia_display = "0 Wh"cap_bruta = res['cap_final_wh']else:# Carga Normalcap_bruta = res['cap_final_wh']h, m = divmod(math.ceil(res["tiempo"]), 60)tiempo_display = f"{h}h {m}m"energia_display = f"+{int(res['energia'])} Wh"# --- FÍSICA DE RUTA ---cap_util = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS)cap_util_drift = cap_util * (1.0 - drift_pct)wh_perdidos_drift = cap_util * drift_pct5 unmodified linesmasa_total = SPECS.PESO_BICI_KG + float(peso_piloto) + SPECS.PESO_EQUIPO_KGg = 9.81wh_gravedad = (masa_total * g * float(elev_val)) / 3600.0# --- UI: PANEL DE ESTRATEGIA ---def get_card_style(is_active, color_hex):base = "flex: 1; padding: 10px; border-radius: 12px; margin: 2px;"6 unmodified linesreturn f"color: {color_hex}; font-weight: 800;"return "color: #6b7280; font-weight: 600;"# Lógica de Activaciónactive_storage = 30 <= pct_objetivo <= 60active_daily = 60 < pct_objetivo <= 95active_balance = pct_objetivo > 95# Tarjeta 1: Almacenajehtml_storage = f"""<div style="{get_card_style(active_storage, '#6366f1')}"><div style="font-size:9px; text-transform:uppercase; {get_text_style(active_storage, '#4f46e5')}">📦 Hibernación</div><div style="font-size:16px; font-weight:800; color:#1f2937;">40-60%</div><div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Almacenaje largo plazo.</div></div>"""# Tarjeta 2: Diariohtml_daily = f"""<div style="{get_card_style(active_daily, '#16a34a')}"><div style="font-size:9px; text-transform:uppercase; {get_text_style(active_daily, '#15803d')}">🔋 Diario</div><div style="font-size:16px; font-weight:800; color:#1f2937;">80-90%</div><div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Longevidad máxima.</div></div>"""# Tarjeta 3: Balanceohtml_balance = f"""<div style="{get_card_style(active_balance, '#ea580c')}"><div style="font-size:9px; text-transform:uppercase; {get_text_style(active_balance, '#c2410c')}">⚖️ Balanceo</div><div style="font-size:16px; font-weight:800; color:#1f2937;">100%</div><div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Mantenimiento (+45min).</div></div>"""# --- AVISO INTELIGENTE DE EXCESO ---header_color = "#2563eb" # Azul por defectoheader_gradient = "linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)"aviso_drenaje = ""if res["estado"] == "DRENAR" and active_storage:header_color = "#dc2626"header_gradient = "linear-gradient(135deg, #dc2626 0%, #991b1b 100%)"aviso_drenaje = """<div style="background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c; padding: 10px; border-radius: 12px; margin-bottom: 16px; font-size: 11px; text-align:center;"><b>⚠️ EXCESO DE CARGA PARA ALMACENAJE</b><br>Tienes más batería de la recomendada para hibernar. Úsala antes de guardarla.</div>"""# --- HTML PRINCIPAL ---html = f"""<div style="font-family: -apple-system, sans-serif; max-width: 450px; margin: auto; color: #111827;"><div style="background: {header_gradient}; color: white; padding: 20px; border-radius: 16px; text-align: center; box-shadow: 0 4px 12px rgba(0,0,0,0.2); margin-bottom: 20px;"><div style="font-size: 10px; font-weight: 700; opacity: 0.9; letter-spacing: 1px;">TIEMPO DE CARGA ({int(temp_trastero)}°C)</div><div style="font-size: 42px; font-weight: 800; line-height: 1.1;">{tiempo_display}</div><div style="margin-top:6px;">6 unmodified lines{html_daily}{html_balance}</div>{aviso_drenaje}"""if drift_pct > 0.015:html += f"""1 unmodified line<div style="font-size:11px; font-weight:800; color:#be123c; margin-bottom:2px;">⚠️ MANTENIMIENTO NECESARIO</div><div style="font-size:11px; color:#9f1239;">Llevas {int(ciclos_drift)} cargas rápidas. Has perdido un <b>{drift_pct*100:.1f}%</b> de capacidad.<br><i>Solución: Carga hoy al 100%.</i></div></div>"""1 unmodified lineif f_clima < 0.98:perdida_clima = int((1.0 - f_clima) * 100)html += f"""<div style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e40af;3 unmodified lines45678910111213141516171819202122232425265 unmodified lines32333435363738394041424344454 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909134 unmodified lines1261271281291301311321331341 unmodified line1361371381391401411421431441451461471481491501511521531541551561575 unmodified lines1631641651661671686 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072086 unmodified lines2152162172182192202211 unmodified line2232242252262272282291 unmodified line2312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263 unmodified linesfrom dataclasses import dataclass, fieldfrom typing import Dict, Tuple, List@dataclass(frozen=True)class BatterySpecs:MODELO: str = 'Husqvarna Hard Cross HC3'MOTOR: str = 'Shimano EP6 (85Nm)'CAPACIDAD_NOMINAL_AH: float = 17.5VOLTAJE_NOMINAL: float = 36.0BUFFER_SEGURIDAD_BMS: float = 0.05PESO_BICI_KG: float = 24.5PESO_EQUIPO_KG: float = 4.5AMPERAJE_CARGADOR: float = 4.0OCV_X: Tuple[float, ...] = (0.0, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0)OCV_Y: Tuple[float, ...] = (31.0, 32.5, 34.0, 35.1, 35.8, 36.3, 36.7, 37.2, 38.0, 39.2, 40.8, 41.5, 42.0)TEMP_X: Tuple[float, ...] = (-10.0, -5.0, 0.0, 5.0, 10.0, 20.0, 40.0)TEMP_Y: Tuple[float, ...] = (0.70, 0.78, 0.85, 0.92, 0.97, 1.00, 1.00)PERFILES_TORQUE: Dict[str, List[float]] = field(default_factory=lambda: {'ECO (Nvl 1)': [27, 5.0, 0.40, 0.96],'Nivel 2': [34, 6.8, 0.50, 0.95],5 unmodified linesSPECS = BatterySpecs()def get_voltage(soc: float) -> float:return float(np.interp(soc, SPECS.OCV_X, SPECS.OCV_Y))def calcular_salud(km: float, ciclos_drift: int) -> dict:ciclos = max(0.0, float(km) / 75.0)degradacion = (0.03 * (1 - np.exp(-0.05 * ciclos))) + (0.0002 * ciclos)soh = max(0.60, min(1.0, 1.0 - degradacion))drift_pct = 0.0if ciclos_drift > 5:x = ciclos_drift - 54 unmodified linesdef factor_clima_ruta(temp: float) -> float:return float(np.interp(temp, SPECS.TEMP_X, SPECS.TEMP_Y))def simulador_master_v53(km, ciclos_drift, inicio, fin, temp_trastero):if temp_trastero < -5 or temp_trastero > 50:return {"estado": "ERROR_TEMP"}salud = calcular_salud(km, ciclos_drift)soh = salud["soh"]if inicio >= fin:return {"estado": "CARGADO","soh": soh,"drift": salud["drift"],"tiempo": 0,"energia": 0,"cap_final_wh": 0}cap_total = SPECS.CAPACIDAD_NOMINAL_AH * sohah_actual = cap_total * (inicio / 100.0)ah_objetivo = cap_total * (fin / 100.0)t_min = 0.0e_wh = 0.0if temp_trastero < 15: f_temp = max(0.15, 0.4 + (0.04 * temp_trastero))elif temp_trastero > 35: f_temp = 0.92else: f_temp = 1.0dt = 1.0 / 60.0while ah_actual < ah_objetivo:soc_now = ah_actual / cap_totalv_now = get_voltage(soc_now)i_target = SPECS.AMPERAJE_CARGADOR * f_tempif v_now >= (SPECS.OCV_Y[-1] - 0.25):diff = v_now - (SPECS.OCV_Y[-1] - 0.6)i_real = i_target * np.exp(-4.5 * max(0, diff))34 unmodified lines"cap_final_wh": ah_actual * SPECS.VOLTAJE_NOMINAL}def generar_interfaz_final(km_val, temp_trastero, temp_ruta, elev_val, peso_piloto, ciclos_drift, inicio_val, fin_val):try:res = simulador_master_v53(float(km_val), int(ciclos_drift),float(inicio_val), float(fin_val), float(temp_trastero))1 unmodified lineif res["estado"] == "ERROR_TEMP":return "<div style='background:#fee2e2; padding:20px; color:#991b1b; text-align:center;'>⛔ <b>ERROR:</b> Temperatura insegura.</div>"drift_pct = res["drift"]soh = res["soh"]pct_objetivo = float(fin_val)if res["estado"] == "CARGADO":pct_calculo = float(inicio_val)cap_bruta = (SPECS.CAPACIDAD_NOMINAL_AH * soh * SPECS.VOLTAJE_NOMINAL) * (pct_calculo/100.0)tiempo_display = "LISTA"energia_display = "0 Wh"else:pct_calculo = float(fin_val)cap_bruta = res['cap_final_wh']h, m = divmod(math.ceil(res["tiempo"]), 60)tiempo_display = f"{h}h {m}m"energia_display = f"+{int(res['energia'])} Wh"cap_util = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS)cap_util_drift = cap_util * (1.0 - drift_pct)wh_perdidos_drift = cap_util * drift_pct5 unmodified linesmasa_total = SPECS.PESO_BICI_KG + float(peso_piloto) + SPECS.PESO_EQUIPO_KGg = 9.81wh_gravedad = (masa_total * g * float(elev_val)) / 3600.0def get_card_style(is_active, color_hex):base = "flex: 1; padding: 10px; border-radius: 12px; margin: 2px;"6 unmodified linesreturn f"color: {color_hex}; font-weight: 800;"return "color: #6b7280; font-weight: 600;"active_storage = 30 <= pct_objetivo <= 60active_daily = 60 < pct_objetivo <= 90active_balance = pct_objetivo > 90html_storage = f"""<div style="{get_card_style(active_storage, '#6366f1')}"><div style="font-size:9px; text-transform:uppercase; {get_text_style(active_storage, '#4f46e5')}">📦 Hibernación</div><div style="font-size:16px; font-weight:800; color:#1f2937;">40-60%</div><div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Para guardar la bici meses.</div></div>"""html_daily = f"""<div style="{get_card_style(active_daily, '#16a34a')}"><div style="font-size:9px; text-transform:uppercase; {get_text_style(active_daily, '#15803d')}">🔋 Diario</div><div style="font-size:16px; font-weight:800; color:#1f2937;">80-90%</div><div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Vida útil máxima. Rutas normales.</div></div>"""html_balance = f"""<div style="{get_card_style(active_balance, '#ea580c')}"><div style="font-size:9px; text-transform:uppercase; {get_text_style(active_balance, '#c2410c')}">⚖️ Balanceo</div><div style="font-size:16px; font-weight:800; color:#1f2937;">100%</div><div style="font-size:9px; color:#4b5563; line-height:1.1; margin-top:3px;">Cada 10 cargas (+45min).</div></div>"""html = f"""<div style="font-family: -apple-system, sans-serif; max-width: 450px; margin: auto; color: #111827;"><div style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 20px; border-radius: 16px; text-align: center; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25); margin-bottom: 20px;"><div style="font-size: 10px; font-weight: 700; opacity: 0.9; letter-spacing: 1px;">TIEMPO DE CARGA ({int(temp_trastero)}°C)</div><div style="font-size: 42px; font-weight: 800; line-height: 1.1;">{tiempo_display}</div><div style="margin-top:6px;">6 unmodified lines{html_daily}{html_balance}</div>"""if drift_pct > 0.015:html += f"""1 unmodified line<div style="font-size:11px; font-weight:800; color:#be123c; margin-bottom:2px;">⚠️ MANTENIMIENTO NECESARIO</div><div style="font-size:11px; color:#9f1239;">Llevas {int(ciclos_drift)} cargas rápidas. Has perdido un <b>{drift_pct*100:.1f}%</b> de capacidad.<br><i>Solución: Selecciona objetivo 100% hoy.</i></div></div>"""1 unmodified lineif f_clima < 0.98:perdida_clima = int((1.0 - f_clima) * 100)html += f"""<div style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e40af; padding: 10px 12px; border-radius: 12px; margin-bottom: 16px; font-size: 11px; display:flex; align-items:center;"><span style="font-size:16px; margin-right:8px;">❄️</span><div><b>Ruta Fría ({float(temp_ruta)}°C):</b> Rendimiento cae un <b>{perdida_clima}%</b>.</div></div>"""html += """<div style="background: white; border: 1px solid #e5e7eb; border-radius: 16px; overflow: hidden;"><div style="padding: 10px 16px; background: #f9fafb; border-bottom: 1px solid #e5e7eb; font-size: 10px; font-weight: 700; color: #6b7280; letter-spacing: 0.5px;">PREDICCIÓN DE AUTONOMÍA REAL</div>"""for modo, specs_modo in SPECS.PERFILES_TORQUE.items():factor_rodadura = masa_total / 105.0consumo_llano = specs_modo[1] * factor_rodadurafactor_asist = specs_modo[2]efic_termica = specs_modo[3]coste_subida = wh_gravedad * factor_asist * (1.0 / efic_termica)wh_rodadura = cap_rueda - coste_subidaif cap_rueda > 0:pct_barra = min(100, max(0, (coste_subida / cap_rueda * 100)))else:pct_barra = 100if wh_rodadura > 0:distancia = int(wh_rodadura / consumo_llano)color = "#15803d" if distancia > 25 else "#b45309" if distancia > 10 else "#b91c1c"html += f"""<div style="padding: 12px 16px; border-bottom: 1px solid #f3f4f6;"><div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;"><div style="font-size: 13px; font-weight: 700; color: #1f2937;">{modo}</div><div style="font-size: 16px; font-weight: 800; color: {color};">{distancia} km</div></div><div style="height: 6px; background: #f3f4f6; border-radius: 3px; overflow:hidden; display:flex;"><div style="width: {pct_barra}%; background: #94a3b8;"></div><div style="flex-grow: 1; background: {color};"></div></div><div style="display:flex; justify-content:space-between; margin-top:2px;"><div style="font-size: 9px; color: #9ca3af;">Subida: -{int(coste_subida)}Wh</div><div style="font-size: 9px; color: #9ca3af;">Rodar</div></div></div>"""else:max_m = int(float(elev_val) * (cap_rueda / coste_subida)) if coste_subida > 0 else 0html += f"""<div style="padding: 12px 16px; border-bottom: 1px solid #f3f4f6; background: #fef2f2;"><div style="display:flex; justify-content:space-between; align-items:center;"><div style="font-size: 13px; font-weight: 700; color: #991b1b;">{modo}</div><div style="font-size: 13px; font-weight: 800; color: #dc2626;">AGOTADA</div></div><div style="font-size: 10px; color: #b91c1c; margin-top:4px;">⚠️ Límite físico: {max_m}m desnivel</div></div>"""html += "</div></div>"return htmlexcept Exception as e:return f"Error: {str(e)}"with gr.Blocks(title="Husqvarna HC3 Fast UI", css="footer {display: none !important;}") as app:gr.Markdown("### ⚡ Husqvarna HC3 | V53 Fast UI")with gr.Row():with gr.Column():inp_km = gr.Number(label="Odómetro Total (km)", value=1500)inp_ciclos = gr.Slider(0, 50, value=20, label="Cargas sin balancear (Drift)", step=1)inp_peso = gr.Slider(50, 100, value=68, label="Tu Peso (kg)", step=1)inp_elev = gr.Slider(0, 3000, value=1000, label="Desnivel Objetivo (m)", step=50)gr.Markdown("---")with gr.Row():inp_t_trastero = gr.Slider(-5, 40, value=20, label="Temp. Trastero (Carga)")inp_t_ruta = gr.Slider(-10, 40, value=5, label="Temp. Exterior (Ruta)")inp_inicio = gr.Slider(0, 100, value=20, step=5, label="% Batería ACTUAL")inp_fin = gr.Slider(5, 100, value=100, step=5, label="% Batería OBJETIVO")btn = gr.Button("CALCULAR ESTRATEGIA", variant="primary")with gr.Column():out = gr.HTML(label="Informe Técnico")btn.click(fn=generar_interfaz_final,inputs=[inp_km, inp_t_trastero, inp_t_ruta, inp_elev, inp_peso, inp_ciclos, inp_inicio, inp_fin],outputs=out)if __name__ == "__main__":app.launch()
app.py+116-103