mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 07:16:15 +00:00
477 lines
16 KiB
Python
477 lines
16 KiB
Python
"""Daily data collection pipeline for the ski predictor.
|
|
|
|
This script is designed for cron execution. It runs every day to:
|
|
|
|
1. Collect weather forecasts for all configured stations.
|
|
2. Collect current station operational status.
|
|
3. Append new rows to the processed dataset.
|
|
4. Run feature engineering on the updated dataset.
|
|
5. Generate predictions for the configured target date using the
|
|
HybridPredictor.
|
|
6. Save the prediction run to SQLite.
|
|
|
|
Cron example (run daily at 20:00, after stations close):
|
|
0 20 * * * /path/to/.venv/bin/python /path/to/scripts/collect_daily_data.py
|
|
|
|
Ad hoc example for same-day verification without affecting the bot:
|
|
python scripts/collect_daily_data.py --days-ahead 0 --run-kind adhoc
|
|
|
|
Exit codes:
|
|
0 - Pipeline completed (partial failures are logged but do not abort).
|
|
1 - Fatal error that prevented any useful work.
|
|
"""
|
|
|
|
import argparse
|
|
import logging
|
|
import sys
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Ensure the project root is on sys.path so all project packages are
|
|
# importable when this script is executed directly (e.g. via cron or CLI).
|
|
# ---------------------------------------------------------------------------
|
|
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
_PROJECT_ROOT = _SCRIPT_DIR.parent
|
|
if str(_PROJECT_ROOT) not in sys.path:
|
|
sys.path.insert(0, str(_PROJECT_ROOT))
|
|
|
|
from data_sources.weather_api import WeatherCollector
|
|
from data_sources.station_scraper import StationScraper
|
|
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,
|
|
)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Logging setup
|
|
# ---------------------------------------------------------------------------
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
|
|
datefmt="%Y-%m-%d %H:%M:%S",
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Storage
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_DEFAULT_RUN_KIND = PUBLISHED_RUN_KIND
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Pipeline steps
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def collect_weather(
|
|
collector: WeatherCollector,
|
|
store: SQLiteStore,
|
|
) -> dict[str, pd.DataFrame]:
|
|
"""Fetch weather forecasts for all stations."""
|
|
logger.info("Step 1/5 - Collecting weather forecasts.")
|
|
results = {}
|
|
for station_id, cfg in collector.stations.items():
|
|
try:
|
|
df = collector.get_forecast(station_id, cfg["latitude"], cfg["longitude"])
|
|
results[station_id] = df
|
|
logger.info("Weather forecast: station=%s, %d rows.", station_id, len(df))
|
|
except Exception as exc:
|
|
logger.error("Weather failed for %s: %s", station_id, exc)
|
|
|
|
if results:
|
|
snapshot = pd.concat(results.values(), ignore_index=True)
|
|
store.save_weather_snapshot(snapshot, table_name=LATEST_WEATHER_TABLE)
|
|
return results
|
|
|
|
|
|
def collect_station_status(
|
|
scraper: StationScraper,
|
|
store: SQLiteStore,
|
|
) -> list[dict]:
|
|
"""Scrape current operational status for all stations."""
|
|
logger.info("Step 2/5 - Collecting station status.")
|
|
records = []
|
|
for station_id in scraper.station_ids:
|
|
try:
|
|
record = scraper.scrape_station(station_id)
|
|
records.append(record)
|
|
logger.info(
|
|
"Station status: %s open=%s km=%s depth=%s",
|
|
station_id, record.get("open_status"),
|
|
record.get("km_open"), record.get("snow_depth"),
|
|
)
|
|
except Exception as exc:
|
|
logger.error("Scraping failed for %s: %s", station_id, exc)
|
|
|
|
if records:
|
|
store.save_latest_station_status(records)
|
|
return records
|
|
|
|
|
|
def append_to_dataset(
|
|
builder: DatasetBuilder,
|
|
weather_by_station: dict[str, pd.DataFrame],
|
|
station_records: list[dict],
|
|
) -> pd.DataFrame:
|
|
"""Append today's data to the processed dataset."""
|
|
logger.info("Step 3/5 - Appending data to dataset.")
|
|
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_record = station_map.get(station_id)
|
|
if station_record is None:
|
|
logger.warning("No station record for %s, skipping.", station_id)
|
|
continue
|
|
|
|
# Use today's forecast row for the weather data
|
|
today_rows = weather_df[pd.to_datetime(weather_df["date"]) == today]
|
|
if today_rows.empty:
|
|
# Fallback to first available row
|
|
today_rows = weather_df.head(1)
|
|
|
|
weather_row = today_rows.iloc[0].to_dict()
|
|
|
|
try:
|
|
builder.append_daily(weather_data=weather_row, station_data=station_record)
|
|
logger.info("Dataset updated for %s.", station_id)
|
|
except Exception as exc:
|
|
logger.error("Append failed for %s: %s", station_id, exc)
|
|
|
|
return builder.store.read_dataframe(RUNTIME_DATASET_TABLE, parse_dates=("date",))
|
|
|
|
|
|
def run_feature_engineering(
|
|
engineer: FeatureEngineer,
|
|
store: SQLiteStore,
|
|
df: pd.DataFrame,
|
|
) -> pd.DataFrame:
|
|
"""Run feature engineering on the dataset."""
|
|
logger.info("Step 4/5 - Running feature engineering.")
|
|
if df.empty:
|
|
logger.warning("Empty dataset, skipping feature engineering.")
|
|
return df
|
|
|
|
featured = engineer.transform(df)
|
|
store.replace_dataframe(RUNTIME_FEATURED_TABLE, featured)
|
|
logger.info(
|
|
"Featured dataset saved to table %s: %d rows, %d cols.",
|
|
RUNTIME_FEATURED_TABLE,
|
|
len(featured),
|
|
len(featured.columns),
|
|
)
|
|
return featured
|
|
|
|
|
|
def _available_prediction_dates(
|
|
weather_by_station: dict[str, pd.DataFrame],
|
|
*,
|
|
base_date: date,
|
|
include_today: bool,
|
|
) -> list[date]:
|
|
"""Return the real prediction dates available in the collected forecasts."""
|
|
available_dates: set[date] = set()
|
|
for weather_df in weather_by_station.values():
|
|
if weather_df.empty or "date" not in weather_df.columns:
|
|
continue
|
|
station_dates = pd.to_datetime(weather_df["date"], format="mixed").dt.date
|
|
available_dates.update(station_dates.tolist())
|
|
|
|
if include_today:
|
|
return sorted(d for d in available_dates if d >= base_date)
|
|
return sorted(d for d in available_dates if d > base_date)
|
|
|
|
|
|
def _select_forecast_row_for_date(
|
|
weather_df: pd.DataFrame,
|
|
*,
|
|
station_id: str,
|
|
target_date: date,
|
|
) -> dict[str, object] | None:
|
|
"""Return the exact forecast row for *target_date*, or None when unavailable."""
|
|
if weather_df.empty or "date" not in weather_df.columns:
|
|
logger.warning("No forecast rows available for %s.", station_id)
|
|
return None
|
|
|
|
weather_dates = pd.to_datetime(weather_df["date"], format="mixed").dt.date
|
|
target_rows = weather_df.loc[weather_dates == target_date]
|
|
if not target_rows.empty:
|
|
return target_rows.iloc[0].to_dict()
|
|
|
|
available_dates = sorted(set(weather_dates.tolist()))
|
|
if available_dates:
|
|
logger.warning(
|
|
"Forecast for %s on %s is unavailable. Available range: %s -> %s.",
|
|
station_id,
|
|
target_date.isoformat(),
|
|
available_dates[0].isoformat(),
|
|
available_dates[-1].isoformat(),
|
|
)
|
|
else:
|
|
logger.warning(
|
|
"Forecast for %s on %s is unavailable.",
|
|
station_id,
|
|
target_date.isoformat(),
|
|
)
|
|
return None
|
|
|
|
|
|
def _load_prediction_feature_base(
|
|
store: SQLiteStore,
|
|
runtime_featured_df: pd.DataFrame,
|
|
) -> pd.DataFrame:
|
|
"""Return the best available feature base for inference.
|
|
|
|
Preference order:
|
|
1. Historical featured dataset used for model training, when it
|
|
exists and contains more rows than the runtime snapshot.
|
|
2. The runtime-engineered dataset generated during this script run.
|
|
|
|
This prevents the daily pipeline from relying on a tiny runtime snapshot
|
|
when rich historical features are available.
|
|
"""
|
|
historical_df = store.read_dataframe(
|
|
HISTORICAL_FEATURED_TABLE,
|
|
parse_dates=("date",),
|
|
)
|
|
if not historical_df.empty:
|
|
logger.info(
|
|
"Loaded historical feature base from table %s (%d rows).",
|
|
HISTORICAL_FEATURED_TABLE,
|
|
len(historical_df),
|
|
)
|
|
|
|
candidates = []
|
|
if not historical_df.empty:
|
|
candidates.append(("historical", historical_df))
|
|
if not runtime_featured_df.empty:
|
|
candidates.append(("runtime", runtime_featured_df))
|
|
|
|
if not candidates:
|
|
return runtime_featured_df
|
|
|
|
source_name, feature_base_df = max(candidates, key=lambda item: len(item[1]))
|
|
logger.info(
|
|
"Using %s feature base for predictions (%d rows).",
|
|
source_name,
|
|
len(feature_base_df),
|
|
)
|
|
return feature_base_df
|
|
|
|
|
|
def _select_feature_anchor_row(
|
|
feature_base_df: pd.DataFrame,
|
|
station_id: str,
|
|
target_date: date,
|
|
) -> pd.DataFrame | None:
|
|
"""Return the best historical feature row to anchor inference.
|
|
|
|
The daily inference path must not blindly use the latest row in the
|
|
historical dataset because that dataset can contain dates after the
|
|
prediction target. Using a future-season row skews engineered features
|
|
such as calendar fields and rolling weather summaries.
|
|
|
|
Preference order:
|
|
1. Latest row with ``date <= target_date``.
|
|
2. Earliest available row for the station as a fallback.
|
|
"""
|
|
station_featured = feature_base_df[feature_base_df["station_id"] == station_id].copy()
|
|
if station_featured.empty:
|
|
return None
|
|
|
|
station_featured["date"] = pd.to_datetime(station_featured["date"])
|
|
eligible = station_featured[station_featured["date"] <= pd.Timestamp(target_date)]
|
|
if eligible.empty:
|
|
anchor = station_featured.sort_values("date").head(1).copy()
|
|
else:
|
|
anchor = eligible.sort_values("date").tail(1).copy()
|
|
|
|
logger.info(
|
|
"Selected feature anchor for %s at %s.",
|
|
station_id,
|
|
pd.Timestamp(anchor.iloc[0]["date"]).date().isoformat(),
|
|
)
|
|
return anchor
|
|
|
|
|
|
def generate_predictions(
|
|
store: SQLiteStore,
|
|
predictor: HybridPredictor,
|
|
weather_by_station: dict[str, pd.DataFrame],
|
|
featured_df: pd.DataFrame,
|
|
station_records: list[dict],
|
|
target_date: date,
|
|
run_kind: str,
|
|
) -> None:
|
|
"""Generate predictions for a target date and save them to SQLite."""
|
|
logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat())
|
|
predictions = {}
|
|
station_map = {r["station_id"]: r for r in station_records}
|
|
feature_base_df = _load_prediction_feature_base(store, featured_df)
|
|
|
|
for station_id, weather_df in weather_by_station.items():
|
|
weather_data = _select_forecast_row_for_date(
|
|
weather_df,
|
|
station_id=station_id,
|
|
target_date=target_date,
|
|
)
|
|
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(
|
|
feature_base_df=feature_base_df,
|
|
station_id=station_id,
|
|
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
|
|
logger.info(
|
|
"Prediction for %s: open=%.2f, km=%.1f, crowd=%s, source=%s",
|
|
station_id,
|
|
result["open_probability"],
|
|
result["km_open"],
|
|
result["crowd_level"],
|
|
result["prediction_source"],
|
|
)
|
|
except Exception as exc:
|
|
logger.error("Prediction failed for %s: %s", station_id, exc)
|
|
|
|
if not predictions:
|
|
logger.error(
|
|
"No predictions generated for %s; the requested horizon is outside the "
|
|
"available forecast window or every station failed.",
|
|
target_date.isoformat(),
|
|
)
|
|
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)
|
|
|
|
|
|
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
"""Parse CLI arguments for prediction runs."""
|
|
parser = argparse.ArgumentParser(
|
|
description="Collect station/weather data and generate ski predictions.",
|
|
)
|
|
parser.add_argument(
|
|
"--days-ahead",
|
|
type=int,
|
|
default=1,
|
|
help="Prediction horizon in days relative to today (default: 1). Use 0 for today.",
|
|
)
|
|
parser.add_argument(
|
|
"--run-kind",
|
|
choices=[PUBLISHED_RUN_KIND, AD_HOC_RUN_KIND],
|
|
default=_DEFAULT_RUN_KIND,
|
|
help=(
|
|
"Whether this prediction run should be published to the bot "
|
|
"or stored as an ad hoc diagnostic run."
|
|
),
|
|
)
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Main entry point
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
"""Run the full daily data collection and prediction pipeline."""
|
|
args = _parse_args(argv)
|
|
target_date = date.today() + timedelta(days=args.days_ahead)
|
|
store = SQLiteStore()
|
|
|
|
logger.info(
|
|
"=== Daily pipeline started (target_date=%s, run_kind=%s, db=%s) ===",
|
|
target_date.isoformat(),
|
|
args.run_kind,
|
|
store.db_path,
|
|
)
|
|
|
|
try:
|
|
weather_collector = WeatherCollector()
|
|
station_scraper = StationScraper()
|
|
dataset_builder = DatasetBuilder(store=store)
|
|
feature_engineer = FeatureEngineer()
|
|
hybrid_predictor = HybridPredictor()
|
|
except Exception as exc:
|
|
logger.critical("Failed to initialise components: %s", exc, exc_info=True)
|
|
return 1
|
|
|
|
# Steps 1-2: collect data
|
|
weather_data = collect_weather(weather_collector, store)
|
|
station_records = collect_station_status(station_scraper, store)
|
|
|
|
if not weather_data and not station_records:
|
|
logger.error("No data collected. Aborting.")
|
|
return 1
|
|
|
|
# Step 3: append to dataset
|
|
df = append_to_dataset(dataset_builder, weather_data, station_records)
|
|
|
|
# Step 4: feature engineering
|
|
featured_df = run_feature_engineering(feature_engineer, store, df)
|
|
|
|
# Step 5: predictions
|
|
generate_predictions(
|
|
store,
|
|
hybrid_predictor,
|
|
weather_data,
|
|
featured_df,
|
|
station_records,
|
|
target_date=target_date,
|
|
run_kind=args.run_kind,
|
|
)
|
|
|
|
logger.info("=== Daily pipeline finished ===")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|