Files
skipredictor/app/scheduler/tasks.py
T
dasemu f6a65f41d9 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
2026-03-13 11:56:59 +01:00

300 lines
11 KiB
Python

"""Scheduled tasks for forecast generation and model retraining.
Three scheduled tasks:
- run_standard_task() — 5h, 10h, 15h: archive + weather + predict
- run_extended_task() — 20h: same + webcam + crowd + actuals scraping
- run_training_task() — Sunday 21h: retrain ML models
"""
from __future__ import annotations
import logging
from datetime import date, datetime, timezone
from typing import Any
import pandas as pd
from data_sources.station_scraper import StationScraper
from data_sources.weather_api import WeatherCollector
from pipeline.build_dataset import DatasetBuilder
from pipeline.feature_engineering import FeatureEngineer
from predictor.hybrid_predictor import HybridPredictor
from scripts.collect_daily_data import (
_available_prediction_dates,
_load_prediction_feature_base,
_select_forecast_row_for_date,
_select_feature_anchor_row,
)
from scripts.retrain_model import main as retrain_main
from storage import (
LATEST_WEATHER_TABLE,
RUNTIME_DATASET_TABLE,
RUNTIME_FEATURED_TABLE,
SQLiteStore,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Shared forecast logic
# ---------------------------------------------------------------------------
def _run_forecast_core(
*,
include_today: bool,
run_hour: int,
) -> list[dict[str, Any]]:
"""Shared forecast generation logic used by standard and extended tasks.
Returns the list of forecast dicts that were saved.
"""
logger.info("=== Forecast cycle started (run_hour=%d) ===", run_hour)
store = SQLiteStore()
# 1. Archive previous forecasts
store.archive_current_forecasts()
# 2. Collect weather
weather_collector = WeatherCollector()
weather_by_station: dict[str, pd.DataFrame] = {}
for station_id, cfg in weather_collector.stations.items():
try:
df = weather_collector.get_forecast(
station_id, cfg["latitude"], cfg["longitude"]
)
weather_by_station[station_id] = df
logger.info("Weather OK: %s (%d rows)", station_id, len(df))
except Exception as exc:
logger.error("Weather failed for %s: %s", station_id, exc)
if not weather_by_station:
logger.error("No weather data collected. Aborting forecast cycle.")
return []
# 3. Scrape station status
scraper = StationScraper()
station_records: list[dict[str, Any]] = []
for station_id in scraper.station_ids:
try:
record = scraper.scrape_station(station_id)
station_records.append(record)
except Exception as exc:
logger.error("Scraping failed for %s: %s", station_id, exc)
# 4. Dataset append + feature engineering
builder = DatasetBuilder(store=store)
engineer = FeatureEngineer()
station_map = {r["station_id"]: r for r in station_records}
today = pd.Timestamp(date.today())
for station_id, weather_df in weather_by_station.items():
station_rec = station_map.get(station_id)
if station_rec is None:
continue
today_rows = weather_df[pd.to_datetime(weather_df["date"]) == today]
if today_rows.empty:
today_rows = weather_df.head(1)
try:
builder.append_daily(
weather_data=today_rows.iloc[0].to_dict(),
station_data=station_rec,
)
except Exception as exc:
logger.error("Dataset append failed for %s: %s", station_id, exc)
# Save weather snapshot
if weather_by_station:
snapshot = pd.concat(weather_by_station.values(), ignore_index=True)
store.save_weather_snapshot(snapshot, table_name=LATEST_WEATHER_TABLE)
runtime_df = store.read_dataframe(RUNTIME_DATASET_TABLE, parse_dates=("date",))
featured_df = pd.DataFrame()
if not runtime_df.empty:
featured_df = engineer.transform(runtime_df)
store.replace_dataframe(RUNTIME_FEATURED_TABLE, featured_df)
# 5. Determine forecast dates
base_date = date.today()
forecast_dates = _available_prediction_dates(
weather_by_station,
base_date=base_date,
include_today=include_today,
)
if not forecast_dates:
logger.error("No usable forecast dates were returned by the weather provider.")
return []
# 6. Generate predictions
predictor = HybridPredictor()
feature_base_df = _load_prediction_feature_base(store, featured_df)
all_forecasts: list[dict[str, Any]] = []
for station_id, weather_df in weather_by_station.items():
station_rec = station_map.get(station_id, {})
for target_date in forecast_dates:
weather_data = _select_forecast_row_for_date(
weather_df,
station_id=station_id,
target_date=target_date,
)
if weather_data is None:
continue
features_df = None
if not feature_base_df.empty:
anchor = _select_feature_anchor_row(
feature_base_df, station_id, target_date
)
if anchor is not None:
features_df = anchor.copy()
features_df["date"] = pd.Timestamp(target_date)
for col in weather_data:
if col in features_df.columns and col not in (
"date",
"station_id",
):
features_df[col] = weather_data[col]
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"]
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)
all_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"],
}
)
except Exception as exc:
logger.error(
"Prediction failed for %s on %s: %s",
station_id,
target_date.isoformat(),
exc,
)
# 7. Save to current_forecasts
if all_forecasts:
store.save_current_forecasts(all_forecasts, run_hour)
logger.info(
"=== Forecast cycle finished (run_hour=%d, forecasts=%d) ===",
run_hour,
len(all_forecasts),
)
return all_forecasts
# ---------------------------------------------------------------------------
# Standard task (5h, 10h, 15h)
# ---------------------------------------------------------------------------
def run_standard_task() -> None:
"""Standard forecast cycle: archive + weather + predict (today included)."""
_run_forecast_core(include_today=True, run_hour=_current_hour())
# ---------------------------------------------------------------------------
# Extended task (20h)
# ---------------------------------------------------------------------------
def run_extended_task() -> None:
"""Extended forecast cycle: predictions from tomorrow + webcam + actuals."""
_run_forecast_core(include_today=False, run_hour=20)
store = SQLiteStore()
scraper = StationScraper()
# Scrape today's actual station data
_scrape_daily_actuals(store, scraper)
# Webcam snapshot + crowd analysis
_collect_daily_crowd_density(store)
# ---------------------------------------------------------------------------
# Training task (Sunday 21h)
# ---------------------------------------------------------------------------
def run_training_task() -> None:
"""Run the full model retraining pipeline."""
logger.info("=== Model retraining triggered by scheduler ===")
try:
exit_code = retrain_main()
if exit_code != 0:
logger.error("Retraining finished with exit code %d.", exit_code)
else:
logger.info("=== Model retraining completed successfully ===")
except Exception as exc:
logger.error("Retraining failed: %s", exc, exc_info=True)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _current_hour() -> int:
"""Return the current hour in Europe/Madrid."""
from zoneinfo import ZoneInfo
return datetime.now(ZoneInfo("Europe/Madrid")).hour
def _collect_daily_crowd_density(store: SQLiteStore) -> None:
"""Download and analyze today's 10:00 AM webcam snapshot from Infonieve."""
logger.info("Collecting today's crowd density from historical archive.")
from scripts.collect_historical_webcams import HISTORICAL_CONFIG, HistoricalWebcamCollector
collector = HistoricalWebcamCollector(store=store)
today = date.today()
for station_id in HISTORICAL_CONFIG:
try:
logger.info("Collecting historical snapshot for %s on %s", station_id, today)
collector.process_day(station_id, today)
except Exception as exc:
logger.error("Daily crowd collection failed for %s: %s", station_id, exc)
def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None:
"""Scrape today's actual station data and save to historical_actuals."""
logger.info("Scraping today's actual station data.")
today_iso = date.today().isoformat()
records: list[dict[str, Any]] = []
for station_id in scraper.station_ids:
try:
data = scraper.scrape_station(station_id)
records.append(
{
"date": today_iso,
"station_id": station_id,
"open_status": int(data["open_status"]) if data.get("open_status") is not None else None,
"km_open": data.get("km_open"),
"lifts_open": data.get("lifts_open"),
"snow_depth": data.get("snow_depth"),
}
)
except Exception as exc:
logger.error("Actual scrape failed for %s: %s", station_id, exc)
if records:
store.save_historical_actual(records)