mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
299 lines
11 KiB
Python
299 lines
11 KiB
Python
"""Scheduled tasks for forecast generation and model retraining.
|
|
|
|
These functions are invoked by APScheduler from the FastAPI lifespan and
|
|
reuse the same pipeline components as ``scripts/collect_daily_data.py``.
|
|
"""
|
|
|
|
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__)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Forecast cycle
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def run_forecast_cycle(run_hour: int) -> None:
|
|
"""Execute a full forecast cycle for a given run hour.
|
|
|
|
Steps:
|
|
1. Archive current forecasts into past_forecasts.
|
|
2. Fetch weather forecasts via Open-Meteo.
|
|
3. Scrape current station status.
|
|
4. Append to runtime dataset + feature engineering.
|
|
5. Generate predictions for each station x each forecast day.
|
|
6. Save results to current_forecasts.
|
|
7. At hour 20, scrape today's actual data into historical_actuals.
|
|
"""
|
|
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=run_hour < 15,
|
|
)
|
|
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
|
|
|
|
# Build feature row
|
|
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)
|
|
|
|
# Also save as a published prediction run for the bot's existing flow
|
|
# (one run per distinct target date, same as collect_daily_data.py)
|
|
_save_as_prediction_runs(store, all_forecasts, run_hour)
|
|
|
|
# 8. At hour 20: scrape today's actual data and crowd density
|
|
if run_hour == 20:
|
|
_scrape_daily_actuals(store, scraper)
|
|
_collect_daily_crowd_density(store)
|
|
|
|
logger.info(
|
|
"=== Forecast cycle finished (run_hour=%d, forecasts=%d) ===",
|
|
run_hour,
|
|
len(all_forecasts),
|
|
)
|
|
|
|
|
|
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.")
|
|
# Local import to avoid circular dependencies
|
|
from scripts.collect_historical_webcams import HistoricalWebcamCollector
|
|
|
|
collector = HistoricalWebcamCollector(store=store)
|
|
today = date.today()
|
|
|
|
# Process for each configured historical station
|
|
from scripts.collect_historical_webcams import HISTORICAL_CONFIG
|
|
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 _save_as_prediction_runs(
|
|
store: SQLiteStore,
|
|
forecasts: list[dict[str, Any]],
|
|
run_hour: int,
|
|
) -> None:
|
|
"""Persist forecasts as published prediction_runs for bot compatibility."""
|
|
by_date: dict[str, dict[str, Any]] = {}
|
|
for f in forecasts:
|
|
by_date.setdefault(f["prediction_date"], {})[f["station_id"]] = {
|
|
"station_name": f["station_id"],
|
|
"open_probability": f["open_probability"],
|
|
"km_open": f["km_open"],
|
|
"crowd_level": f["crowd_level"],
|
|
"weather_summary": f.get("weather_summary"),
|
|
"rule_overrides": f.get("rule_notes", []),
|
|
"prediction_source": f["prediction_source"],
|
|
}
|
|
|
|
for pred_date, stations in by_date.items():
|
|
payload = {
|
|
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
"prediction_date": pred_date,
|
|
"stations": stations,
|
|
}
|
|
store.save_prediction_run(payload, run_kind="published")
|
|
|
|
|
|
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)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Retrain
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def run_retrain() -> 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)
|