feat(crowd): add automated historical webcam collection and dataset integration

This commit is contained in:
dasemu committed 2026-03-13 10:41:57 +01:00
1 parent e952cea417
commit b4c6041eea
91 files changed
+7957 -40

No files matched your search

+61 -39
View File
@@ -44,15 +44,16 @@ _STATION_TARGET_COLS = [
"lifts_open",
"snow_depth",
"snow_quality",
"crowd_density",
]
class DatasetBuilder:
"""Merges raw weather and station data into a single processed dataset.
"""Merges raw weather, station, and crowd data into a single processed dataset.
The builder reads the latest forecast snapshot and latest station status
snapshot from SQLite, merges them on ``(date, station_id)``, and persists
the processed result into another SQLite table.
The builder reads the latest forecast snapshot, latest station status
snapshot, and crowd analysis records from SQLite, merges them on
``(date, station_id)``, and persists the processed result.
"""
def __init__(
@@ -74,9 +75,8 @@ class DatasetBuilder:
def build(self) -> pd.DataFrame:
"""Run the full build pipeline and persist the result.
Reads the latest weather and station snapshots from SQLite, merges
them, fills missing values, and saves the result to the configured
dataset table.
Reads the latest weather, station, and crowd snapshots from SQLite,
merges them, fills missing values, and saves the result.
Returns
-------
@@ -87,12 +87,26 @@ class DatasetBuilder:
weather_df = self._load_weather_snapshot()
station_df = self._load_station_snapshot()
crowd_df = self._load_crowd_density_snapshot()
if weather_df.empty and station_df.empty:
logger.warning("No raw data found. Returning empty dataset.")
return pd.DataFrame()
merged = self._merge(weather_df, station_df)
# Merge crowd data if available
if not crowd_df.empty:
merged["date"] = pd.to_datetime(merged["date"])
crowd_df["date"] = pd.to_datetime(crowd_df["date"])
merged = pd.merge(
merged,
crowd_df,
on=["date", "station_id"],
how="left"
)
logger.debug("Merged crowd data. New shape: %s", merged.shape)
merged = self._handle_missing(merged)
self._save(merged)
@@ -103,55 +117,49 @@ class DatasetBuilder:
self,
weather_data: dict | pd.DataFrame,
station_data: dict | pd.DataFrame,
crowd_data: dict | pd.DataFrame | None = None,
) -> pd.DataFrame:
"""Append a single day's data to the existing processed dataset.
Useful for daily cron-driven updates without reprocessing the full
history.
Parameters
----------
weather_data:
Either a ``dict`` (single record) or a one-row ``DataFrame``
containing weather measurements for the day.
Weather measurements for the day.
station_data:
Either a ``dict`` (single record) or a one-row ``DataFrame``
containing station operational data for the day.
Returns
-------
pd.DataFrame
The updated full dataset (existing rows + new row).
Station operational data for the day.
crowd_data:
Optional crowd analysis data for the day.
"""
weather_row = self._to_dataframe(weather_data)
station_row = self._to_dataframe(station_data)
new_row = self._merge(weather_row, station_row)
new_row = self._handle_missing(new_row)
if crowd_data is not None:
crowd_row = self._to_dataframe(crowd_data)
# Ensure date columns are compatible for merge
new_row["date"] = pd.to_datetime(new_row["date"])
crowd_row["date"] = pd.to_datetime(crowd_row["date"])
new_row = pd.merge(new_row, crowd_row, on=["date", "station_id"], how="left")
new_row = self._handle_missing(new_row)
existing = self._load_existing_dataset()
# Normalize date columns to pd.Timestamp before concat to avoid
# mixed-type sort errors (datetime.date vs Timestamp).
# Normalize date columns
new_row["date"] = pd.to_datetime(new_row["date"])
if not existing.empty:
existing["date"] = pd.to_datetime(existing["date"], format="mixed")
combined = pd.concat([existing, new_row], ignore_index=True)
# Ensure date column is uniform Timestamp after concat
combined["date"] = pd.to_datetime(combined["date"], format="mixed")
# Drop duplicate (date, station_id) pairs, keeping the latest entry.
combined = combined.drop_duplicates(
subset=["date", "station_id"], keep="last"
)
combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True)
self._save(combined)
logger.info(
"Appended daily data. Total rows: %d", len(combined)
)
logger.info("Appended daily data. Total rows: %d", len(combined))
return combined
# ------------------------------------------------------------------
@@ -176,16 +184,30 @@ class DatasetBuilder:
logger.info("Loaded %d station rows from table %s.", len(df), self.station_table)
return df
def _load_existing_dataset(self) -> pd.DataFrame:
"""Return the persisted processed dataset, or an empty DataFrame."""
df = self.store.read_dataframe(self.dataset_table, parse_dates=("date",))
if not df.empty:
logger.debug(
"Loaded existing dataset from table %s with %d rows.",
self.dataset_table,
len(df),
)
return df
def _load_crowd_density_snapshot(self) -> pd.DataFrame:
"""Load and aggregate daily crowd density levels."""
df = self.store.load_crowd_analyses()
if df.empty:
logger.info("No crowd analysis records found.")
return pd.DataFrame()
# Map density labels to numeric ranks for aggregation (max wins)
rank_map = {"low": 0, "medium": 1, "high": 2}
inv_map = {v: k for k, v in rank_map.items()}
df["date"] = pd.to_datetime(df["analysis_date"]).dt.date
df["density_rank"] = df["crowd_density"].map(rank_map).fillna(-1)
# Aggregate by taking the highest density detected in any image that day
daily = (
df.groupby(["date", "station_id"])["density_rank"]
.max()
.reset_index()
)
daily["crowd_density"] = daily["density_rank"].map(inv_map)
logger.info("Loaded crowd density for %d (date, station) pairs.", len(daily))
return daily[["date", "station_id", "crowd_density"]]
# ------------------------------------------------------------------
# Private helpers – merging and cleaning