mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
fix(bot): read current prediction schema
This commit is contained in:
1 parent
dabadb105b
commit
4933c61c69
2 files changed
+106
-34
No files matched your search
+95
-34
@@ -19,6 +19,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from telegram import Update
|
||||
from telegram.constants import ParseMode
|
||||
@@ -112,12 +113,37 @@ def _open_label(probability: float) -> str:
|
||||
return "Cerrada"
|
||||
|
||||
|
||||
def format_station_prediction(station_key: str, prediction: dict) -> str:
|
||||
def _extract_station_predictions(payload: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"""Return the per-station prediction map from either supported schema."""
|
||||
stations = payload.get("stations")
|
||||
if isinstance(stations, dict):
|
||||
return stations
|
||||
|
||||
return {
|
||||
key: value
|
||||
for key, value in payload.items()
|
||||
if key in STATIONS and isinstance(value, dict)
|
||||
}
|
||||
|
||||
|
||||
def _message_title(station_name: str, prediction_date: str | None) -> str:
|
||||
"""Return the station header including the prediction date when known."""
|
||||
if prediction_date:
|
||||
return f"{station_name} - Prediccion para {prediction_date}"
|
||||
return f"{station_name} - Prediccion para manana"
|
||||
|
||||
|
||||
def format_station_prediction(
|
||||
station_key: str,
|
||||
prediction: dict[str, Any],
|
||||
prediction_date: str | None = None,
|
||||
) -> str:
|
||||
"""Build the Telegram HTML message for a single station prediction.
|
||||
|
||||
Args:
|
||||
station_key: One of 'pajares', 'sanisidro', 'fuentes'.
|
||||
prediction: Sub-dictionary for this station from predictions_latest.json.
|
||||
prediction_date: ISO date string for the prediction target day.
|
||||
|
||||
Returns:
|
||||
Formatted string ready to be sent with ParseMode.HTML.
|
||||
@@ -126,19 +152,33 @@ def format_station_prediction(station_key: str, prediction: dict) -> str:
|
||||
station_name = meta["name"]
|
||||
max_km = meta["max_km"]
|
||||
|
||||
open_prob: float = prediction.get("station_open_probability", 0.0)
|
||||
km_open: float = prediction.get("km_open_prediction", 0.0)
|
||||
crowd_raw: str = prediction.get("crowd_level_prediction", "unknown")
|
||||
open_prob = float(
|
||||
prediction.get(
|
||||
"open_probability",
|
||||
prediction.get("station_open_probability", 0.0),
|
||||
)
|
||||
)
|
||||
km_open = float(
|
||||
prediction.get(
|
||||
"km_open",
|
||||
prediction.get("km_open_prediction", 0.0),
|
||||
)
|
||||
)
|
||||
crowd_raw = str(
|
||||
prediction.get(
|
||||
"crowd_level",
|
||||
prediction.get("crowd_level_prediction", "unknown"),
|
||||
)
|
||||
)
|
||||
|
||||
# Weather sub-dict is optional; provide sensible defaults.
|
||||
weather: dict = prediction.get("weather_forecast", {})
|
||||
temp_min: float | None = weather.get("temperature_min")
|
||||
temp_max: float | None = weather.get("temperature_max")
|
||||
snowfall: float | None = weather.get("snowfall_cm")
|
||||
wind_speed: float | None = weather.get("wind_speed_kmh")
|
||||
wind_gust: float | None = weather.get("wind_gust_kmh")
|
||||
weather_summary = prediction.get("weather_summary")
|
||||
|
||||
source: str = prediction.get("source", "prediccion hibrida (reglas + ML)")
|
||||
source = str(
|
||||
prediction.get(
|
||||
"prediction_source",
|
||||
prediction.get("source", "prediccion hibrida (reglas + ML)"),
|
||||
)
|
||||
)
|
||||
|
||||
open_pct = int(round(open_prob * 100))
|
||||
open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)"
|
||||
@@ -146,34 +186,50 @@ def format_station_prediction(station_key: str, prediction: dict) -> str:
|
||||
crowd_str = _crowd_label(crowd_raw)
|
||||
km_str = f"{km_open:.1f} / {max_km:.1f}"
|
||||
|
||||
# Build weather block only with available data.
|
||||
weather_lines: list[str] = []
|
||||
if temp_min is not None and temp_max is not None:
|
||||
weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C")
|
||||
elif temp_max is not None:
|
||||
weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C")
|
||||
|
||||
if snowfall is not None:
|
||||
weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos")
|
||||
|
||||
if wind_speed is not None and wind_gust is not None:
|
||||
weather_lines.append(
|
||||
f"Viento: {wind_speed:.0f} km/h (rachas {wind_gust:.0f} km/h)"
|
||||
)
|
||||
elif wind_speed is not None:
|
||||
weather_lines.append(f"Viento: {wind_speed:.0f} km/h")
|
||||
|
||||
weather_block = ""
|
||||
if weather_lines:
|
||||
weather_block = "\n<b>Tiempo previsto:</b>\n" + "\n".join(weather_lines) + "\n"
|
||||
if weather_summary:
|
||||
weather_block = f"\n<b>Tiempo previsto:</b>\n{weather_summary}\n"
|
||||
else:
|
||||
# Legacy schema support: weather as structured sub-dict.
|
||||
weather: dict[str, Any] = prediction.get("weather_forecast", {})
|
||||
temp_min = weather.get("temperature_min")
|
||||
temp_max = weather.get("temperature_max")
|
||||
snowfall = weather.get("snowfall_cm")
|
||||
wind_speed = weather.get("wind_speed_kmh")
|
||||
wind_gust = weather.get("wind_gust_kmh")
|
||||
|
||||
weather_lines: list[str] = []
|
||||
if temp_min is not None and temp_max is not None:
|
||||
weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C")
|
||||
elif temp_max is not None:
|
||||
weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C")
|
||||
|
||||
if snowfall is not None:
|
||||
weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos")
|
||||
|
||||
if wind_speed is not None and wind_gust is not None:
|
||||
weather_lines.append(
|
||||
f"Viento: {wind_speed:.0f} km/h (rachas {wind_gust:.0f} km/h)"
|
||||
)
|
||||
elif wind_speed is not None:
|
||||
weather_lines.append(f"Viento: {wind_speed:.0f} km/h")
|
||||
|
||||
if weather_lines:
|
||||
weather_block = "\n<b>Tiempo previsto:</b>\n" + "\n".join(weather_lines) + "\n"
|
||||
|
||||
overrides = prediction.get("rule_overrides") or []
|
||||
reasons_block = ""
|
||||
if overrides:
|
||||
reasons_block = "\n<b>Notas:</b>\n" + "\n".join(f"• {reason}" for reason in overrides) + "\n"
|
||||
|
||||
message = (
|
||||
f"<b>{station_name} - Prediccion para manana</b>\n"
|
||||
f"<b>{_message_title(station_name, prediction_date)}</b>\n"
|
||||
f"\n"
|
||||
f"Estado: {open_str}\n"
|
||||
f"Km esquiables: {km_str}\n"
|
||||
f"Nivel de afluencia: {crowd_str}\n"
|
||||
f"{weather_block}"
|
||||
f"{reasons_block}"
|
||||
f"\n<i>Fuente: {source}</i>"
|
||||
)
|
||||
|
||||
@@ -251,7 +307,8 @@ async def _send_station(
|
||||
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
||||
return
|
||||
|
||||
station_pred = predictions.get(station_key)
|
||||
station_predictions = _extract_station_predictions(predictions)
|
||||
station_pred = station_predictions.get(station_key)
|
||||
if not station_pred:
|
||||
logger.warning("No prediction entry for station '%s'", station_key)
|
||||
text = _no_prediction_message(station_name)
|
||||
@@ -259,7 +316,11 @@ async def _send_station(
|
||||
return
|
||||
|
||||
try:
|
||||
text = format_station_prediction(station_key, station_pred)
|
||||
text = format_station_prediction(
|
||||
station_key,
|
||||
station_pred,
|
||||
predictions.get("prediction_date"),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("Error formatting prediction for '%s': %s", station_key, exc)
|
||||
text = _no_prediction_message(station_name)
|
||||
|
||||
Reference in new issue
Block a user