diff --git a/LESSONS.md b/LESSONS.md index 1ba89b1..8dac01b 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -2,10 +2,10 @@ **What went wrong:** I assumed the Telegram bot running on the server might differ from the repository after seeing a schema mismatch between the bot code and the predictions JSON. -**Root cause:** I inferred deployment drift before exhausting the simpler explanation: the repository bot itself still expected the old JSON schema and would therefore fail even when code and server were synchronized. +**Root cause:** I inferred deployment drift before exhausting the simpler explanation: the repository bot itself still expected the old JSON schema and would therefore fail even when code and server were synchronized. I also failed to apply the repository-specific operating assumption that production runs on the server unless the user explicitly says otherwise. -**Prevention rule:** In this repository, when the user states the server and repo are synchronized, treat that as the default assumption and first verify whether the bug is reproducible directly from the checked-in code before attributing it to deployment drift. +**Prevention rule:** In this repository, unless the user explicitly says otherwise, assume production deployment lives on the server even if development happens locally. When the user states the server and repo are synchronized, treat that as the default assumption and first verify whether the bug is reproducible directly from the checked-in code before attributing it to deployment drift. -**Example:** `bot/telegram_bot.py` expected top-level station keys plus legacy fields like `station_open_probability`, while `scripts/collect_daily_data.py` writes predictions under `stations` with fields such as `open_probability` and `km_open`. +**Example:** The production JSON at `/opt/skipredictor/data/processed/predictions_latest.json` on the server contained valid predictions under `stations`, and the checked-in [telegram_bot.py](/home/dasemu/Hacking/Darío Sevilla/skipredictor/bot/telegram_bot.py) still expected top-level station keys plus legacy fields like `station_open_probability`, while [collect_daily_data.py](/home/dasemu/Hacking/Darío Sevilla/skipredictor/scripts/collect_daily_data.py) writes predictions under `stations` with fields such as `open_probability` and `km_open`. **Files affected:** `bot/telegram_bot.py`, `scripts/collect_daily_data.py` diff --git a/pipeline/build_dataset.py b/pipeline/build_dataset.py index 34c8d88..6d13a1c 100644 --- a/pipeline/build_dataset.py +++ b/pipeline/build_dataset.py @@ -7,7 +7,6 @@ handles missing data, and writes a processed dataset to disk. import glob import json import logging -import os from pathlib import Path from typing import Optional @@ -19,7 +18,6 @@ logger = logging.getLogger(__name__) _REPO_ROOT = Path(__file__).resolve().parents[1] _RAW_DIR = _REPO_ROOT / "data" / "raw" _PROCESSED_DIR = _REPO_ROOT / "data" / "processed" -_DATASET_PATH = _PROCESSED_DIR / "dataset.csv" # Numeric weather columns that can be safely interpolated when values are # missing in the middle of a time series. Columns not listed here are filled @@ -231,13 +229,14 @@ class DatasetBuilder: def _load_existing_dataset(self) -> pd.DataFrame: """Return the persisted processed dataset, or an empty DataFrame.""" - if _DATASET_PATH.exists(): - df = pd.read_csv(_DATASET_PATH) + dataset_path = self.processed_dir / "dataset.csv" + if dataset_path.exists(): + df = pd.read_csv(dataset_path) df["date"] = pd.to_datetime(df["date"], format="mixed") logger.debug("Loaded existing dataset with %d rows.", len(df)) return df - logger.debug("No existing dataset found at %s.", _DATASET_PATH) + logger.debug("No existing dataset found at %s.", dataset_path) return pd.DataFrame() # ------------------------------------------------------------------ diff --git a/scripts/collect_daily_data.py b/scripts/collect_daily_data.py index a07dd13..b796a44 100644 --- a/scripts/collect_daily_data.py +++ b/scripts/collect_daily_data.py @@ -6,17 +6,24 @@ This script is designed for cron execution. It runs every day to: 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. + 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 @@ -56,8 +63,10 @@ logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- _PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed" -_DATASET_PATH = _PROCESSED_DIR / "dataset.csv" -_FEATURED_PATH = _PROCESSED_DIR / "dataset_featured.csv" +_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" @@ -144,44 +153,96 @@ def run_feature_engineering(engineer: FeatureEngineer, df: pd.DataFrame) -> pd.D return df featured = engineer.transform(df) - _PROCESSED_DIR.mkdir(parents=True, exist_ok=True) + _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 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 next-day predictions and save to disk.""" - logger.info("Step 5/5 - Generating predictions.") - tomorrow = date.today() + timedelta(days=1) + """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 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) + # 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 = tomorrow_rows.iloc[0].to_dict() + weather_data = target_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) + # 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 featured_df.empty: - station_featured = featured_df[featured_df["station_id"] == station_id] + if not feature_base_df.empty: + station_featured = feature_base_df[feature_base_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 + 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] @@ -212,15 +273,42 @@ def generate_predictions( logger.error("Prediction failed for %s: %s", station_id, exc) # Save predictions - _PREDICTIONS_PATH.parent.mkdir(parents=True, exist_ok=True) + output_path.parent.mkdir(parents=True, exist_ok=True) output = { "generated_at": datetime.now(timezone.utc).isoformat(), - "prediction_date": tomorrow.isoformat(), + "prediction_date": target_date.isoformat(), "stations": predictions, } - with open(_PREDICTIONS_PATH, "w", encoding="utf-8") as fh: + 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.", _PREDICTIONS_PATH) + 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() # --------------------------------------------------------------------------- @@ -228,14 +316,22 @@ def generate_predictions( # --------------------------------------------------------------------------- -def main() -> int: +def main(argv: list[str] | None = None) -> int: """Run the full daily data collection and prediction pipeline.""" - logger.info("=== Daily pipeline started ===") + 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() + dataset_builder = DatasetBuilder(processed_dir=_RUNTIME_DIR) feature_engineer = FeatureEngineer() hybrid_predictor = HybridPredictor() except Exception as exc: @@ -257,7 +353,14 @@ def main() -> int: featured_df = run_feature_engineering(feature_engineer, df) # Step 5: predictions - generate_predictions(hybrid_predictor, weather_data, featured_df, station_records) + 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