Update app.py
Browse files8 unmodified lines910111213141516171819202122232425262728293031323334353637383940416 unmodified lines484950515253545 unmodified lines60616263646566676869707172735 unmodified lines798081828384855 unmodified lines9192939495969728 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232244 unmodified lines2292302312322332342352362372382392402416 unmodified lines24824925025125225325425525625725815 unmodified lines27427527627727827928028128228328428510 unmodified lines2962972982993003013023033043053068 unmodified lines3153163173183193203213223233243253263278 unmodified lines@dataclass(frozen=True)class BatterySpecs:# --- IDENTIDAD ---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ÍSICA USUARIO ---PESO_BICI_KG: float = 24.5PESO_EQUIPO_KG: float = 4.5# --- CARGADOR ---AMPERAJE_CARGADOR: float = 4.0# --- MATRICES DE DATOS (LOOKUP TABLES) ---# Curva de Voltaje OCV (NMC 21700)OCV_CURVE_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_CURVE_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)# Curva de Penalización Térmica (Temp °C -> Factor Eficiencia 0-1)TEMP_CURVE_X: Tuple[float, ...] = (-10.0, -5.0, 0.0, 5.0, 10.0, 20.0, 40.0)TEMP_CURVE_Y: Tuple[float, ...] = (0.70, 0.78, 0.85, 0.92, 0.97, 1.00, 1.00)# --- PERFILES DE RENDIMIENTO ---# [0]: Torque, [1]: Wh/km, [2]: Asistencia, [3]: Eficiencia TérmicaPERFILES_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],6 unmodified linesSPECS = BatterySpecs()# ==============================================================================# 2. KERNEL DE SIMULACIÓN (ROBUSTO)# ==============================================================================def get_voltage(soc: float) -> float:5 unmodified linesreturn max(0.60, min(1.0, 1.0 - degradacion))def factor_clima_ruta_continuo(temp: float) -> float:"""Interpolación lineal segura usando datos de BatterySpecs."""return float(np.interp(temp, SPECS.TEMP_CURVE_X, SPECS.TEMP_CURVE_Y))def simulador_carga_v43(km, inicio, fin, temp_trastero):# BLINDAJE: Si inicio >= fin, la batería ya cumple.if inicio >= fin:return {"estado": "CARGADO", "soh": calcular_soh(km)}if temp_trastero < -5 or temp_trastero > 50:return {"estado": "ERROR_TEMP"}5 unmodified linest_min = 0.0e_wh = 0.0# Arrheniusif 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.05 unmodified linesv_t0 = get_voltage(soc_t0)i_target = SPECS.AMPERAJE_CARGADOR * f_temp# CC/CVif v_t0 >= (42.0 - 0.2):diff = v_t0 - (42.0 - 0.6)i_real = i_target * np.exp(-3.5 * max(0, diff))28 unmodified lines}# ==============================================================================# 3. INTERFAZ VISUAL FINAL (V43)# ==============================================================================def generar_vista_final(km_val, temp_trastero, temp_ruta, elev_val, peso_piloto, inicio_val, fin_val):try:# 1. Simulaciónres = simulador_carga_v43(float(km_val), float(inicio_val), float(fin_val), float(temp_trastero))if res["estado"] == "ERROR_TEMP":return "<div style='background:#fee2e2; padding:20px; color:#991b1b; text-align:center; border-radius:12px;'>⛔ <b>ERROR:</b> Trastero a temperatura insegura.</div>"# 2. Datos Energíapct_objetivo_real = float(fin_val)if res["estado"] == "CARGADO":soh = res["soh"]# Si ya está cargada por encima del objetivo, usamos el nivel actual para el cálculo de rangopct_calculo = float(inicio_val)cap_bruta = (SPECS.CAPACIDAD_NOMINAL_AH * soh * SPECS.VOLTAJE_NOMINAL) * (pct_calculo/100.0)tiempo_txt = "LISTA"energia_txt = "0 Wh"else:pct_calculo = float(fin_val)cap_bruta = res['cap_final_wh']h, m = divmod(int(res["tiempo"]), 60)tiempo_txt = f"{h}h {m}m"energia_txt = f"+{res['energia']:.0f} Wh"# 3. Física de Ruta (Descarga)cap_util_teorica = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS)f_clima = factor_clima_ruta_continuo(float(temp_ruta))cap_util_real = cap_util_teorica * f_climaif cap_util_real < 0: cap_util_real = 0masa_total = SPECS.PESO_BICI_KG + float(peso_piloto) + SPECS.PESO_EQUIPO_KGg = 9.81julios_totales = masa_total * g * float(elev_val)wh_gravedad = julios_totales / 3600.0# 4. Asesor Inteligente (Siempre activo)mensaje_asesor = ""bg_asesor = "white"perfil_trail = SPECS.PERFILES_TORQUE['TRAIL (Nvl 3)']wh_km_trail = perfil_trail[1]asist_trail = perfil_trail[2]efic_trail = perfil_trail[3]distancia_ref = max(15, float(elev_val) / 35.0)consumo_ref_rodar = wh_km_trail * (masa_total/105.0)coste_subida_ref = wh_gravedad * asist_trail * (1.0 / efic_trail)wh_necesarios = coste_subida_ref + (distancia_ref * consumo_ref_rodar)cap_total_100 = SPECS.CAPACIDAD_NOMINAL_AH * res['soh'] * SPECS.VOLTAJE_NOMINAL# Evitar división por cero si Soh o Capacidad fallan (improbable pero seguro)if cap_total_100 > 0:pct_necesario = (wh_necesarios / (cap_total_100 * f_clima * 0.95)) * 100else:pct_necesario = 100pct_recomendado = min(100, pct_necesario + 15)# Lógica de aviso: Comparamos el objetivo del usuario con lo necesarioif pct_calculo > 90 and pct_recomendado < 80:mensaje_asesor = f"💡 <b>Smart Charge:</b> Para {int(float(elev_val))}m desnivel, con el <b>{int(pct_recomendado)}%</b> es suficiente. Cuidarás la batería."bg_asesor = "#f0fdf4; border: 1px solid #86efac; color: #166534"elif pct_calculo < pct_necesario:mensaje_asesor = f"⚠️ <b>Riesgo:</b> Ruta exigente. Necesitas mínimo <b>{int(pct_necesario)}%</b> para ir tranquilo en Trail."bg_asesor = "#fef2f2; border: 1px solid #fca5a5; color: #991b1b"# --- HTML BUILDER ---html = f"""<div style="font-family: -apple-system, sans-serif; max-width: 450px; margin: auto; color: #1f2937;"><div style="background: linear-gradient(135deg, #4f46e5 0%, #4338ca 100%); color: white; padding: 24px; border-radius: 20px; text-align: center; box-shadow: 0 10px 25px rgba(67, 56, 202, 0.3); margin-bottom: 16px;"><div style="font-size: 11px; font-weight: 700; opacity: 0.8; letter-spacing: 1px;">TIEMPO DE CARGA ({int(temp_trastero)}°C)</div><div style="font-size: 48px; font-weight: 800; line-height: 1;">{tiempo_txt}</div><div style="margin-top:8px;"><span style="background: rgba(255,255,255,0.15); font-size: 13px; padding: 4px 12px; border-radius: 99px;">⚡ {energia_txt}</span></div></div>{f'<div style="background: {bg_asesor}; padding: 12px 16px; border-radius: 12px; font-size: 12px; margin-bottom: 16px; line-height: 1.4;">{mensaje_asesor}</div>' if mensaje_asesor else ''}<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px;"><div style="background: #f8fafc; padding: 12px; border-radius: 14px; border: 1px solid #e2e8f0; text-align:center;"><div style="font-size: 10px; color: #64748b; font-weight: 700;">PESO TOTAL</div><div style="font-size: 16px; font-weight: 800;">{masa_total:.1f} kg</div></div><div style="background: #f8fafc; padding: 12px; border-radius: 14px; border: 1px solid #e2e8f0; text-align:center;"><div style="font-size: 10px; color: #64748b; font-weight: 700;">CLIMA RUTA</div><div style="font-size: 16px; font-weight: 800;">{int(float(temp_ruta))}°C</div></div></div>4 unmodified lineshtml += f"""<div style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e40af; padding: 10px 15px; border-radius: 12px; margin-bottom: 16px; font-size: 12px; display:flex; align-items:center;"><span style="font-size:18px; margin-right:10px;">❄️</span><div><b>Penalización Térmica:</b> -{perdida}% de autonomía por frío.</div></div>"""html += """<div style="background: white; border: 1px solid #e2e8f0; border-radius: 20px; overflow: hidden;"><div style="padding: 12px 20px; background: #f1f5f9; border-bottom: 1px solid #e2e8f0; font-size: 11px; font-weight: 700; color: #64748b; letter-spacing: 0.5px;">AUTONOMÍA ESTIMADA</div>"""6 unmodified linescoste_g = wh_gravedad * factor_asist * (1.0 / efic_termica)wh_rodadura = cap_util_real - coste_g# Barra visual segura (Evita valores > 100 o < 0)if cap_util_real > 0:pct_g = min(100, max(0, (coste_g / cap_util_real * 100)))else:pct_g = 100 # Si no hay batería, todo es coste (visualmente)if wh_rodadura > 0:distancia = int(wh_rodadura / consumo_llano)15 unmodified lines</div></div>"""else:# BLINDAJE DIVISION ZERO V43if coste_g > 0:max_m = int(float(elev_val) * (cap_util_real / coste_g))else:max_m = 0 # Caso imposible físicamente si wh_rodadura < 0, pero por seguridadhtml += f"""<div style="padding: 14px 20px; border-bottom: 1px solid #f1f5f9; background: #fef2f2;"><div style="display:flex; justify-content:space-between; align-items:center;">10 unmodified linesreturn f"Error: {str(e)}"# ==============================================================================# 4. LANZAMIENTO V43 (ZERO-BUG)# ==============================================================================with gr.Blocks(title="Husqvarna FINAL V43", css="footer {display: none !important;}") as app:gr.Markdown("### ⚡ Husqvarna HC3 | Final Zero-Bug V43")with gr.Row():with gr.Column():8 unmodified linesinp_inicio = gr.Slider(0, 99, value=20, label="% Batería ACTUAL")inp_fin = gr.Slider(1, 100, value=100, label="% Batería OBJETIVO")btn = gr.Button("ANALIZAR RUTA", variant="primary")with gr.Column():out = gr.HTML(label="Análisis")btn.click(fn=generar_vista_final,inputs=[inp_km, inp_t_trastero, inp_t_ruta, inp_elev, inp_peso, inp_inicio, inp_fin],outputs=out)8 unmodified lines9101112131415161718192021222324252627282930316 unmodified lines383940414243445 unmodified lines50515253545556575859605 unmodified lines6667686970715 unmodified lines7778798081828328 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032044 unmodified lines2092102112122132142152162172182192202216 unmodified lines22822923023123223323423523623723815 unmodified lines25425525625725825926026126226310 unmodified lines2742752762772782792802812822832848 unmodified lines2932942952962972982993003013023033043058 unmodified lines@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.0# Lookup TablesOCV_CURVE_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_CURVE_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_CURVE_X: Tuple[float, ...] = (-10.0, -5.0, 0.0, 5.0, 10.0, 20.0, 40.0)TEMP_CURVE_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],6 unmodified linesSPECS = BatterySpecs()# ==============================================================================# 2. MOTOR DE SIMULACIÓN V44# ==============================================================================def get_voltage(soc: float) -> float:5 unmodified linesreturn max(0.60, min(1.0, 1.0 - degradacion))def factor_clima_ruta_continuo(temp: float) -> float:return float(np.interp(temp, SPECS.TEMP_CURVE_X, SPECS.TEMP_CURVE_Y))def simulador_carga_v44(km, inicio, fin, temp_trastero):if inicio >= fin:return {"estado": "CARGADO", "soh": calcular_soh(km)}if temp_trastero < -5 or temp_trastero > 50:return {"estado": "ERROR_TEMP"}5 unmodified linest_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.05 unmodified linesv_t0 = get_voltage(soc_t0)i_target = SPECS.AMPERAJE_CARGADOR * f_temp# CC/CV Logicif v_t0 >= (42.0 - 0.2):diff = v_t0 - (42.0 - 0.6)i_real = i_target * np.exp(-3.5 * max(0, diff))28 unmodified lines}# ==============================================================================# 3. INTERFAZ VISUAL V44 (MANTENIMIENTO BMS ACTIVO)# ==============================================================================def generar_vista_lifecycle(km_val, temp_trastero, temp_ruta, elev_val, peso_piloto, inicio_val, fin_val):try:res = simulador_carga_v44(float(km_val), float(inicio_val), float(fin_val), float(temp_trastero))if res["estado"] == "ERROR_TEMP":return "<div style='background:#fee2e2; padding:20px; color:#991b1b; text-align:center;'>⛔ <b>ERROR:</b> Trastero inseguro.</div>"# Datos Basepct_objetivo = float(fin_val)if res["estado"] == "CARGADO":soh = res["soh"]cap_bruta = (SPECS.CAPACIDAD_NOMINAL_AH * soh * SPECS.VOLTAJE_NOMINAL) * (float(inicio_val)/100.0)tiempo_txt = "LISTA"energia_txt = "0 Wh"else:cap_bruta = res['cap_final_wh']h, m = divmod(int(res["tiempo"]), 60)tiempo_txt = f"{h}h {m}m"energia_txt = f"+{res['energia']:.0f} Wh"# Física Rutacap_util = cap_bruta * (1.0 - SPECS.BUFFER_SEGURIDAD_BMS)f_clima = factor_clima_ruta_continuo(float(temp_ruta))cap_util_real = cap_util * f_climaif cap_util_real < 0: cap_util_real = 0masa_total = SPECS.PESO_BICI_KG + float(peso_piloto) + SPECS.PESO_EQUIPO_KGg = 9.81wh_gravedad = (masa_total * g * float(elev_val)) / 3600.0# --- PROTOCOLO DE MANTENIMIENTO BMS (NUEVO EN V44) ---html_mantenimiento = ""if pct_objetivo >= 99:# CASO 1: CARGA AL 100% -> PROTOCOLO DE BALANCEOhtml_mantenimiento = """<div style="background: #fff7ed; border: 1px solid #fdba74; padding: 12px 16px; border-radius: 14px; margin-bottom: 16px;"><div style="display:flex; align-items:center; margin-bottom:6px;"><span style="font-size:20px; margin-right:10px;">⚖️</span><div style="font-size:12px; font-weight:800; color:#9a3412; text-transform:uppercase;">Protocolo de Balanceo Activo</div></div><div style="font-size:12px; color:#c2410c; line-height:1.4;">Al llegar al 100%, <b>no desconectes</b>. Deja el cargador <b>45 minutos extra</b> con la luz verde.<br><span style="opacity:0.8; font-size:11px;">(Esto iguala el voltaje de las 40 celdas internas).</span></div></div>"""else:# CASO 2: CARGA PARCIAL -> RECORDATORIO CALIBRACIÓNhtml_mantenimiento = """<div style="background: #f0fdf4; border: 1px solid #86efac; padding: 12px 16px; border-radius: 14px; margin-bottom: 16px;"><div style="display:flex; align-items:center; margin-bottom:6px;"><span style="font-size:20px; margin-right:10px;">🛡️</span><div style="font-size:12px; font-weight:800; color:#166534; text-transform:uppercase;">Modo Longevidad Activo</div></div><div style="font-size:12px; color:#15803d; line-height:1.4;">Cargar al 80-90% triplica la vida de la batería.<br><b>⚠️ Importante:</b> Realiza una carga al 100% (con balanceo) <b>cada 5-10 ciclos</b> para recalibrar el BMS.</div></div>"""# --- HTML PRINCIPAL ---html = f"""<div style="font-family: -apple-system, sans-serif; max-width: 450px; margin: auto; color: #1f2937;"><div style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 24px; border-radius: 20px; text-align: center; box-shadow: 0 10px 20px rgba(37,99,235,0.3); margin-bottom: 16px;"><div style="font-size: 11px; font-weight: 700; opacity: 0.8; letter-spacing: 1px;">TIEMPO DE CARGA ({int(temp_trastero)}°C)</div><div style="font-size: 48px; font-weight: 800; line-height: 1;">{tiempo_txt}</div><div style="margin-top:8px;"><span style="background: rgba(255,255,255,0.2); font-size: 13px; padding: 4px 12px; border-radius: 99px;">⚡ {energia_txt}</span></div></div>{html_mantenimiento}<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px;"><div style="background: #f8fafc; padding: 12px; border-radius: 14px; border: 1px solid #e2e8f0; text-align:center;"><div style="font-size: 10px; color: #64748b; font-weight: 700;">PESO SISTEMA</div><div style="font-size: 16px; font-weight: 800;">{masa_total:.1f} kg</div></div><div style="background: #f8fafc; padding: 12px; border-radius: 14px; border: 1px solid #e2e8f0; text-align:center;"><div style="font-size: 10px; color: #64748b; font-weight: 700;">TEMP RUTA</div><div style="font-size: 16px; font-weight: 800;">{int(float(temp_ruta))}°C</div></div></div>4 unmodified lineshtml += f"""<div style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e40af; padding: 10px 15px; border-radius: 12px; margin-bottom: 16px; font-size: 12px; display:flex; align-items:center;"><span style="font-size:18px; margin-right:10px;">❄️</span><div><b>Frío en Ruta:</b> -{perdida}% de autonomía (Voltage Sag).</div></div>"""html += """<div style="background: white; border: 1px solid #e2e8f0; border-radius: 20px; overflow: hidden;"><div style="padding: 12px 20px; background: #f1f5f9; border-bottom: 1px solid #e2e8f0; font-size: 11px; font-weight: 700; color: #64748b; letter-spacing: 0.5px;">PREDICCIÓN DE AUTONOMÍA</div>"""6 unmodified linescoste_g = wh_gravedad * factor_asist * (1.0 / efic_termica)wh_rodadura = cap_util_real - coste_g# Barra visualif cap_util_real > 0:pct_g = min(100, max(0, (coste_g / cap_util_real * 100)))else:pct_g = 100if wh_rodadura > 0:distancia = int(wh_rodadura / consumo_llano)15 unmodified lines</div></div>"""else:if coste_g > 0:max_m = int(float(elev_val) * (cap_util_real / coste_g))else:max_m = 0html += f"""<div style="padding: 14px 20px; border-bottom: 1px solid #f1f5f9; background: #fef2f2;"><div style="display:flex; justify-content:space-between; align-items:center;">10 unmodified linesreturn f"Error: {str(e)}"# ==============================================================================# 4. LANZAMIENTO V44# ==============================================================================with gr.Blocks(title="Husqvarna Lifecycle V44", css="footer {display: none !important;}") as app:gr.Markdown("### ⚡ Husqvarna HC3 | Lifecycle V44")with gr.Row():with gr.Column():8 unmodified linesinp_inicio = gr.Slider(0, 99, value=20, label="% Batería ACTUAL")inp_fin = gr.Slider(1, 100, value=100, label="% Batería OBJETIVO")btn = gr.Button("ANALIZAR CICLO", variant="primary")with gr.Column():out = gr.HTML(label="Dashboard")btn.click(fn=generar_vista_lifecycle,inputs=[inp_km, inp_t_trastero, inp_t_ruta, inp_elev, inp_peso, inp_inicio, inp_fin],outputs=out)
app.py+62-84