From f63913b23cb48739aadb309c93fd26d43b78d232 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Fri, 13 Mar 2026 12:09:42 +0100 Subject: [PATCH] fix(setup): enforce webcam crowd labels --- scripts/build_full_dataset.py | 97 +++++++++++++++++++----- scripts/collect_historical_webcams.py | 22 ++++-- setup.sh | 18 +++-- tests/test_build_full_dataset.py | 86 +++++++++++++++++++++ tests/test_collect_historical_webcams.py | 69 +++++++++++++++++ 5 files changed, 261 insertions(+), 31 deletions(-) create mode 100644 tests/test_build_full_dataset.py create mode 100644 tests/test_collect_historical_webcams.py diff --git a/scripts/build_full_dataset.py b/scripts/build_full_dataset.py index cb9332f..9eec9f3 100644 --- a/scripts/build_full_dataset.py +++ b/scripts/build_full_dataset.py @@ -7,7 +7,7 @@ Steps: 4. Merge weather + station data on (date, station_id) 5. Run feature engineering 6. Save the merged and featured datasets to SQLite -7. Train ML models +7. Train ML models (unless --skip-training is passed) Column mapping from infonieve schema to project schema: closedflag / idestado -> open_status (1=open, 0=closed) @@ -15,10 +15,11 @@ Column mapping from infonieve schema to project schema: pistasopen -> lifts_open (actually slopes, but matches schema) espesormax -> snow_depth calidadnieve -> snow_quality - pistasopen/pistastotal ratio -> crowd_level (low/medium/high) + crowd_analysis table -> crowd_level (low/medium/high) when available open_status + km_open -> station_open (ML target alias) """ +import argparse import logging import sys from datetime import date, timedelta @@ -60,9 +61,7 @@ logger = logging.getLogger(__name__) WEATHER_START_YEAR = 2009 WEATHER_END_YEAR = 2026 # inclusive -# Crowd level thresholds based on pistas open / pistas total ratio -CROWD_LOW_THRESHOLD = 0.33 -CROWD_HIGH_THRESHOLD = 0.67 +VALID_CROWD_LEVELS = {"low", "medium", "high"} # Station coordinates from config/stations.yaml STATIONS = { @@ -71,6 +70,42 @@ STATIONS = { "sanisidro": {"latitude": 43.0700, "longitude": -5.3700}, } + +def _load_webcam_crowd_labels(store: SQLiteStore) -> pd.DataFrame: + """Load one historical webcam crowd label per (date, station_id). + + If multiple webcam analyses exist for the same station-day, keep the latest + one by ``analyzed_at``. + """ + crowd_df = store.load_crowd_analyses() + if crowd_df.empty: + logger.info("No rows found in crowd_analysis; crowd labels will be missing.") + return pd.DataFrame(columns=["date", "station_id", "webcam_crowd_level"]) + + valid = crowd_df[crowd_df["crowd_density"].isin(VALID_CROWD_LEVELS)].copy() + if valid.empty: + logger.info( + "No valid webcam crowd labels found (only unknown/missing values)." + ) + return pd.DataFrame(columns=["date", "station_id", "webcam_crowd_level"]) + + valid["date"] = pd.to_datetime(valid["analysis_date"], errors="coerce") + valid["analyzed_at"] = pd.to_datetime(valid["analyzed_at"], errors="coerce") + valid = valid.dropna(subset=["date", "station_id", "crowd_density"]) + valid = valid.sort_values(["station_id", "date", "analyzed_at"]) + valid = valid.drop_duplicates(subset=["station_id", "date"], keep="last") + + labels = valid[["date", "station_id", "crowd_density"]].rename( + columns={"crowd_density": "webcam_crowd_level"} + ) + logger.info( + "Loaded %d valid webcam labels across %d station-days.", + len(valid), + len(labels), + ) + return labels + + # --------------------------------------------------------------------------- # Step 1: Load and map station data # --------------------------------------------------------------------------- @@ -134,19 +169,22 @@ def load_station_data(store: SQLiteStore) -> pd.DataFrame: df["snow_quality"] = df["calidadnieve"].astype(str) df.loc[df["snow_quality"] == "nan", "snow_quality"] = None - # ---------- crowd_level ---------- - # Derived from fraction of slopes open vs total available - pistastotal = pd.to_numeric(df["pistastotal"], errors="coerce") - pistasopen = pd.to_numeric(df["pistasopen"], errors="coerce") - ratio = pistasopen / pistastotal.replace(0, float("nan")) + webcam_labels = _load_webcam_crowd_labels(store) + if webcam_labels.empty: + df["webcam_crowd_level"] = None + else: + df = df.merge(webcam_labels, on=["date", "station_id"], how="left") - crowd = pd.Series(index=df.index, dtype="object") - crowd[ratio < CROWD_LOW_THRESHOLD] = "low" - crowd[(ratio >= CROWD_LOW_THRESHOLD) & (ratio < CROWD_HIGH_THRESHOLD)] = "medium" - crowd[ratio >= CROWD_HIGH_THRESHOLD] = "high" - # Only assign crowd_level when the station is open + # ---------- crowd_level ---------- + # Crowd labels are sourced strictly from webcam analysis. + # We only keep labels for days where the station is open. + open_mask = df["open_status"] == 1 df["crowd_level"] = None - df.loc[df["open_status"] == 1, "crowd_level"] = crowd[df["open_status"] == 1] + df["crowd_level_source"] = None + + webcam_mask = open_mask & df["webcam_crowd_level"].isin(VALID_CROWD_LEVELS) + df.loc[webcam_mask, "crowd_level"] = df.loc[webcam_mask, "webcam_crowd_level"] + df.loc[webcam_mask, "crowd_level_source"] = "webcam" # Keep only the columns needed for merging keep = [ @@ -155,6 +193,7 @@ def load_station_data(store: SQLiteStore) -> pd.DataFrame: "km_open", "lifts_open", "snow_depth", "snow_quality", "crowd_level", + "crowd_level_source", ] result = df[keep].copy() result = result.sort_values(["station_id", "date"]).reset_index(drop=True) @@ -168,6 +207,10 @@ def load_station_data(store: SQLiteStore) -> pd.DataFrame: "crowd_level distribution:\n%s", result["crowd_level"].value_counts(), ) + logger.info( + "crowd_level source distribution:\n%s", + result["crowd_level_source"].fillna("missing").value_counts(), + ) return result @@ -376,7 +419,7 @@ def print_summary(df: pd.DataFrame) -> None: # Main # --------------------------------------------------------------------------- -def main() -> None: +def main(*, skip_training: bool = False) -> None: logger.info("Starting full dataset build pipeline.") store = SQLiteStore() @@ -398,6 +441,11 @@ def main() -> None: # Step 6: Summary print_summary(featured) + if skip_training: + logger.info("Skipping model training (--skip-training).") + logger.info("Pipeline complete (dataset only).") + return + # Step 7: Train models logger.info("Starting model training on the full dataset.") trainer = ModelTrainer(store=store, dataset_table=HISTORICAL_FEATURED_TABLE) @@ -414,5 +462,18 @@ def main() -> None: logger.info("Pipeline complete.") +def _parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Build historical datasets and optionally train ML models.", + ) + parser.add_argument( + "--skip-training", + action="store_true", + help="Build and store datasets but skip model training.", + ) + return parser.parse_args() + + if __name__ == "__main__": - main() + args = _parse_args() + main(skip_training=args.skip_training) diff --git a/scripts/collect_historical_webcams.py b/scripts/collect_historical_webcams.py index e9ff3f3..e0ae68b 100644 --- a/scripts/collect_historical_webcams.py +++ b/scripts/collect_historical_webcams.py @@ -204,7 +204,10 @@ class HistoricalWebcamCollector: if crowd_df.empty: existing_dates = set() else: - existing_dates = set(pd.to_datetime(crowd_df["timestamp"]).dt.date) + existing_dates = set( + pd.to_datetime(crowd_df["analysis_date"], errors="coerce") + .dt.date.dropna() + ) # 4. Missing is the difference missing = sorted(list(station_dates - existing_dates)) @@ -215,10 +218,11 @@ class HistoricalWebcamCollector: df = self.store.load_crowd_analyses(station_id=station_id) if df.empty: return False - - # Convert timestamp strings to date objects - df['date_only'] = pd.to_datetime(df['timestamp']).dt.date - return day in df['date_only'].values + + processed_dates = set( + pd.to_datetime(df["analysis_date"], errors="coerce").dt.date.dropna() + ) + return day in processed_dates def process_day(self, station_id: str, day: date): """Download and analyze a single snapshot for one day.""" @@ -292,14 +296,18 @@ def main(): collector = HistoricalWebcamCollector() stations = args.stations.split(",") if args.stations else None - if args.auto: + if args.auto or (not args.start_date and not args.end_date): + if not args.auto: + logger.info( + "No date range provided; defaulting to automatic sync mode." + ) collector.auto_sync(stations) elif args.start_date and args.end_date: start_date = datetime.strptime(args.start_date, "%Y-%m-%d").date() end_date = datetime.strptime(args.end_date, "%Y-%m-%d").date() collector.process_range(start_date, end_date, stations) else: - parser.print_help() + parser.error("Use --auto or provide both --start-date and --end-date.") if __name__ == "__main__": main() diff --git a/setup.sh b/setup.sh index 8b0f9d4..dbfea4c 100755 --- a/setup.sh +++ b/setup.sh @@ -4,8 +4,8 @@ # Usage: ./setup.sh # # This script sets up the environment, downloads historical data, -# and trains the ML models. After running it, start the unified -# daemon with: +# performs historical webcam crowd analysis, and trains ML models. +# After running it, start the unified daemon with: # # source .venv/bin/activate # export TELEGRAM_BOT_TOKEN='your_token' @@ -57,16 +57,22 @@ if [ -f "$ENV_FILE" ]; then fi # --------------------------------------------------------------- -# 4. Download historical station data + weather + train models +# 4. Build historical station+weather datasets (no training yet) # --------------------------------------------------------------- -info "Building full dataset (station history + weather + feature engineering + training)..." -"$PYTHON" -m scripts.build_full_dataset +info "Building full dataset (station history + weather + feature engineering, no training)..." +"$PYTHON" -m scripts.build_full_dataset --skip-training # --------------------------------------------------------------- # 5. Download historical webcam images + crowd detection # --------------------------------------------------------------- info "Collecting historical webcam snapshots and crowd analysis..." -"$PYTHON" -m scripts.collect_historical_webcams +"$PYTHON" -m scripts.collect_historical_webcams --auto + +# --------------------------------------------------------------- +# 6. Rebuild featured dataset with webcam labels (if available) + train models +# --------------------------------------------------------------- +info "Rebuilding dataset and training models..." +"$PYTHON" -m scripts.build_full_dataset # --------------------------------------------------------------- # Summary diff --git a/tests/test_build_full_dataset.py b/tests/test_build_full_dataset.py new file mode 100644 index 0000000..b2934f8 --- /dev/null +++ b/tests/test_build_full_dataset.py @@ -0,0 +1,86 @@ +"""Tests for scripts/build_full_dataset.py crowd-label logic.""" + +from __future__ import annotations + +import pandas as pd + +from scripts.build_full_dataset import _load_webcam_crowd_labels, load_station_data + + +class _FakeStore: + """Minimal store stub for dataset-builder tests.""" + + def __init__(self, station_df: pd.DataFrame, crowd_df: pd.DataFrame): + self._station_df = station_df + self._crowd_df = crowd_df + + def load_historical_station_raw(self) -> pd.DataFrame: + return self._station_df.copy() + + def load_crowd_analyses(self, **_: object) -> pd.DataFrame: + return self._crowd_df.copy() + + +def _station_raw_row() -> pd.DataFrame: + return pd.DataFrame( + { + "date": ["2026-03-10"], + "station_id": ["pajares"], + "idestado": [1.0], + "kmopen": [20.0], + "pistasopen": [30.0], + "pistastotal": [40.0], + "espesormax": [120.0], + "calidadnieve": ["polvo"], + } + ) + + +def test_crowd_level_is_sourced_from_webcam_labels(): + """Crowd labels must be read from crowd_analysis data.""" + crowd_df = pd.DataFrame( + { + "analyzed_at": ["2026-03-10T10:00:00"], + "analysis_date": ["2026-03-10"], + "station_id": ["pajares"], + "crowd_density": ["low"], + } + ) + store = _FakeStore(_station_raw_row(), crowd_df) + + result = load_station_data(store) + + assert result.iloc[0]["crowd_level"] == "low" + assert result.iloc[0]["crowd_level_source"] == "webcam" + + +def test_crowd_level_is_missing_when_webcam_label_is_missing(): + """Without webcam data, crowd labels must remain null.""" + store = _FakeStore(_station_raw_row(), pd.DataFrame()) + + result = load_station_data(store) + + assert pd.isna(result.iloc[0]["crowd_level"]) + assert pd.isna(result.iloc[0]["crowd_level_source"]) + + +def test_load_webcam_labels_keeps_latest_valid_label_per_day(): + """The latest valid label must be used when multiple rows exist per day.""" + crowd_df = pd.DataFrame( + { + "analyzed_at": [ + "2026-03-10T09:00:00", + "2026-03-10T10:00:00", + "2026-03-10T11:00:00", + ], + "analysis_date": ["2026-03-10", "2026-03-10", "2026-03-10"], + "station_id": ["pajares", "pajares", "pajares"], + "crowd_density": ["low", "medium", "unknown"], + } + ) + store = _FakeStore(_station_raw_row(), crowd_df) + + labels = _load_webcam_crowd_labels(store) + + assert len(labels) == 1 + assert labels.iloc[0]["webcam_crowd_level"] == "medium" diff --git a/tests/test_collect_historical_webcams.py b/tests/test_collect_historical_webcams.py new file mode 100644 index 0000000..4746dec --- /dev/null +++ b/tests/test_collect_historical_webcams.py @@ -0,0 +1,69 @@ +"""Unit tests for scripts/collect_historical_webcams.py.""" + +from __future__ import annotations + +from datetime import date + +import pandas as pd + +from scripts.collect_historical_webcams import HistoricalWebcamCollector + + +class _StoreStub: + """Minimal store stub for historical webcam collector tests.""" + + def __init__(self, station_df: pd.DataFrame, crowd_df: pd.DataFrame): + self._station_df = station_df + self._crowd_df = crowd_df + + def read_dataframe(self, *_: object, **__: object) -> pd.DataFrame: + return self._station_df.copy() + + def load_crowd_analyses(self, **_: object) -> pd.DataFrame: + return self._crowd_df.copy() + + +def _collector_with_store(store: _StoreStub) -> HistoricalWebcamCollector: + collector = object.__new__(HistoricalWebcamCollector) + collector.store = store + collector.get_available_date_range = lambda _station_id: None + return collector + + +def test_get_missing_dates_uses_analysis_date_column(): + """Missing-date detection must use analysis_date instead of timestamp.""" + station_df = pd.DataFrame( + { + "date": pd.to_datetime(["2026-03-10", "2026-03-11", "2026-03-12"]), + "station_id": ["pajares", "pajares", "pajares"], + } + ) + crowd_df = pd.DataFrame( + { + "analysis_date": ["2026-03-10", "2026-03-11"], + "station_id": ["pajares", "pajares"], + } + ) + collector = _collector_with_store(_StoreStub(station_df, crowd_df)) + + missing = collector.get_missing_dates("pajares") + + assert missing == [date(2026, 3, 12)] + + +def test_is_already_processed_uses_analysis_date_column(): + """Processed-day checks must match against analysis_date values.""" + collector = _collector_with_store( + _StoreStub( + station_df=pd.DataFrame(), + crowd_df=pd.DataFrame( + { + "analysis_date": ["2026-03-10"], + "station_id": ["pajares"], + } + ), + ) + ) + + assert collector._is_already_processed("pajares", date(2026, 3, 10)) + assert not collector._is_already_processed("pajares", date(2026, 3, 11))