feat: initial ski predictor system

Hybrid ML + rules prediction system for 3 Asturian ski stations
(Pajares, San Isidro, Fuentes de Invierno).

- Weather data from Open-Meteo (historical + forecast)
- Station scraping from infonieve.es (live + 16 seasons historical TSV)
- Feature engineering: rolling snow, calendar, temperature/pressure trends
- ML models: RandomForest (open/close), GradientBoosting (km), LightGBM (crowd)
- Rules engine: wind closure, snow depth, rain+heat, heavy snow
- YOLOv8 webcam crowd detection (cars, people in parking/lifts)
- Telegram bot with /pajares, /sanisidro, /fuentes commands
- Daily cron pipeline for automated data collection and predictions
- Deployment guide with systemd service and cron setup
This commit is contained in:
dasemu committed 2026-03-12 14:51:32 +01:00
commit 1afe2b73e0
34 files changed
+7201

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
"""Pipeline package for ski predictor.
Modules:
build_dataset: Merges raw weather and station data into a processed dataset.
feature_engineering: Derives ML-ready features from the merged dataset.
"""
+361
View File
@@ -0,0 +1,361 @@
"""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
import os
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"
_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
# 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
``<repo_root>/data/raw``.
processed_dir:
Directory where the processed dataset is written. Defaults to
``<repo_root>/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."""
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])
+397
View File
@@ -0,0 +1,397 @@
"""Feature engineering for the ski predictor pipeline.
Derives temporal, rolling, and calendar features from a merged weather +
station DataFrame to produce an ML-ready feature set.
"""
import logging
from pathlib import Path
from typing import Optional
import numpy as np
import pandas as pd
import yaml
logger = logging.getLogger(__name__)
_REPO_ROOT = Path(__file__).resolve().parents[1]
_DEFAULT_FEATURES_CONFIG = _REPO_ROOT / "config" / "features.yaml"
# Spanish national public holidays (month, day). Regional holidays for
# Asturias (where all three target stations are located) are also included.
_SPANISH_HOLIDAYS: set[tuple[int, int]] = {
# National
(1, 1), # New Year's Day
(1, 6), # Epiphany
(5, 1), # Labour Day
(8, 15), # Assumption of Mary
(10, 12), # National Day of Spain
(11, 1), # All Saints' Day
(12, 6), # Constitution Day
(12, 8), # Immaculate Conception
(12, 25), # Christmas Day
# Asturian regional
(9, 8), # Day of Asturias
}
# Approximate Good Friday dates for years 2018-2035 (moveable feast).
# Keyed by year, value is (month, day).
_GOOD_FRIDAY: dict[int, tuple[int, int]] = {
2018: (3, 30),
2019: (4, 19),
2020: (4, 10),
2021: (4, 2),
2022: (4, 15),
2023: (4, 7),
2024: (3, 29),
2025: (4, 18),
2026: (4, 3),
2027: (3, 26),
2028: (4, 14),
2029: (3, 30),
2030: (4, 19),
2031: (4, 11),
2032: (3, 26),
2033: (4, 15),
2034: (4, 7),
2035: (3, 23),
}
def _build_holiday_set(years: Optional[list[int]] = None) -> set[pd.Timestamp]:
"""Return a set of Timestamps for every known holiday across the given years.
Parameters
----------
years:
Calendar years to include. Defaults to 2018-2035.
"""
if years is None:
years = list(range(2018, 2036))
holidays: set[pd.Timestamp] = set()
for year in years:
for month, day in _SPANISH_HOLIDAYS:
try:
holidays.add(pd.Timestamp(year=year, month=month, day=day))
except ValueError:
pass
gf = _GOOD_FRIDAY.get(year)
if gf:
holidays.add(pd.Timestamp(year=year, month=gf[0], day=gf[1]))
return holidays
class FeatureEngineer:
"""Derives engineered features from a merged weather + station DataFrame.
All features defined in ``config/features.yaml`` under
``engineered_features`` are computed. Columns required by each feature
must be present in the input DataFrame; missing source columns are logged
as warnings and the corresponding feature is set to NaN.
Parameters
----------
config_path:
Path to the ``features.yaml`` configuration file. Defaults to
``<repo_root>/config/features.yaml``.
"""
def __init__(self, config_path: Optional[Path] = None) -> None:
self.config_path = (
Path(config_path) if config_path else _DEFAULT_FEATURES_CONFIG
)
self._config = self._load_config()
self._holidays = _build_holiday_set()
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def transform(self, df: pd.DataFrame) -> pd.DataFrame:
"""Add all engineered features to *df* and return the result.
The input DataFrame must contain at minimum:
- ``date`` (datetime-like)
- ``station_id`` (str or int)
- ``snowfall_sum`` (float) – daily snowfall in cm
- ``temperature_2m_mean`` (float) – mean temperature in degrees C
- ``wind_gusts_10m_max`` (float) – maximum wind gust in km/h
- ``surface_pressure_mean`` (float) – mean surface pressure in hPa
Parameters
----------
df:
Merged weather + station DataFrame, one row per (date, station_id).
Returns
-------
pd.DataFrame
Original DataFrame with additional feature columns appended.
"""
if df.empty:
logger.warning("Input DataFrame is empty; returning as-is.")
return df
result = df.copy()
result["date"] = pd.to_datetime(result["date"])
result = result.sort_values(["station_id", "date"]).reset_index(drop=True)
enabled = set(self._config.get("engineered_features", []))
result = self._add_rolling_snow(result, enabled)
result = self._add_rolling_temperature(result, enabled)
result = self._add_max_wind_gust(result, enabled)
result = self._add_calendar_features(result, enabled)
result = self._add_days_since_last_snowfall(result, enabled)
result = self._add_temperature_trend(result, enabled)
result = self._add_pressure_trend(result, enabled)
computed = [c for c in result.columns if c not in df.columns]
logger.info("Feature engineering complete. Added columns: %s", computed)
return result
# ------------------------------------------------------------------
# Private feature methods
# ------------------------------------------------------------------
def _add_rolling_snow(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute rolling snowfall sums over 3 and 7 days.
Features produced:
- ``snow_last_3_days``: sum of snowfall_sum over the 3 preceding days
(exclusive of the current day).
- ``snow_last_7_days``: sum of snowfall_sum over the 7 preceding days
(exclusive of the current day).
The shift-by-one before rolling ensures these features capture
antecedent conditions, which is the meaningful signal for a
next-day opening-probability model.
"""
source = "snowfall_sum"
if not self._check_source(df, source):
for feat in ("snow_last_3_days", "snow_last_7_days"):
if feat in enabled:
df[feat] = np.nan
return df
grp = df.groupby("station_id")[source]
if "snow_last_3_days" in enabled:
shifted = grp.shift(1)
df["snow_last_3_days"] = (
shifted.groupby(df["station_id"])
.transform(lambda s: s.rolling(window=3, min_periods=1).sum())
)
if "snow_last_7_days" in enabled:
shifted = grp.shift(1)
df["snow_last_7_days"] = (
shifted.groupby(df["station_id"])
.transform(lambda s: s.rolling(window=7, min_periods=1).sum())
)
return df
def _add_rolling_temperature(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute 3-day rolling mean temperature.
Feature produced:
- ``avg_temperature_3_days``: mean of temperature_2m_mean over the
3 preceding days (exclusive of the current day).
"""
feat = "avg_temperature_3_days"
if feat not in enabled:
return df
source = "temperature_2m_mean"
if not self._check_source(df, source):
df[feat] = np.nan
return df
shifted = df.groupby("station_id")[source].shift(1)
df[feat] = (
shifted.groupby(df["station_id"])
.transform(lambda s: s.rolling(window=3, min_periods=1).mean())
)
return df
def _add_max_wind_gust(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Alias the daily maximum wind gust into a consistently named feature.
Feature produced:
- ``max_wind_gust``: maximum wind gust (km/h) for the current day,
sourced directly from ``wind_gusts_10m_max``.
The raw column already represents the 24-hour maximum, so no rolling
aggregation is required.
"""
feat = "max_wind_gust"
if feat not in enabled:
return df
source = "wind_gusts_10m_max"
if not self._check_source(df, source):
df[feat] = np.nan
else:
df[feat] = df[source]
return df
def _add_calendar_features(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Add calendar-derived features.
Features produced:
- ``is_weekend``: 1 if the date falls on Saturday (5) or Sunday (6).
- ``is_holiday``: 1 if the date is a Spanish or Asturian public holiday.
- ``month_of_year``: integer month 1-12.
- ``day_of_week``: integer weekday 0 (Monday) through 6 (Sunday).
"""
dates = df["date"]
if "is_weekend" in enabled:
df["is_weekend"] = dates.dt.dayofweek.isin([5, 6]).astype(int)
if "is_holiday" in enabled:
df["is_holiday"] = dates.isin(self._holidays).astype(int)
if "month_of_year" in enabled:
df["month_of_year"] = dates.dt.month
if "day_of_week" in enabled:
df["day_of_week"] = dates.dt.dayofweek
return df
def _add_days_since_last_snowfall(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute days elapsed since the most recent snowfall event.
A snowfall event is defined as ``snowfall_sum > 0``.
Feature produced:
- ``days_since_last_snowfall``: integer count of days since the last
day with non-zero snowfall. 0 means it snowed today. NaN is used
for rows where no prior snowfall is present in the history window.
"""
feat = "days_since_last_snowfall"
if feat not in enabled:
return df
source = "snowfall_sum"
if not self._check_source(df, source):
df[feat] = np.nan
return df
def _days_since_for_group(group: pd.Series) -> pd.Series:
"""Vectorised computation for a single station's snowfall series."""
snow = group.values
result = np.full(len(snow), np.nan)
last_snow_idx: Optional[int] = None
for i, val in enumerate(snow):
if val > 0:
last_snow_idx = i
if last_snow_idx is not None:
result[i] = float(i - last_snow_idx)
return pd.Series(result, index=group.index)
df[feat] = (
df.groupby("station_id")[source]
.transform(_days_since_for_group)
)
return df
def _add_temperature_trend(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute temperature change over the last 3 days.
Feature produced:
- ``temperature_trend_3_days``: difference between today's mean
temperature and the mean temperature 3 days ago. A positive value
indicates warming; a negative value indicates cooling.
"""
feat = "temperature_trend_3_days"
if feat not in enabled:
return df
source = "temperature_2m_mean"
if not self._check_source(df, source):
df[feat] = np.nan
return df
df[feat] = (
df[source]
- df.groupby("station_id")[source].transform(lambda s: s.shift(3))
)
return df
def _add_pressure_trend(
self, df: pd.DataFrame, enabled: set
) -> pd.DataFrame:
"""Compute surface pressure change over the last 3 days.
Feature produced:
- ``pressure_trend_3_days``: difference between today's mean surface
pressure and the value 3 days ago. A positive value indicates a
rising pressure (improving conditions); a negative value indicates
a falling pressure (approaching precipitation).
"""
feat = "pressure_trend_3_days"
if feat not in enabled:
return df
source = "surface_pressure_mean"
if not self._check_source(df, source):
df[feat] = np.nan
return df
df[feat] = (
df[source]
- df.groupby("station_id")[source].transform(lambda s: s.shift(3))
)
return df
# ------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------
def _load_config(self) -> dict:
"""Load and return the features YAML configuration."""
if not self.config_path.exists():
logger.warning(
"Features config not found at %s. All features enabled by default.",
self.config_path,
)
return {}
with open(self.config_path, "r", encoding="utf-8") as fh:
config = yaml.safe_load(fh)
logger.debug("Loaded features config from %s.", self.config_path)
return config or {}
@staticmethod
def _check_source(df: pd.DataFrame, column: str) -> bool:
"""Return True if *column* exists in *df*, otherwise log a warning."""
if column not in df.columns:
logger.warning(
"Source column '%s' not found in DataFrame. "
"Dependent feature(s) will be set to NaN.",
column,
)
return False
return True