mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-27 07:46:22 +00:00
fix(bot): read current prediction schema
This commit is contained in:
1 parent
dabadb105b
commit
4933c61c69
2 files changed
+89
-17
No files matched your search
+11
@@ -0,0 +1,11 @@
|
|||||||
|
## Deployment Assumptions - 2026-03-12
|
||||||
|
|
||||||
|
**What went wrong:** I assumed the Telegram bot running on the server might differ from the repository after seeing a schema mismatch between the bot code and the predictions JSON.
|
||||||
|
|
||||||
|
**Root cause:** I inferred deployment drift before exhausting the simpler explanation: the repository bot itself still expected the old JSON schema and would therefore fail even when code and server were synchronized.
|
||||||
|
|
||||||
|
**Prevention rule:** In this repository, when the user states the server and repo are synchronized, treat that as the default assumption and first verify whether the bug is reproducible directly from the checked-in code before attributing it to deployment drift.
|
||||||
|
|
||||||
|
**Example:** `bot/telegram_bot.py` expected top-level station keys plus legacy fields like `station_open_probability`, while `scripts/collect_daily_data.py` writes predictions under `stations` with fields such as `open_probability` and `km_open`.
|
||||||
|
|
||||||
|
**Files affected:** `bot/telegram_bot.py`, `scripts/collect_daily_data.py`
|
||||||
+78
-17
@@ -19,6 +19,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from telegram import Update
|
from telegram import Update
|
||||||
from telegram.constants import ParseMode
|
from telegram.constants import ParseMode
|
||||||
@@ -112,12 +113,37 @@ def _open_label(probability: float) -> str:
|
|||||||
return "Cerrada"
|
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.
|
"""Build the Telegram HTML message for a single station prediction.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
station_key: One of 'pajares', 'sanisidro', 'fuentes'.
|
station_key: One of 'pajares', 'sanisidro', 'fuentes'.
|
||||||
prediction: Sub-dictionary for this station from predictions_latest.json.
|
prediction: Sub-dictionary for this station from predictions_latest.json.
|
||||||
|
prediction_date: ISO date string for the prediction target day.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Formatted string ready to be sent with ParseMode.HTML.
|
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"]
|
station_name = meta["name"]
|
||||||
max_km = meta["max_km"]
|
max_km = meta["max_km"]
|
||||||
|
|
||||||
open_prob: float = prediction.get("station_open_probability", 0.0)
|
open_prob = float(
|
||||||
km_open: float = prediction.get("km_open_prediction", 0.0)
|
prediction.get(
|
||||||
crowd_raw: str = prediction.get("crowd_level_prediction", "unknown")
|
"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_summary = prediction.get("weather_summary")
|
||||||
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")
|
|
||||||
|
|
||||||
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_pct = int(round(open_prob * 100))
|
||||||
open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)"
|
open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)"
|
||||||
@@ -146,7 +186,18 @@ def format_station_prediction(station_key: str, prediction: dict) -> str:
|
|||||||
crowd_str = _crowd_label(crowd_raw)
|
crowd_str = _crowd_label(crowd_raw)
|
||||||
km_str = f"{km_open:.1f} / {max_km:.1f}"
|
km_str = f"{km_open:.1f} / {max_km:.1f}"
|
||||||
|
|
||||||
# Build weather block only with available data.
|
weather_block = ""
|
||||||
|
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] = []
|
weather_lines: list[str] = []
|
||||||
if temp_min is not None and temp_max is not None:
|
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")
|
weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C")
|
||||||
@@ -163,17 +214,22 @@ def format_station_prediction(station_key: str, prediction: dict) -> str:
|
|||||||
elif wind_speed is not None:
|
elif wind_speed is not None:
|
||||||
weather_lines.append(f"Viento: {wind_speed:.0f} km/h")
|
weather_lines.append(f"Viento: {wind_speed:.0f} km/h")
|
||||||
|
|
||||||
weather_block = ""
|
|
||||||
if weather_lines:
|
if weather_lines:
|
||||||
weather_block = "\n<b>Tiempo previsto:</b>\n" + "\n".join(weather_lines) + "\n"
|
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 = (
|
message = (
|
||||||
f"<b>{station_name} - Prediccion para manana</b>\n"
|
f"<b>{_message_title(station_name, prediction_date)}</b>\n"
|
||||||
f"\n"
|
f"\n"
|
||||||
f"Estado: {open_str}\n"
|
f"Estado: {open_str}\n"
|
||||||
f"Km esquiables: {km_str}\n"
|
f"Km esquiables: {km_str}\n"
|
||||||
f"Nivel de afluencia: {crowd_str}\n"
|
f"Nivel de afluencia: {crowd_str}\n"
|
||||||
f"{weather_block}"
|
f"{weather_block}"
|
||||||
|
f"{reasons_block}"
|
||||||
f"\n<i>Fuente: {source}</i>"
|
f"\n<i>Fuente: {source}</i>"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -251,7 +307,8 @@ async def _send_station(
|
|||||||
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
||||||
return
|
return
|
||||||
|
|
||||||
station_pred = predictions.get(station_key)
|
station_predictions = _extract_station_predictions(predictions)
|
||||||
|
station_pred = station_predictions.get(station_key)
|
||||||
if not station_pred:
|
if not station_pred:
|
||||||
logger.warning("No prediction entry for station '%s'", station_key)
|
logger.warning("No prediction entry for station '%s'", station_key)
|
||||||
text = _no_prediction_message(station_name)
|
text = _no_prediction_message(station_name)
|
||||||
@@ -259,7 +316,11 @@ async def _send_station(
|
|||||||
return
|
return
|
||||||
|
|
||||||
try:
|
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
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.exception("Error formatting prediction for '%s': %s", station_key, exc)
|
logger.exception("Error formatting prediction for '%s': %s", station_key, exc)
|
||||||
text = _no_prediction_message(station_name)
|
text = _no_prediction_message(station_name)
|
||||||
|
|||||||
Reference in new issue
Block a user