"""Dataset builder for the ski predictor pipeline. Loads raw weather CSVs and station JSONs, merges them on date and station_id, handles missing data, and writes a processed dataset to disk. """ import glob import json import logging from pathlib import Path from typing import Optional import pandas as pd logger = logging.getLogger(__name__) # Paths are relative to the repository root. _REPO_ROOT = Path(__file__).resolve().parents[1] _RAW_DIR = _REPO_ROOT / "data" / "raw" _PROCESSED_DIR = _REPO_ROOT / "data" / "processed" # 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 # with forward-fill only (e.g. station metadata). _INTERPOLATABLE_WEATHER_COLS = [ "temperature_2m_max", "temperature_2m_min", "temperature_2m_mean", "precipitation_sum", "snowfall_sum", "wind_speed_10m_max", "wind_gusts_10m_max", "wind_direction_10m_dominant", "relative_humidity_2m_mean", "surface_pressure_mean", ] # Station operational columns are TARGET variables for ML and must NEVER # be forward-filled or interpolated. Missing values mean we have no # observation for that date and should remain as NaN. _STATION_TARGET_COLS = [ "open_status", "km_open", "lifts_open", "snow_depth", "snow_quality", ] class DatasetBuilder: """Merges raw weather and station data into a single processed dataset. Raw weather data is expected as CSV files matching the glob pattern ``data/raw/weather_*.csv``. Raw station data is expected as JSON files matching ``data/raw/station_*.json``. Both sources must contain a ``date`` column (or key) and a ``station_id`` column (or key). They are merged on ``(date, station_id)``. Parameters ---------- raw_dir: Directory that contains the raw input files. Defaults to ``/data/raw``. processed_dir: Directory where the processed dataset is written. Defaults to ``/data/processed``. """ def __init__( self, raw_dir: Optional[Path] = None, processed_dir: Optional[Path] = None, ) -> None: self.raw_dir = Path(raw_dir) if raw_dir else _RAW_DIR self.processed_dir = Path(processed_dir) if processed_dir else _PROCESSED_DIR # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def build(self) -> pd.DataFrame: """Run the full build pipeline and persist the result. Reads all raw weather CSVs and station JSONs, merges them, fills missing values and saves the result to ``data/processed/dataset.csv``. Returns ------- pd.DataFrame The fully merged and cleaned dataset. """ logger.info("Starting full dataset build.") weather_df = self._load_weather_csvs() station_df = self._load_station_jsons() 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) merged = self._handle_missing(merged) self._save(merged) logger.info("Dataset build complete. Rows: %d", len(merged)) return merged def append_daily( self, weather_data: dict | pd.DataFrame, station_data: dict | pd.DataFrame, ) -> 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. 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). """ 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) existing = self._load_existing_dataset() # Normalize date columns to pd.Timestamp before concat to avoid # mixed-type sort errors (datetime.date vs Timestamp). 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) ) return combined # ------------------------------------------------------------------ # Private helpers – loading # ------------------------------------------------------------------ def _load_weather_csvs(self) -> pd.DataFrame: """Load and concatenate all ``weather_*.csv`` files from raw_dir.""" pattern = str(self.raw_dir / "weather_*.csv") files = sorted(glob.glob(pattern)) if not files: logger.warning("No weather CSV files found at %s.", pattern) return pd.DataFrame() frames = [] for path in files: logger.debug("Reading weather file: %s", path) try: df = pd.read_csv(path) frames.append(df) except Exception as exc: logger.error("Failed to read %s: %s", path, exc) if not frames: return pd.DataFrame() combined = pd.concat(frames, ignore_index=True) combined["date"] = pd.to_datetime(combined["date"]) logger.info("Loaded %d weather rows from %d file(s).", len(combined), len(files)) return combined def _load_station_jsons(self) -> pd.DataFrame: """Load and concatenate all ``station_*.json`` files from raw_dir.""" pattern = str(self.raw_dir / "station_*.json") files = sorted(glob.glob(pattern)) if not files: logger.warning("No station JSON files found at %s.", pattern) return pd.DataFrame() frames = [] for path in files: logger.debug("Reading station file: %s", path) try: with open(path, "r", encoding="utf-8") as fh: raw = json.load(fh) # Accept either a single record (dict) or a list of records. if isinstance(raw, dict): raw = [raw] df = pd.DataFrame(raw) frames.append(df) except Exception as exc: logger.error("Failed to read %s: %s", path, exc) if not frames: return pd.DataFrame() combined = pd.concat(frames, ignore_index=True) combined["date"] = pd.to_datetime(combined["date"]) logger.info( "Loaded %d station rows from %d file(s).", len(combined), len(files) ) return combined def _load_existing_dataset(self) -> pd.DataFrame: """Return the persisted processed dataset, or an empty DataFrame.""" 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) return pd.DataFrame() # ------------------------------------------------------------------ # Private helpers – merging and cleaning # ------------------------------------------------------------------ def _merge( self, weather_df: pd.DataFrame, station_df: pd.DataFrame ) -> pd.DataFrame: """Outer-merge weather and station frames on (date, station_id). An outer merge is used so that rows present in only one source are still retained (with NaN in the missing columns). This allows the missing-data handler to fill or interpolate the gaps. """ if weather_df.empty and station_df.empty: return pd.DataFrame() if weather_df.empty: logger.warning( "Weather data is empty; returning station data only." ) return station_df.copy() if station_df.empty: logger.warning( "Station data is empty; returning weather data only." ) return weather_df.copy() merged = pd.merge( weather_df, station_df, on=["date", "station_id"], how="outer", ) merged = merged.sort_values(["station_id", "date"]).reset_index(drop=True) logger.debug("Merged dataset shape: %s", merged.shape) return merged def _handle_missing(self, df: pd.DataFrame) -> pd.DataFrame: """Fill or interpolate missing values. Strategy per column type: - Interpolatable numeric weather columns: linear interpolation, then forward-fill for leading/trailing NaNs. - All other numeric columns: forward-fill then backward-fill. - Non-numeric columns: forward-fill within each station group. """ if df.empty: return df result = df.copy() # Interpolate known numeric weather variables within each station group. weather_cols_present = [ c for c in _INTERPOLATABLE_WEATHER_COLS if c in result.columns ] if weather_cols_present: result[weather_cols_present] = ( result.groupby("station_id", group_keys=False)[weather_cols_present] .apply( lambda g: g.interpolate(method="linear", limit_direction="both") ) ) # Forward-fill / backward-fill remaining numeric columns, # but NEVER fill station target columns (those are real observations). numeric_cols = result.select_dtypes(include="number").columns.tolist() remaining_numeric = [ c for c in numeric_cols if c not in weather_cols_present and c not in _STATION_TARGET_COLS ] if remaining_numeric: result[remaining_numeric] = ( result.groupby("station_id", group_keys=False)[remaining_numeric] .apply(lambda g: g.ffill().bfill()) ) # Forward-fill non-numeric columns (e.g. station name, categorical fields), # but NEVER fill station target columns. non_numeric_cols = result.select_dtypes(exclude="number").columns.tolist() skip_cols = {"date"} | set(_STATION_TARGET_COLS) fill_non_numeric = [ c for c in non_numeric_cols if c not in skip_cols ] if fill_non_numeric: result[fill_non_numeric] = ( result.groupby("station_id", group_keys=False)[fill_non_numeric] .apply(lambda g: g.ffill()) ) missing_after = result.isnull().sum().sum() if missing_after > 0: logger.warning( "%d missing values remain after imputation.", missing_after ) return result # ------------------------------------------------------------------ # Private helpers – persistence # ------------------------------------------------------------------ def _save(self, df: pd.DataFrame) -> None: """Write dataset to ``data/processed/dataset.csv``.""" self.processed_dir.mkdir(parents=True, exist_ok=True) output_path = self.processed_dir / "dataset.csv" df.to_csv(output_path, index=False) logger.info("Dataset saved to %s.", output_path) # ------------------------------------------------------------------ # Private helpers – type coercion # ------------------------------------------------------------------ @staticmethod def _to_dataframe(data: dict | pd.DataFrame) -> pd.DataFrame: """Coerce a dict or DataFrame to a one-row DataFrame.""" if isinstance(data, pd.DataFrame): return data.copy() return pd.DataFrame([data])