mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
fix(setup): enforce webcam crowd labels
This commit is contained in:
1 parent
f6a65f41d9
commit
f63913b23c
5 files changed
+261
-31
No files matched your search
@@ -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)
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user