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

+21 -22
View File
@@ -44,10 +44,8 @@ from pipeline.build_dataset import DatasetBuilder
from pipeline.feature_engineering import FeatureEngineer
from predictor.hybrid_predictor import HybridPredictor
from storage import (
AD_HOC_RUN_KIND,
HISTORICAL_FEATURED_TABLE,
LATEST_WEATHER_TABLE,
PUBLISHED_RUN_KIND,
RUNTIME_DATASET_TABLE,
RUNTIME_FEATURED_TABLE,
SQLiteStore,
@@ -68,7 +66,7 @@ logger = logging.getLogger(__name__)
# Storage
# ---------------------------------------------------------------------------
_DEFAULT_RUN_KIND = PUBLISHED_RUN_KIND
_DEFAULT_RUN_KIND = "published"
# ---------------------------------------------------------------------------
@@ -316,9 +314,9 @@ def generate_predictions(
target_date: date,
run_kind: str,
) -> None:
"""Generate predictions for a target date and save them to SQLite."""
"""Generate predictions for a target date and save them to current_forecasts."""
logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat())
predictions = {}
forecasts: list[dict] = []
station_map = {r["station_id"]: r for r in station_records}
feature_base_df = _load_prediction_feature_base(store, featured_df)
@@ -331,9 +329,6 @@ def generate_predictions(
if weather_data is None:
continue
# Build a feature row: target-date weather + today's station data.
# Current station observations are still the best proxy available for
# same-day or next-day inference.
features_df = None
if not feature_base_df.empty:
anchor_row = _select_feature_anchor_row(
@@ -342,28 +337,35 @@ def generate_predictions(
target_date=target_date,
)
if anchor_row is not None:
# Start from the latest featured row (has rolling features)
features_df = anchor_row
features_df["date"] = pd.Timestamp(target_date)
# Overlay target-date weather
for col in weather_data:
if col in features_df.columns and col not in ("date", "station_id"):
features_df[col] = weather_data[col]
# Overlay today's station data as best proxy
station_rec = station_map.get(station_id, {})
if station_rec.get("snow_depth") is not None:
features_df["snow_depth"] = station_rec["snow_depth"]
if station_rec.get("lifts_open") is not None:
features_df["lifts_open"] = station_rec["lifts_open"]
# Also inject snow_depth into weather_data for the rules engine
station_rec = station_map.get(station_id, {})
if station_rec.get("snow_depth") is not None:
weather_data["snow_depth"] = station_rec["snow_depth"]
try:
result = predictor.predict(station_id, weather_data, features_df)
predictions[station_id] = result
forecasts.append(
{
"station_id": station_id,
"prediction_date": target_date.isoformat(),
"open_probability": result["open_probability"],
"km_open": result["km_open"],
"crowd_level": result["crowd_level"],
"weather_summary": result.get("weather_summary"),
"rule_notes": result.get("rule_overrides", []),
"prediction_source": result["prediction_source"],
}
)
logger.info(
"Prediction for %s: open=%.2f, km=%.1f, crowd=%s, source=%s",
station_id,
@@ -375,7 +377,7 @@ def generate_predictions(
except Exception as exc:
logger.error("Prediction failed for %s: %s", station_id, exc)
if not predictions:
if not forecasts:
logger.error(
"No predictions generated for %s; the requested horizon is outside the "
"available forecast window or every station failed.",
@@ -383,13 +385,10 @@ def generate_predictions(
)
return
output = {
"generated_at": datetime.now(timezone.utc).isoformat(),
"prediction_date": target_date.isoformat(),
"stations": predictions,
}
store.save_prediction_run(output, run_kind=run_kind)
logger.info("Predictions saved to SQLite as %s run.", run_kind)
# Archive existing and save new forecasts
store.archive_current_forecasts()
store.save_current_forecasts(forecasts, run_hour=0)
logger.info("Predictions saved to current_forecasts (%s).", run_kind)
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
@@ -405,7 +404,7 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
)
parser.add_argument(
"--run-kind",
choices=[PUBLISHED_RUN_KIND, AD_HOC_RUN_KIND],
choices=["published", "adhoc"],
default=_DEFAULT_RUN_KIND,
help=(
"Whether this prediction run should be published to the bot "
+106 -15
View File
@@ -14,9 +14,11 @@ Usage:
import argparse
import logging
import re
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from urllib.parse import quote
import pandas as pd
import requests
@@ -45,6 +47,7 @@ HISTORICAL_CONFIG = {
PEAK_HOUR = 10
_BASE_URL = "https://www.infonieve.es/estacion-esqui/{slug}/historico-webcams/{cam_id}-{date_str}-{hour}"
_HISTORICO_AJAX_URL = "https://www.infonieve.es/webcams/historico.php?id={cam_id}&anyo={anyo}&mes={mes}&dia={dia}&hora=&base={base}"
_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
@@ -57,28 +60,107 @@ class HistoricalWebcamCollector:
self.temp_dir = Path("data/raw/webcams/historical")
self.temp_dir.mkdir(parents=True, exist_ok=True)
# Cache for discovered date ranges per station
self._available_ranges: dict[str, tuple[date, date]] = {}
def get_available_date_range(self, station_id: str) -> tuple[date, date] | None:
"""Query Infonieve's AJAX endpoint to find the actual available date range for a station."""
if station_id in self._available_ranges:
return self._available_ranges[station_id]
cfg = HISTORICAL_CONFIG.get(station_id)
if not cfg:
return None
logger.info("Discovering available historical range for %s...", station_id)
try:
base_path = quote(f"estacion-esqui/{cfg['slug']}/historico-webcams/")
# 1. Find years
url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo="", mes="", dia="", base=base_path)
resp = self.session.get(url, timeout=15)
resp.raise_for_status()
years = sorted([int(y) for y in set(re.findall(r'rel="anyo-(\d{4})"', resp.text))])
if not years:
logger.warning("No historical years found for %s", station_id)
return None
min_year, max_year = years[0], years[-1]
# 2. Find min month/day
url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=min_year, mes="", dia="", base=base_path)
resp = self.session.get(url, timeout=15)
months = sorted([int(m) for m in set(re.findall(r'rel="mes-(\d+)"', resp.text))])
min_month = months[0] if months else 1
url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=min_year, mes=f"{min_month:02d}", dia="", base=base_path)
resp = self.session.get(url, timeout=15)
days = sorted([int(d) for d in set(re.findall(r'reldia="(\d+)"', resp.text))])
min_day = days[0] if days else 1
start_date = date(min_year, min_month, min_day)
# 3. Find max month/day
url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=max_year, mes="", dia="", base=base_path)
resp = self.session.get(url, timeout=15)
months = sorted([int(m) for m in set(re.findall(r'rel="mes-(\d+)"', resp.text))])
max_month = months[-1] if months else 12
url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=max_year, mes=f"{max_month:02d}", dia="", base=base_path)
resp = self.session.get(url, timeout=15)
days = sorted([int(d) for d in set(re.findall(r'reldia="(\d+)"', resp.text))])
max_day = days[-1] if days else 28
end_date = date(max_year, max_month, max_day)
logger.info("Range for %s: %s to %s", station_id, start_date, end_date)
self._available_ranges[station_id] = (start_date, end_date)
return start_date, end_date
except Exception as exc:
logger.error("Failed to discover range for %s: %s", station_id, exc)
return None
def process_range(self, start_date: date, end_date: date, station_ids: list[str] | None = None):
"""Process all stations for a given date range."""
"""Process all stations for a given date range, respecting the discovered archive range."""
if station_ids is None:
station_ids = list(HISTORICAL_CONFIG.keys())
current = start_date
while current <= end_date:
for sid in station_ids:
if sid not in HISTORICAL_CONFIG:
for sid in station_ids:
if sid not in HISTORICAL_CONFIG:
continue
# Discover available archive range
archive_range = self.get_available_date_range(sid)
actual_start = start_date
actual_end = end_date
if archive_range:
start_limit, end_limit = archive_range
actual_start = max(start_date, start_limit)
actual_end = min(end_date, end_limit)
if actual_start > actual_end:
logger.info("Requested range for %s is outside available archive range (%s to %s)",
sid, start_limit, end_limit)
continue
logger.info("Adjusted range for %s: %s to %s", sid, actual_start, actual_end)
current = actual_start
while current <= actual_end:
# Skip if we already have analysis for this date/station
if self._is_already_processed(sid, current):
logger.debug("Skipping %s for %s (already processed)", sid, current)
continue
self.process_day(sid, current)
# Be polite to Infonieve
time.sleep(1.0)
current += timedelta(days=1)
else:
self.process_day(sid, current)
# Be polite to Infonieve
time.sleep(1.0)
current += timedelta(days=1)
def auto_sync(self, station_ids: list[str] | None = None):
"""Find all dates in historical_station_raw that lack crowd analysis and fill them."""
@@ -99,7 +181,7 @@ class HistoricalWebcamCollector:
time.sleep(1.0)
def get_missing_dates(self, station_id: str) -> list[date]:
"""Return a list of dates that have snow data but no crowd analysis."""
"""Return a list of dates that have snow data but no crowd analysis, filtered by available archive range."""
# 1. Get all dates with historical station data
station_df = self.store.read_dataframe(HISTORICAL_STATION_TABLE, parse_dates=("date",))
if station_df.empty:
@@ -108,14 +190,23 @@ class HistoricalWebcamCollector:
station_dates = set(station_df[station_df["station_id"] == station_id]["date"].dt.date)
# 2. Get dates that already have crowd analysis
# 2. Discover available webcam archive range
archive_range = self.get_available_date_range(station_id)
if archive_range:
start_limit, end_limit = archive_range
station_dates = {d for d in station_dates if start_limit <= d <= end_limit}
if not station_dates:
logger.info("No station data dates fall within the discovered archive range for %s", station_id)
return []
# 3. Get dates that already have crowd analysis
crowd_df = self.store.load_crowd_analyses(station_id=station_id)
if crowd_df.empty:
existing_dates = set()
else:
existing_dates = set(pd.to_datetime(crowd_df["timestamp"]).dt.date)
# 3. Missing is the difference
# 4. Missing is the difference
missing = sorted(list(station_dates - existing_dates))
return missing