"""Weather data collector using Open-Meteo API. Fetches historical and forecast weather data for ski stations defined in config/stations.yaml and persists snapshots in SQLite. Historical endpoint: https://archive-api.open-meteo.com/v1/archive Forecast endpoint: https://api.open-meteo.com/v1/forecast """ import logging import time from datetime import date, timedelta from pathlib import Path import pandas as pd import requests import yaml logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- BASE_DIR = Path(__file__).resolve().parent.parent CONFIG_PATH = BASE_DIR / "config" / "stations.yaml" HISTORICAL_URL = "https://archive-api.open-meteo.com/v1/archive" FORECAST_URL = "https://api.open-meteo.com/v1/forecast" # Variables requested from Open-Meteo for both endpoints. DAILY_VARIABLES = [ "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", "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 # --------------------------------------------------------------------------- # WeatherCollector # --------------------------------------------------------------------------- class WeatherCollector: """Fetches and persists weather data from Open-Meteo for ski stations. Parameters ---------- config_path: Path to the stations YAML config file. Defaults to ``config/stations.yaml`` relative to the project root. """ def __init__(self, config_path: Path = CONFIG_PATH) -> None: self.config_path = config_path self.stations = self._load_stations() # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def get_historical( self, station_id: str, lat: float, lon: float, start_date: str, end_date: str, ) -> pd.DataFrame: """Fetch historical daily weather for a station. Parameters ---------- station_id: Identifier used in output filenames and the ``station_id`` column. lat: Latitude of the station. lon: Longitude of the station. start_date: Inclusive start date in ``YYYY-MM-DD`` format. end_date: Inclusive end date in ``YYYY-MM-DD`` format. Returns ------- pandas.DataFrame Columns: date, 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_id. Raises ------ RuntimeError If the API request fails after all retries. """ logger.info( "Fetching historical weather for station=%s (%s to %s)", station_id, start_date, end_date, ) params = { "latitude": lat, "longitude": lon, "start_date": start_date, "end_date": end_date, "daily": ",".join(DAILY_VARIABLES), "timezone": "Europe/Madrid", } raw = self._request(HISTORICAL_URL, params) df = self._parse_response(raw, station_id) return df def get_forecast( self, station_id: str, lat: float, lon: float, ) -> pd.DataFrame: """Fetch 7-day daily weather forecast for a station. Parameters ---------- station_id: Identifier used in output filenames and the ``station_id`` column. lat: Latitude of the station. lon: Longitude of the station. Returns ------- pandas.DataFrame Same columns as :meth:`get_historical`. Raises ------ RuntimeError If the API request fails after all retries. """ logger.info("Fetching 7-day forecast for station=%s", station_id) params = { "latitude": lat, "longitude": lon, "forecast_days": 7, "daily": ",".join(DAILY_VARIABLES), "timezone": "Europe/Madrid", } raw = self._request(FORECAST_URL, params) df = self._parse_response(raw, station_id) return df def collect_all_stations( self, start_date: str | None = None, end_date: str | None = None, include_forecast: bool = True, ) -> dict[str, pd.DataFrame]: """Collect weather data for every station in the config. Fetches historical data when ``start_date`` / ``end_date`` are provided, and optionally the 7-day forecast. Parameters ---------- start_date: Inclusive start date (``YYYY-MM-DD``) for historical collection. Defaults to 365 days before today. end_date: Inclusive end date (``YYYY-MM-DD``) for historical collection. Defaults to yesterday. include_forecast: Whether to also fetch the 7-day forecast. Defaults to ``True``. Returns ------- dict[str, pandas.DataFrame] Mapping of station_id to a combined DataFrame (historical + forecast when ``include_forecast`` is True, otherwise historical only). """ if start_date is None: start_date = (date.today() - timedelta(days=365)).strftime("%Y-%m-%d") if end_date is None: end_date = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d") results: dict[str, pd.DataFrame] = {} for station_id, cfg in self.stations.items(): lat = cfg["latitude"] lon = cfg["longitude"] frames: list[pd.DataFrame] = [] try: hist_df = self.get_historical(station_id, lat, lon, start_date, end_date) frames.append(hist_df) except RuntimeError as exc: logger.error("Historical fetch failed for station=%s: %s", station_id, exc) if include_forecast: try: forecast_df = self.get_forecast(station_id, lat, lon) frames.append(forecast_df) except RuntimeError as exc: logger.error("Forecast fetch failed for station=%s: %s", station_id, exc) if frames: combined = pd.concat(frames, ignore_index=True) combined.drop_duplicates(subset=["date", "station_id"], inplace=True) combined.sort_values("date", inplace=True) results[station_id] = combined logger.info("collect_all_stations complete. Stations collected: %s", list(results.keys())) return results # ------------------------------------------------------------------ # Private helpers # ------------------------------------------------------------------ def _load_stations(self) -> dict: """Load station configuration from YAML.""" with open(self.config_path, "r", encoding="utf-8") as fh: config = yaml.safe_load(fh) return config.get("stations", {}) def _request(self, url: str, params: dict) -> dict: """Send a GET request with retry logic. Parameters ---------- url: API endpoint URL. params: Query parameters to include in the request. Returns ------- dict Parsed JSON response body. Raises ------ RuntimeError If all retries are exhausted or a non-retryable error occurs. """ last_exc: Exception | None = None for attempt in range(1, MAX_RETRIES + 1): try: response = requests.get(url, params=params, timeout=30) response.raise_for_status() return response.json() except requests.exceptions.HTTPError as exc: status = exc.response.status_code if exc.response is not None else None # 429 Too Many Requests is retryable with a longer back-off if status == 429: wait = RETRY_BACKOFF * attempt * 10 logger.warning( "Rate-limited (429) on attempt %d/%d. Waiting %ds before retry.", attempt, MAX_RETRIES, wait, ) last_exc = exc time.sleep(wait) continue # Other 4xx errors are not retryable if status is not None and 400 <= status < 500: raise RuntimeError( f"Client error {status} from {url}: {exc}" ) from exc last_exc = exc logger.warning("Attempt %d/%d failed: %s", attempt, MAX_RETRIES, exc) except requests.exceptions.RequestException as exc: last_exc = exc logger.warning("Attempt %d/%d failed: %s", attempt, MAX_RETRIES, exc) if attempt < MAX_RETRIES: time.sleep(RETRY_BACKOFF * attempt) raise RuntimeError( f"All {MAX_RETRIES} attempts failed for {url}. Last error: {last_exc}" ) def _parse_response(self, raw: dict, station_id: str) -> pd.DataFrame: """Convert an Open-Meteo daily response dict into a DataFrame. Parameters ---------- raw: Parsed JSON response from the API. station_id: Station identifier to add as a column. Returns ------- pandas.DataFrame """ daily = raw.get("daily", {}) if not daily: logger.warning("Empty daily data in response for station=%s", station_id) return pd.DataFrame( columns=["date"] + DAILY_VARIABLES + ["station_id"] ) df = pd.DataFrame(daily) df.rename(columns={"time": "date"}, inplace=True) df["date"] = pd.to_datetime(df["date"]).dt.date df["station_id"] = station_id # Ensure all expected columns are present for col in DAILY_VARIABLES: if col not in df.columns: logger.warning("Column %s missing in API response for station=%s", col, station_id) df[col] = None # Keep only the expected column order columns = ["date"] + DAILY_VARIABLES + ["station_id"] return df[columns]