mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
merge: sqlite migration
# Conflicts: # bot/telegram_bot.py
This commit is contained in:
commit
c486c585d0
17 files changed
+1207
-686
No files matched your search
+23
-84
@@ -6,8 +6,7 @@ Serves next-day predictions for three ski stations in northern Spain:
|
||||
- San Isidro (/sanisidro)
|
||||
- Fuentes de Invierno (/fuentes)
|
||||
|
||||
The bot reads predictions from the JSON file generated by the daily
|
||||
pipeline at data/processed/predictions_latest.json.
|
||||
The bot reads the latest published prediction run from SQLite.
|
||||
|
||||
Usage:
|
||||
Set the TELEGRAM_BOT_TOKEN environment variable and run:
|
||||
@@ -15,16 +14,16 @@ Usage:
|
||||
or call main() directly.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from telegram import Update
|
||||
from telegram.constants import ParseMode
|
||||
from telegram.ext import Application, CommandHandler, ContextTypes
|
||||
|
||||
from storage import PUBLISHED_RUN_KIND, SQLiteStore
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Logging
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -35,14 +34,6 @@ logging.basicConfig(
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Resolve project root relative to this file regardless of cwd.
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
PREDICTIONS_FILE = _PROJECT_ROOT / "data" / "processed" / "predictions_latest.json"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Station metadata (mirrors config/stations.yaml without adding a runtime
|
||||
# dependency on pyyaml inside the bot module itself).
|
||||
@@ -69,23 +60,22 @@ STATIONS = {
|
||||
|
||||
|
||||
def load_predictions() -> dict | None:
|
||||
"""Load the latest predictions from the JSON file produced by the pipeline.
|
||||
"""Load the latest published predictions from SQLite.
|
||||
|
||||
Returns the parsed dictionary on success, or None if the file is missing
|
||||
or cannot be decoded.
|
||||
Returns the parsed dictionary on success, or None if no published
|
||||
prediction run exists yet.
|
||||
"""
|
||||
if not PREDICTIONS_FILE.exists():
|
||||
logger.warning("Archivo de predicciones no encontrado: %s", PREDICTIONS_FILE)
|
||||
store = SQLiteStore()
|
||||
data = store.load_latest_predictions(run_kind=PUBLISHED_RUN_KIND)
|
||||
if data is None:
|
||||
logger.warning(
|
||||
"No hay ninguna predicción publicada en SQLite (%s)",
|
||||
store.db_path,
|
||||
)
|
||||
return None
|
||||
|
||||
try:
|
||||
with PREDICTIONS_FILE.open(encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
logger.info("Predicciones cargadas desde %s", PREDICTIONS_FILE)
|
||||
return data
|
||||
except json.JSONDecodeError as exc:
|
||||
logger.error("Error al decodificar el archivo de predicciones: %s", exc)
|
||||
return None
|
||||
logger.info("Predicciones cargadas desde SQLite (%s)", store.db_path)
|
||||
return data
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -114,16 +104,11 @@ def _open_label(probability: float) -> str:
|
||||
|
||||
|
||||
def _extract_station_predictions(payload: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"""Return the per-station prediction map from either supported schema."""
|
||||
"""Return the per-station prediction map."""
|
||||
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)
|
||||
}
|
||||
return {}
|
||||
|
||||
|
||||
def _message_title(station_name: str, prediction_date: str | None) -> str:
|
||||
@@ -142,7 +127,7 @@ def format_station_prediction(
|
||||
|
||||
Args:
|
||||
station_key: One of 'pajares', 'sanisidro', 'fuentes'.
|
||||
prediction: Sub-dictionary for this station from predictions_latest.json.
|
||||
prediction: Sub-dictionary for this station from SQLite.
|
||||
prediction_date: ISO date string for the prediction target day.
|
||||
|
||||
Returns:
|
||||
@@ -152,32 +137,13 @@ def format_station_prediction(
|
||||
station_name = meta["name"]
|
||||
max_km = meta["max_km"]
|
||||
|
||||
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"),
|
||||
)
|
||||
)
|
||||
open_prob = float(prediction.get("open_probability", 0.0))
|
||||
km_open = float(prediction.get("km_open", 0.0))
|
||||
crowd_raw = str(prediction.get("crowd_level", "unknown"))
|
||||
|
||||
weather_summary = prediction.get("weather_summary")
|
||||
|
||||
source = str(
|
||||
prediction.get(
|
||||
"prediction_source",
|
||||
prediction.get("source", "predicción híbrida (reglas + ML)"),
|
||||
)
|
||||
prediction.get("prediction_source", "predicción híbrida (reglas + ML)")
|
||||
)
|
||||
|
||||
open_pct = int(round(open_prob * 100))
|
||||
@@ -189,33 +155,6 @@ def format_station_prediction(
|
||||
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] = []
|
||||
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 máxima: {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 = ""
|
||||
@@ -247,7 +186,7 @@ def _no_prediction_message(station_name: str) -> str:
|
||||
|
||||
|
||||
def _unavailable_message() -> str:
|
||||
"""Return a message when the predictions file cannot be loaded at all."""
|
||||
"""Return a message when published predictions cannot be loaded at all."""
|
||||
return (
|
||||
"No se han podido cargar las predicciones.\n\n"
|
||||
"<i>Asegúrate de que el pipeline diario se ha ejecutado correctamente. "
|
||||
|
||||
Reference in new issue
Block a user