"""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 next day 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 Exit codes: 0 - Pipeline completed (partial failures are logged but do not abort). 1 - Fatal error that prevented any useful work. """ 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" _DATASET_PATH = _PROCESSED_DIR / "dataset.csv" _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) _PROCESSED_DIR.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 generate_predictions( predictor: HybridPredictor, weather_by_station: dict[str, pd.DataFrame], featured_df: pd.DataFrame, station_records: list[dict], ) -> None: """Generate next-day predictions and save to disk.""" logger.info("Step 5/5 - Generating predictions.") tomorrow = date.today() + timedelta(days=1) predictions = {} station_map = {r["station_id"]: r for r in station_records} for station_id, weather_df in weather_by_station.items(): # Get tomorrow's forecast row as weather_data dict tomorrow_rows = weather_df[weather_df["date"] == tomorrow] if tomorrow_rows.empty: tomorrow_rows = weather_df.iloc[1:2] if tomorrow_rows.empty: logger.warning("No forecast for tomorrow for %s.", station_id) continue weather_data = tomorrow_rows.iloc[0].to_dict() # Build a feature row: tomorrow's weather + today's station data # (lifts_open, snow_depth are current observations - best proxy for tomorrow) features_df = None if not featured_df.empty: station_featured = featured_df[featured_df["station_id"] == station_id] if not station_featured.empty: # Start from the latest featured row (has rolling features) features_df = station_featured.tail(1).copy() # Overlay tomorrow's 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 _PREDICTIONS_PATH.parent.mkdir(parents=True, exist_ok=True) output = { "generated_at": datetime.now(timezone.utc).isoformat(), "prediction_date": tomorrow.isoformat(), "stations": predictions, } with open(_PREDICTIONS_PATH, "w", encoding="utf-8") as fh: json.dump(output, fh, indent=2, ensure_ascii=False, default=str) logger.info("Predictions saved to %s.", _PREDICTIONS_PATH) # --------------------------------------------------------------------------- # Main entry point # --------------------------------------------------------------------------- def main() -> int: """Run the full daily data collection and prediction pipeline.""" logger.info("=== Daily pipeline started ===") try: weather_collector = WeatherCollector() station_scraper = StationScraper() dataset_builder = DatasetBuilder() 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) logger.info("=== Daily pipeline finished ===") return 0 if __name__ == "__main__": sys.exit(main())