mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
410 lines
15 KiB
Python
410 lines
15 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 predictions to data/processed/predictions_latest.json.
|
|
|
|
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 overwriting production:
|
|
python scripts/collect_daily_data.py \
|
|
--days-ahead 0 \
|
|
--output-path data/processed/predictions_today_check.json
|
|
|
|
Exit codes:
|
|
0 - Pipeline completed (partial failures are logged but do not abort).
|
|
1 - Fatal error that prevented any useful work.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
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
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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__)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Output paths
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed"
|
|
_RUNTIME_DIR = _PROCESSED_DIR / "runtime"
|
|
_DATASET_PATH = _RUNTIME_DIR / "dataset.csv"
|
|
_FEATURED_PATH = _RUNTIME_DIR / "dataset_featured.csv"
|
|
_HISTORICAL_FEATURED_PATH = _PROCESSED_DIR / "dataset_featured.csv"
|
|
_PREDICTIONS_PATH = _PROCESSED_DIR / "predictions_latest.json"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Pipeline steps
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def collect_weather(collector: WeatherCollector) -> 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)
|
|
return results
|
|
|
|
|
|
def collect_station_status(scraper: StationScraper) -> list[dict]:
|
|
"""Scrape current operational status for all stations."""
|
|
logger.info("Step 2/5 - Collecting station status.")
|
|
records = []
|
|
for station_id in scraper._stations:
|
|
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)
|
|
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 = 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[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 the current dataset
|
|
if _DATASET_PATH.exists():
|
|
df = pd.read_csv(_DATASET_PATH)
|
|
df["date"] = pd.to_datetime(df["date"])
|
|
return df
|
|
return pd.DataFrame()
|
|
|
|
|
|
def run_feature_engineering(engineer: FeatureEngineer, 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)
|
|
_FEATURED_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
featured.to_csv(_FEATURED_PATH, index=False)
|
|
logger.info("Featured dataset saved: %d rows, %d cols.", len(featured), len(featured.columns))
|
|
return featured
|
|
|
|
|
|
def _load_prediction_feature_base(runtime_featured_df: pd.DataFrame) -> pd.DataFrame:
|
|
"""Return the best available feature base for inference.
|
|
|
|
Preference order:
|
|
1. Historical `dataset_featured.csv` 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 = pd.DataFrame()
|
|
if _HISTORICAL_FEATURED_PATH.exists():
|
|
try:
|
|
historical_df = pd.read_csv(_HISTORICAL_FEATURED_PATH, parse_dates=["date"])
|
|
logger.info(
|
|
"Loaded historical feature base from %s (%d rows).",
|
|
_HISTORICAL_FEATURED_PATH,
|
|
len(historical_df),
|
|
)
|
|
except Exception as exc:
|
|
logger.warning(
|
|
"Could not load historical feature base from %s: %s",
|
|
_HISTORICAL_FEATURED_PATH,
|
|
exc,
|
|
)
|
|
|
|
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(
|
|
predictor: HybridPredictor,
|
|
weather_by_station: dict[str, pd.DataFrame],
|
|
featured_df: pd.DataFrame,
|
|
station_records: list[dict],
|
|
target_date: date,
|
|
output_path: Path,
|
|
) -> None:
|
|
"""Generate predictions for a target date and save them to disk."""
|
|
logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat())
|
|
predictions = {}
|
|
station_map = {r["station_id"]: r for r in station_records}
|
|
base_date = date.today()
|
|
days_ahead = (target_date - base_date).days
|
|
feature_base_df = _load_prediction_feature_base(featured_df)
|
|
|
|
for station_id, weather_df in weather_by_station.items():
|
|
# Get target-date forecast row as weather_data dict.
|
|
target_rows = weather_df[weather_df["date"] == target_date]
|
|
if target_rows.empty:
|
|
fallback_index = max(0, min(days_ahead, len(weather_df) - 1))
|
|
target_rows = weather_df.iloc[fallback_index:fallback_index + 1]
|
|
if target_rows.empty:
|
|
logger.warning("No forecast for %s for %s.", station_id, target_date.isoformat())
|
|
continue
|
|
|
|
weather_data = target_rows.iloc[0].to_dict()
|
|
|
|
# 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)
|
|
|
|
# Save predictions
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
output = {
|
|
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
"prediction_date": target_date.isoformat(),
|
|
"stations": predictions,
|
|
}
|
|
with output_path.open("w", encoding="utf-8") as fh:
|
|
json.dump(output, fh, indent=2, ensure_ascii=False, default=str)
|
|
logger.info("Predictions saved to %s.", output_path)
|
|
|
|
|
|
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
"""Parse CLI arguments for ad hoc 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(
|
|
"--output-path",
|
|
default=str(_PREDICTIONS_PATH),
|
|
help="Path for the generated predictions JSON. Defaults to predictions_latest.json.",
|
|
)
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def _resolve_output_path(raw_path: str) -> Path:
|
|
"""Resolve an output path against the project root when relative."""
|
|
path = Path(raw_path)
|
|
if path.is_absolute():
|
|
return path
|
|
return (_PROJECT_ROOT / path).resolve()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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)
|
|
output_path = _resolve_output_path(args.output_path)
|
|
|
|
logger.info(
|
|
"=== Daily pipeline started (target_date=%s, output_path=%s) ===",
|
|
target_date.isoformat(),
|
|
output_path,
|
|
)
|
|
|
|
try:
|
|
weather_collector = WeatherCollector()
|
|
station_scraper = StationScraper()
|
|
dataset_builder = DatasetBuilder(processed_dir=_RUNTIME_DIR)
|
|
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)
|
|
station_records = collect_station_status(station_scraper)
|
|
|
|
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, df)
|
|
|
|
# Step 5: predictions
|
|
generate_predictions(
|
|
hybrid_predictor,
|
|
weather_data,
|
|
featured_df,
|
|
station_records,
|
|
target_date=target_date,
|
|
output_path=output_path,
|
|
)
|
|
|
|
logger.info("=== Daily pipeline finished ===")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|