feat: unified architecture and webcam archive optimization

- Refactor backend into a single process (FastAPI + APScheduler + Telegram Bot)
- Implement 'current_forecasts' and 'past_forecasts' architecture in storage
- Optimize historical webcam collector with date range discovery for Pajares, San Isidro, and Fuentes
- Clean up legacy scripts and tables (prediction_runs, prediction_stations)
- Update tests and operations documentation
This commit is contained in:
dasemu committed 2026-03-13 11:56:59 +01:00
1 parent a70eff3e45
commit f6a65f41d9
14 files changed
+563 -660

No files matched your search

+92 -42
View File
@@ -6,8 +6,9 @@ Serves published predictions for three ski stations in northern Spain:
- San Isidro (/sanisidro)
- Fuentes de Invierno (/fuentes)
The bot reads published prediction runs from SQLite and supports both
single-station queries and multi-station horizon commands.
The bot reads forecasts from the ``current_forecasts`` / ``past_forecasts``
tables in SQLite and supports both single-station queries and multi-station
horizon commands.
Usage:
Set the TELEGRAM_BOT_TOKEN environment variable and run:
@@ -15,6 +16,7 @@ Usage:
or call main() directly.
"""
import json
import logging
import os
import sys
@@ -36,7 +38,7 @@ from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import Application, CommandHandler, ContextTypes
from storage import PUBLISHED_RUN_KIND, SQLiteStore
from storage import SQLiteStore
# ---------------------------------------------------------------------------
# Logging
@@ -121,45 +123,85 @@ def prediction_dates_window(
]
def _forecasts_to_payload(
rows: list[dict[str, Any]],
prediction_date: str | None = None,
) -> dict[str, Any] | None:
"""Convert flat forecast rows into the nested payload the bot expects.
Returns a dict with ``prediction_date`` and ``stations`` keys, or None
when *rows* is empty.
"""
if not rows:
return None
stations: dict[str, dict[str, Any]] = {}
first_date = prediction_date
for row in rows:
if prediction_date is not None and row["prediction_date"] != prediction_date:
continue
if first_date is None:
first_date = row["prediction_date"]
stations[row["station_id"]] = {
"station_name": row["station_id"],
"open_probability": row.get("open_probability"),
"km_open": row.get("km_open"),
"crowd_level": row.get("crowd_level"),
"weather_summary": row.get("weather_summary"),
"rule_overrides": json.loads(row["rule_notes_json"] or "[]")
if isinstance(row.get("rule_notes_json"), str)
else (row.get("rule_notes_json") or []),
"prediction_source": row.get("prediction_source"),
}
if not stations:
return None
return {
"generated_at": rows[0].get("generated_at"),
"prediction_date": first_date,
"stations": stations,
}
def load_predictions(
*,
now: datetime | None = None,
store: SQLiteStore | None = None,
) -> dict | None:
"""Load the published predictions most relevant for the current hour.
"""Load the predictions most relevant for the current hour.
Returns the parsed dictionary on success, or None if no published
prediction run exists yet.
Queries ``current_forecasts`` for the preferred prediction dates, falling
back to whatever is available.
"""
store = store or SQLiteStore()
all_rows = store.load_current_forecasts()
for prediction_date in _preferred_prediction_dates(now):
data = store.load_predictions_for_date(
prediction_date=prediction_date,
run_kind=PUBLISHED_RUN_KIND,
)
if data is not None:
logger.info(
"Predicciones cargadas desde SQLite (%s) para %s",
store.db_path,
prediction_date,
)
return data
data = store.load_latest_predictions(run_kind=PUBLISHED_RUN_KIND)
if data is None:
if not all_rows:
logger.warning(
"No hay ninguna predicción publicada en SQLite (%s)",
"No hay ninguna predicción en current_forecasts (%s)",
store.db_path,
)
return None
for prediction_date in _preferred_prediction_dates(now):
payload = _forecasts_to_payload(all_rows, prediction_date)
if payload is not None:
logger.info(
"Predicciones cargadas desde current_forecasts (%s) para %s",
store.db_path,
prediction_date,
)
return payload
# Fallback: return the earliest date available in current_forecasts
payload = _forecasts_to_payload(all_rows, all_rows[0]["prediction_date"])
logger.info(
"Predicciones cargadas desde SQLite (%s) como fallback (%s)",
"Predicciones cargadas desde current_forecasts (%s) como fallback (%s)",
store.db_path,
data.get("prediction_date"),
payload.get("prediction_date") if payload else None,
)
return data
return payload
def load_predictions_for_date(
@@ -167,26 +209,25 @@ def load_predictions_for_date(
*,
store: SQLiteStore | None = None,
) -> dict | None:
"""Load the latest published predictions for a specific target date."""
"""Load the current forecasts for a specific target date."""
store = store or SQLiteStore()
data = store.load_predictions_for_date(
prediction_date=prediction_date,
run_kind=PUBLISHED_RUN_KIND,
)
if data is None:
all_rows = store.load_current_forecasts()
payload = _forecasts_to_payload(all_rows, prediction_date)
if payload is None:
logger.info(
"No hay predicción publicada en SQLite (%s) para %s",
"No hay predicción en current_forecasts (%s) para %s",
store.db_path,
prediction_date,
)
return None
logger.info(
"Predicciones cargadas desde SQLite (%s) para %s",
"Predicciones cargadas desde current_forecasts (%s) para %s",
store.db_path,
prediction_date,
)
return data
return payload
# ---------------------------------------------------------------------------
@@ -559,22 +600,21 @@ async def cmd_semana(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None
# ---------------------------------------------------------------------------
def main() -> None:
"""Build and start the Telegram bot using long-polling.
def create_bot_application(token: str | None = None) -> Application:
"""Build the Telegram Application with all handlers registered.
Reads the bot token from the TELEGRAM_BOT_TOKEN environment variable.
Raises:
EnvironmentError: If TELEGRAM_BOT_TOKEN is not set.
When *token* is None the ``TELEGRAM_BOT_TOKEN`` env var is used.
The returned Application has NOT been started yet — callers can either
use ``app.run_polling()`` (standalone) or manage the lifecycle manually
(in-process with FastAPI).
"""
token = os.environ.get("TELEGRAM_BOT_TOKEN")
token = token or os.environ.get("TELEGRAM_BOT_TOKEN")
if not token:
raise EnvironmentError(
"La variable de entorno TELEGRAM_BOT_TOKEN no está definida. "
"Configura el token del bot antes de iniciar."
)
logger.info("Iniciando bot de predicción de esquí...")
app = Application.builder().token(token).build()
app.add_handler(CommandHandler("start", cmd_start))
@@ -588,6 +628,16 @@ def main() -> None:
app.add_handler(CommandHandler("tresdias", cmd_tresdias))
app.add_handler(CommandHandler("semana", cmd_semana))
return app
def main() -> None:
"""Build and start the Telegram bot using long-polling (standalone mode).
Reads the bot token from the TELEGRAM_BOT_TOKEN environment variable.
"""
logger.info("Iniciando bot de predicción de esquí...")
app = create_bot_application()
logger.info("Bot listo. Esperando mensajes...")
app.run_polling(allowed_updates=Update.ALL_TYPES)