feat(storage): migrate project to sqlite

This commit is contained in:
dasemu committed 2026-03-13 06:50:18 +01:00
1 parent 1bc1e58781
commit 9c8ba03574
17 files changed
+1204 -688

No files matched your search

+20 -86
View File
@@ -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,19 @@ 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("Predictions file not found: %s", PREDICTIONS_FILE)
store = SQLiteStore()
data = store.load_latest_predictions(run_kind=PUBLISHED_RUN_KIND)
if data is None:
logger.warning("No published prediction run found in %s", store.db_path)
return None
try:
with PREDICTIONS_FILE.open(encoding="utf-8") as fh:
data = json.load(fh)
logger.info("Predictions loaded from %s", PREDICTIONS_FILE)
return data
except json.JSONDecodeError as exc:
logger.error("Failed to decode predictions file: %s", exc)
return None
logger.info("Predictions loaded from SQLite (%s)", store.db_path)
return data
# ---------------------------------------------------------------------------
@@ -114,16 +101,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 +124,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,33 +134,12 @@ 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", "prediccion hibrida (reglas + ML)"),
)
)
source = str(prediction.get("prediction_source", "prediccion hibrida (reglas + ML)"))
open_pct = int(round(open_prob * 100))
open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)"
@@ -189,33 +150,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 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 = ""
@@ -247,7 +181,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>Asegurate de que el pipeline diario se ha ejecutado correctamente. "