diff --git a/app/api/routes.py b/app/api/routes.py index 908e088..96790b4 100644 --- a/app/api/routes.py +++ b/app/api/routes.py @@ -243,6 +243,8 @@ def _rows_to_day_forecasts( km_open=r.get("km_open"), max_km=max_km, crowd_level=r.get("crowd_level"), + sky_condition=r.get("sky_condition"), + snow_type=r.get("snow_type"), weather_summary=r.get("weather_summary"), rule_notes=notes, prediction_source=r.get("prediction_source"), diff --git a/app/api/schemas.py b/app/api/schemas.py index d370938..235faaa 100644 --- a/app/api/schemas.py +++ b/app/api/schemas.py @@ -31,6 +31,8 @@ class DayForecast(BaseModel): km_open: float | None = None max_km: float | None = None crowd_level: str | None = None + sky_condition: str | None = None + snow_type: str | None = None weather_summary: str | None = None rule_notes: list[str] = Field(default_factory=list) prediction_source: str | None = None diff --git a/app/scheduler/tasks.py b/app/scheduler/tasks.py index 24cefb7..4b0b240 100644 --- a/app/scheduler/tasks.py +++ b/app/scheduler/tasks.py @@ -173,6 +173,8 @@ def _run_forecast_core( "open_probability": result["open_probability"], "km_open": result["km_open"], "crowd_level": result["crowd_level"], + "sky_condition": result.get("sky_condition"), + "snow_type": result.get("snow_type"), "weather_summary": result.get("weather_summary"), "rule_notes": result.get("rule_overrides", []), "prediction_source": result["prediction_source"], diff --git a/bot/telegram_bot.py b/bot/telegram_bot.py index ba39a2c..e2afdc0 100644 --- a/bot/telegram_bot.py +++ b/bot/telegram_bot.py @@ -147,6 +147,8 @@ def _forecasts_to_payload( "open_probability": row.get("open_probability"), "km_open": row.get("km_open"), "crowd_level": row.get("crowd_level"), + "sky_condition": row.get("sky_condition"), + "snow_type": row.get("snow_type"), "weather_summary": row.get("weather_summary"), "rule_overrides": json.loads(row["rule_notes_json"] or "[]") if isinstance(row.get("rule_notes_json"), str) @@ -304,6 +306,17 @@ def format_station_prediction( crowd_str = _crowd_label(crowd_raw) km_str = f"{km_open:.1f} / {max_km:.1f}" + sky_condition = prediction.get("sky_condition") + snow_type = prediction.get("snow_type") + + sky_block = "" + if sky_condition and sky_condition != "desconocido": + sky_block = f"Cielo: {sky_condition.capitalize()}\n" + + snow_type_block = "" + if snow_type and snow_type != "desconocido": + snow_type_block = f"Tipo de nieve: {snow_type.capitalize()}\n" + weather_block = "" if weather_summary: weather_block = f"\nTiempo previsto:\n{weather_summary}\n" @@ -321,6 +334,8 @@ def format_station_prediction( f"Estado: {open_str}\n" f"Km esquiables: {km_str}\n" f"Nivel de afluencia: {crowd_str}\n" + f"{sky_block}" + f"{snow_type_block}" f"{weather_block}" f"{reasons_block}" f"\nFuente: {source}" diff --git a/config/features.yaml b/config/features.yaml index 929a1a8..ef4c531 100644 --- a/config/features.yaml +++ b/config/features.yaml @@ -9,6 +9,7 @@ weather_variables: - wind_direction_10m_dominant - relative_humidity_2m_mean - surface_pressure_mean + - weather_code engineered_features: - snow_last_3_days diff --git a/data_sources/weather_api.py b/data_sources/weather_api.py index f19b3ea..31b83ee 100644 --- a/data_sources/weather_api.py +++ b/data_sources/weather_api.py @@ -39,8 +39,48 @@ DAILY_VARIABLES = [ "wind_direction_10m_dominant", "relative_humidity_2m_mean", "surface_pressure_mean", + "weather_code", ] +# WMO Weather Code to sky condition mapping (Spanish labels). +_WMO_SKY_CONDITIONS: dict[int, str] = { + 0: "soleado", + 1: "soleado", + 2: "parcialmente nublado", + 3: "nublado", + 45: "niebla", + 48: "niebla", + 51: "nublado", + 53: "nublado", + 55: "nublado", + 56: "nublado", + 57: "nublado", + 61: "nublado", + 63: "nublado", + 65: "nublado", + 66: "nublado", + 67: "nublado", + 71: "nublado con nieve", + 73: "nublado con nieve", + 75: "nublado con nieve", + 77: "nublado con nieve", + 80: "nublado", + 81: "nublado", + 82: "nublado", + 85: "nublado con nieve", + 86: "nublado con nieve", + 95: "tormenta", + 96: "tormenta", + 99: "tormenta", +} + + +def wmo_code_to_sky_condition(code: int | float | None) -> str: + """Convert a WMO weather code to a Spanish sky condition label.""" + if code is None: + return "desconocido" + return _WMO_SKY_CONDITIONS.get(int(code), "desconocido") + MAX_RETRIES = 6 RETRY_BACKOFF = 2 # seconds between retries diff --git a/pipeline/build_dataset.py b/pipeline/build_dataset.py index 3b3c92d..44c3c87 100644 --- a/pipeline/build_dataset.py +++ b/pipeline/build_dataset.py @@ -33,6 +33,7 @@ _INTERPOLATABLE_WEATHER_COLS = [ "wind_direction_10m_dominant", "relative_humidity_2m_mean", "surface_pressure_mean", + "weather_code", ] # Station operational columns are TARGET variables for ML and must NEVER diff --git a/predictor/hybrid_predictor.py b/predictor/hybrid_predictor.py index 127e648..8f23d0f 100644 --- a/predictor/hybrid_predictor.py +++ b/predictor/hybrid_predictor.py @@ -64,8 +64,15 @@ def _build_weather_summary(weather_data: dict[str, Any]) -> str: A single-line string summarising the most operationally relevant weather factors present in the data. """ + from data_sources.weather_api import wmo_code_to_sky_condition + parts: list[str] = [] + weather_code = weather_data.get("weather_code") + if weather_code is not None: + sky = wmo_code_to_sky_condition(weather_code) + parts.append(sky.capitalize()) + temp_max = weather_data.get("temperature_2m_max") temp_min = weather_data.get("temperature_2m_min") if temp_max is not None and temp_min is not None: @@ -181,8 +188,12 @@ class HybridPredictor: Raises: ValueError: If station_id is not found in the configuration. """ + from data_sources.weather_api import wmo_code_to_sky_condition + station_name = _load_station_name(station_id, self._config_path) weather_summary = _build_weather_summary(weather_data) + sky_condition = wmo_code_to_sky_condition(weather_data.get("weather_code")) + snow_type = self._infer_snow_type(weather_data) logger.info("HybridPredictor.predict called for station '%s'.", station_name) @@ -238,6 +249,8 @@ class HybridPredictor: "open_probability": round(open_probability, 4), "km_open": round(km_open, 2), "crowd_level": crowd_level, + "sky_condition": sky_condition, + "snow_type": snow_type, "weather_summary": weather_summary, "rule_overrides": rule_reasons, "prediction_source": prediction_source, @@ -450,3 +463,42 @@ class HybridPredictor: exc, ) return 10.0 + + @staticmethod + def _infer_snow_type(weather_data: dict[str, Any]) -> str: + """Infer snow type from weather conditions. + + Uses temperature, snowfall and humidity to estimate snow quality: + - Cold temp + fresh snow = "polvo" (powder) + - Warm temp + snow = "humeda" (wet) + - Very cold + no fresh snow = "dura" (hard/icy) + - Warm temp + no fresh snow = "primavera" (spring) + + If the Infonieve ``calidadnieve`` field is present it is used directly. + + Args: + weather_data: Dict of weather variables for the prediction day. + + Returns: + A snow type label in Spanish (e.g. ``"polvo"``, ``"dura"``). + """ + # If Infonieve provided snow quality directly, use it + if weather_data.get("calidadnieve"): + return str(weather_data["calidadnieve"]).lower() + + temp_max = weather_data.get("temperature_2m_max") + snowfall = weather_data.get("snowfall_sum", 0) or 0 + + if temp_max is None: + return "desconocido" + + if snowfall > 0: + if temp_max < 0: + return "polvo" + return "húmeda" + + if temp_max < -2: + return "dura" + if temp_max > 8: + return "primavera" + return "dura" diff --git a/scripts/collect_daily_data.py b/scripts/collect_daily_data.py index 68091cc..0d8dcc2 100644 --- a/scripts/collect_daily_data.py +++ b/scripts/collect_daily_data.py @@ -361,6 +361,8 @@ def generate_predictions( "open_probability": result["open_probability"], "km_open": result["km_open"], "crowd_level": result["crowd_level"], + "sky_condition": result.get("sky_condition"), + "snow_type": result.get("snow_type"), "weather_summary": result.get("weather_summary"), "rule_notes": result.get("rule_overrides", []), "prediction_source": result["prediction_source"], diff --git a/storage/sqlite_store.py b/storage/sqlite_store.py index 8493409..fe64c2f 100644 --- a/storage/sqlite_store.py +++ b/storage/sqlite_store.py @@ -62,6 +62,7 @@ _WEATHER_COLUMNS: list[str] = [ "wind_direction_10m_dominant", "relative_humidity_2m_mean", "surface_pressure_mean", + "weather_code", ] @@ -398,9 +399,10 @@ class SQLiteStore: INSERT INTO {CURRENT_FORECASTS_TABLE} ( generated_at, run_hour, station_id, prediction_date, open_probability, km_open, crowd_level, + sky_condition, snow_type, weather_summary, rule_notes_json, prediction_source ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, [ ( @@ -411,6 +413,8 @@ class SQLiteStore: self._coerce_float(f.get("open_probability")), self._coerce_float(f.get("km_open")), f.get("crowd_level"), + f.get("sky_condition"), + f.get("snow_type"), f.get("weather_summary"), json.dumps(f.get("rule_notes") or [], ensure_ascii=False), f.get("prediction_source"), @@ -430,11 +434,13 @@ class SQLiteStore: INSERT INTO {PAST_FORECASTS_TABLE} ( generated_at, run_hour, station_id, prediction_date, open_probability, km_open, crowd_level, + sky_condition, snow_type, weather_summary, rule_notes_json, prediction_source ) SELECT generated_at, run_hour, station_id, prediction_date, open_probability, km_open, crowd_level, + sky_condition, snow_type, weather_summary, rule_notes_json, prediction_source FROM {CURRENT_FORECASTS_TABLE} """ @@ -649,6 +655,8 @@ class SQLiteStore: open_probability REAL, km_open REAL, crowd_level TEXT, + sky_condition TEXT, + snow_type TEXT, weather_summary TEXT, rule_notes_json TEXT, prediction_source TEXT @@ -663,6 +671,8 @@ class SQLiteStore: open_probability REAL, km_open REAL, crowd_level TEXT, + sky_condition TEXT, + snow_type TEXT, weather_summary TEXT, rule_notes_json TEXT, prediction_source TEXT