"""Webcam snapshot collector for ski station crowd analysis. Downloads the latest JPEG snapshot from each station's public webcam feeds and persists them to ``data/raw/webcams/``. The collector supports two URL strategies: * **Static URL** – the remote server overwrites the same file in-place on every camera refresh cycle (e.g. nieveleonsanisidro.com, fuentesdeinvierno.com). The configured URL is used directly. * **Page-scraped URL** – the remote page embeds a timestamped filename for the current snapshot (e.g. infonieve.es/webcams/pajares-cuitu_.jpg). The collector fetches the HTML of ``primary_webcam_page`` and extracts the first ``/webcams/*.jpg`` URL it finds. URL configuration lives in ``config/stations.yaml`` under ``stations..webcams``. """ from __future__ import annotations import logging import re import time from datetime import datetime from pathlib import Path from typing import Any import requests import yaml logger = logging.getLogger(__name__) BASE_DIR = Path(__file__).resolve().parent.parent CONFIG_PATH = BASE_DIR / "config" / "stations.yaml" WEBCAM_DIR = BASE_DIR / "data" / "raw" / "webcams" # HTTP settings REQUEST_TIMEOUT = 20 # seconds MAX_RETRIES = 3 RETRY_BACKOFF = 2 # seconds between retries # Minimum acceptable image size – smaller responses are treated as errors. MIN_IMAGE_BYTES = 5_000 # User-agent that avoids bot-blocking on some servers. _USER_AGENT = ( "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/122.0 Safari/537.36" ) _HEADERS = {"User-Agent": _USER_AGENT} # --------------------------------------------------------------------------- # WebcamCollector # --------------------------------------------------------------------------- class WebcamCollector: """Downloads and saves the latest webcam snapshots for each ski station. Parameters ---------- config_path: Path to the stations YAML configuration file. Defaults to ``config/stations.yaml`` relative to the project root. output_dir: Directory where captured images are saved. Created automatically if it does not exist. Defaults to ``data/raw/webcams/``. """ def __init__( self, config_path: Path = CONFIG_PATH, output_dir: Path = WEBCAM_DIR, ) -> None: self.config_path = config_path self.output_dir = output_dir self.stations = self._load_stations() self.output_dir.mkdir(parents=True, exist_ok=True) # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def capture(self, station_id: str) -> list[str]: """Download the latest snapshot(s) for *station_id*. Iterates over all configured snapshot entries for the station and attempts to download each one. Failed downloads are logged and skipped; at least one successful download is not guaranteed (webcams are frequently offline). Parameters ---------- station_id: Must match a key in ``config/stations.yaml`` (e.g. ``"pajares"``). Returns ------- list[str] Absolute paths to successfully saved image files. Empty list if all downloads failed or the station has no webcam configuration. """ if station_id not in self.stations: logger.error("Unknown station_id=%s", station_id) return [] station_cfg = self.stations[station_id] webcam_cfg = station_cfg.get("webcams") if not webcam_cfg: logger.warning("No webcam config for station_id=%s", station_id) return [] snapshots = webcam_cfg.get("snapshots", []) if not snapshots: logger.warning("No snapshots configured for station_id=%s", station_id) return [] timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") saved_paths: list[str] = [] for idx, snap in enumerate(snapshots): label = snap.get("label", f"cam{idx}") ssl_verify: bool = snap.get("ssl_verify", True) # Resolve the actual download URL for this snapshot entry. url = self._resolve_snapshot_url(snap, webcam_cfg, station_id) if not url: logger.warning( "Could not resolve URL for station=%s label=%s", station_id, label ) continue # Sanitise label for use as a filename component. safe_label = re.sub(r"[^a-zA-Z0-9_-]", "_", label).strip("_").lower() filename = self.output_dir / f"{station_id}_{safe_label}_{timestamp}.jpg" path = self._download_image(url, filename, ssl_verify=ssl_verify) if path: saved_paths.append(path) if saved_paths: logger.info( "Captured %d image(s) for station=%s", len(saved_paths), station_id ) else: logger.warning("No images captured for station=%s", station_id) return saved_paths def capture_all(self) -> dict[str, list[str]]: """Capture snapshots for every configured station. Returns ------- dict[str, list[str]] Mapping of station_id to the list of saved image paths for that station. Stations with no successful captures map to an empty list. """ results: dict[str, list[str]] = {} for station_id in self.stations: results[station_id] = self.capture(station_id) logger.info( "capture_all complete. Stations: %s", {k: len(v) for k, v in results.items()}, ) return results # ------------------------------------------------------------------ # Private helpers # ------------------------------------------------------------------ def _load_stations(self) -> dict[str, Any]: """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 _resolve_snapshot_url( self, snap: dict[str, Any], webcam_cfg: dict[str, Any], station_id: str, ) -> str | None: """Return the concrete download URL for a snapshot entry. For static entries the ``url`` field is returned directly. For timestamped entries the current URL is scraped from the station's webcam page on infonieve.es. Parameters ---------- snap: A single entry from the ``snapshots`` list in the YAML config. webcam_cfg: The ``webcams`` dict for the station (contains ``primary_webcam_page``). station_id: Used for log messages only. Returns ------- str | None Resolved URL, or ``None`` if resolution failed. """ if snap.get("static", True): return snap.get("url") # Dynamic / timestamped strategy: scrape the page. page_url = webcam_cfg.get("primary_webcam_page") if not page_url: logger.warning("No primary_webcam_page for station=%s", station_id) return None return self._scrape_first_webcam_url(page_url, station_id) def _scrape_first_webcam_url( self, page_url: str, station_id: str ) -> str | None: """Scrape the infonieve.es webcam page and return the first snapshot URL. infonieve.es embeds timestamped filenames such as: ``https://www.infonieve.es/webcams/pajares-cuitu_2026-03-12-13-01-602.jpg`` Parameters ---------- page_url: URL of the infonieve.es webcam listing page. station_id: Used for log messages only. Returns ------- str | None First absolute JPEG URL found, or ``None`` on failure. """ try: resp = requests.get( page_url, headers=_HEADERS, timeout=REQUEST_TIMEOUT, ) resp.raise_for_status() except requests.RequestException as exc: logger.warning( "Failed to fetch webcam page for station=%s: %s", station_id, exc ) return None # Match the first direct JPEG image under /webcams/ path. match = re.search( r'https://www\.infonieve\.es/webcams/[^\s"\'<>)]+\.jpg', resp.text, ) if not match: logger.warning( "No /webcams/*.jpg URL found on page %s for station=%s", page_url, station_id, ) return None url = match.group(0) logger.debug("Resolved webcam URL for station=%s: %s", station_id, url) return url def _download_image( self, url: str, dest: Path, ssl_verify: bool = True, ) -> str | None: """Download a JPEG from *url* and write it to *dest*. Implements a simple retry loop with exponential back-off. Parameters ---------- url: Direct image URL. dest: Destination file path. ssl_verify: Whether to verify the server's TLS certificate. Set to ``False`` for servers with self-signed certificates (e.g. fuentesdeinvierno.com). Returns ------- str | None Absolute path to the saved file, or ``None`` on failure. """ last_exc: Exception | None = None for attempt in range(1, MAX_RETRIES + 1): try: resp = requests.get( url, headers=_HEADERS, timeout=REQUEST_TIMEOUT, verify=ssl_verify, stream=True, ) resp.raise_for_status() content = resp.content if len(content) < MIN_IMAGE_BYTES: logger.warning( "Image too small (%d bytes) from %s, skipping", len(content), url, ) return None dest.write_bytes(content) logger.info("Saved webcam image to %s (%d bytes)", dest, len(content)) return str(dest) except requests.exceptions.SSLError as exc: # Non-retryable if ssl_verify=True was intentional. logger.error("SSL error downloading %s: %s", url, exc) return None except requests.exceptions.HTTPError as exc: if exc.response is not None and 400 <= exc.response.status_code < 500: logger.error( "Client error %d downloading %s", exc.response.status_code, url, ) return None last_exc = exc except requests.exceptions.RequestException as exc: last_exc = exc logger.warning( "Download attempt %d/%d failed for %s: %s", attempt, MAX_RETRIES, url, last_exc, ) if attempt < MAX_RETRIES: time.sleep(RETRY_BACKOFF * attempt) logger.error( "All %d download attempts failed for %s. Last error: %s", MAX_RETRIES, url, last_exc, ) return None