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

+5
View File
@@ -0,0 +1,5 @@
"""Data sources package for ski predictor.
Modules:
weather_api: Fetches weather data from Open-Meteo API.
"""
+368
View File
@@ -0,0 +1,368 @@
"""Crowd density estimator using YOLOv8 object detection.
Analyses webcam snapshot images from ski stations to estimate crowd levels.
Uses the YOLOv8 nano model (``yolov8n.pt``) from the ``ultralytics`` package
to detect people, cars, buses and trucks.
Detected object counts are mapped to three crowd density levels:
* **low** – fewer than 20 cars OR fewer than 10 people visible
* **medium** – 20–50 cars OR 10–30 people
* **high** – more than 50 cars OR more than 30 people
Analysis results are persisted as JSON files in ``data/raw/`` following the
naming pattern ``crowd_{station_id}_{date}.json``.
Typical usage::
analyzer = CrowdAnalyzer()
result = analyzer.estimate_crowd_level("pajares")
print(result["crowd_density"]) # "low" / "medium" / "high"
"""
from __future__ import annotations
import json
import logging
import warnings
from datetime import date, datetime
from pathlib import Path
from typing import Any
import yaml
logger = logging.getLogger(__name__)
BASE_DIR = Path(__file__).resolve().parent.parent
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
RAW_DATA_DIR = BASE_DIR / "data" / "raw"
# YOLO model weights file – downloaded automatically on first use.
YOLO_MODEL_WEIGHTS = "yolov8n.pt"
# COCO class names that count towards crowd estimation.
VEHICLE_CLASSES = {"car", "bus", "truck", "motorcycle"}
PERSON_CLASS = "person"
# Crowd density thresholds.
_CAR_THRESHOLD_LOW = 20
_CAR_THRESHOLD_HIGH = 50
_PERSON_THRESHOLD_LOW = 10
_PERSON_THRESHOLD_HIGH = 30
# Minimum YOLO confidence score for a detection to be counted.
DETECTION_CONFIDENCE = 0.25
# ---------------------------------------------------------------------------
# CrowdAnalyzer
# ---------------------------------------------------------------------------
class CrowdAnalyzer:
"""Estimates crowd levels at ski stations from webcam snapshot images.
Parameters
----------
config_path:
Path to the stations YAML configuration file. Defaults to
``config/stations.yaml`` relative to the project root.
model_weights:
YOLOv8 weights identifier passed to ``ultralytics.YOLO()``.
Defaults to ``"yolov8n.pt"`` (nano model).
output_dir:
Directory where JSON result files are written. Created if it does
not exist. Defaults to ``data/raw/``.
"""
def __init__(
self,
config_path: Path = CONFIG_PATH,
model_weights: str = YOLO_MODEL_WEIGHTS,
output_dir: Path = RAW_DATA_DIR,
) -> None:
self.config_path = config_path
self.model_weights = model_weights
self.output_dir = output_dir
self.stations = self._load_stations()
self.output_dir.mkdir(parents=True, exist_ok=True)
self._model: Any = None # Lazy-loaded on first inference call.
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def analyze_image(self, image_path: str) -> dict[str, Any]:
"""Run object detection on a single webcam snapshot.
Parameters
----------
image_path:
Path to a JPEG or PNG webcam image.
Returns
-------
dict
Keys:
* ``cars_detected`` – number of cars detected
* ``people_detected`` – number of people detected
* ``buses_detected`` – number of buses detected
* ``total_vehicles`` – cars + buses + trucks combined
* ``crowd_density`` – ``"low"``, ``"medium"``, or ``"high"``
* ``confidence_scores`` – list of per-detection confidence values
* ``timestamp`` – ISO-8601 timestamp of when analysis ran
Raises
------
FileNotFoundError
If *image_path* does not exist.
RuntimeError
If the YOLO model cannot be loaded (e.g. ``ultralytics`` not
installed).
"""
path = Path(image_path)
if not path.exists():
raise FileNotFoundError(f"Image not found: {image_path}")
model = self._load_model()
results = model(str(path), conf=DETECTION_CONFIDENCE, verbose=False)
cars = 0
people = 0
buses = 0
trucks = 0
confidence_scores: list[float] = []
for result in results:
boxes = result.boxes
if boxes is None:
continue
for box in boxes:
conf = float(box.conf[0])
cls_id = int(box.cls[0])
cls_name = result.names.get(cls_id, "").lower()
confidence_scores.append(round(conf, 4))
if cls_name == PERSON_CLASS:
people += 1
elif cls_name == "car":
cars += 1
elif cls_name == "bus":
buses += 1
elif cls_name == "truck":
trucks += 1
total_vehicles = cars + buses + trucks
return {
"cars_detected": cars,
"people_detected": people,
"buses_detected": buses,
"total_vehicles": total_vehicles,
"crowd_density": self._classify_density(cars, people),
"confidence_scores": confidence_scores,
"timestamp": datetime.now().isoformat(timespec="seconds"),
}
def estimate_crowd_level(self, station_id: str) -> dict[str, Any]:
"""Capture the latest webcam snapshot for *station_id* and analyse it.
Downloads one image via :class:`~data_sources.webcam_collector.WebcamCollector`,
runs object detection, saves the result as a JSON file and returns the
analysis dict.
Parameters
----------
station_id:
Must match a key in ``config/stations.yaml``.
Returns
-------
dict
Same structure as :meth:`analyze_image`, with an additional
``station_id`` key and a ``image_path`` key (``None`` if the
webcam capture failed). When capture fails a minimal dict with
``crowd_density="unknown"`` is returned so the pipeline can
continue.
"""
# Import here to avoid circular imports at module level.
from data_sources.webcam_collector import WebcamCollector # noqa: PLC0415
collector = WebcamCollector(config_path=self.config_path)
saved_paths = collector.capture(station_id)
if not saved_paths:
logger.warning(
"No webcam images captured for station=%s; crowd level unknown",
station_id,
)
result = self._empty_result(station_id, image_path=None)
self._save_result(result, station_id)
return result
# Analyse only the first captured image to keep latency low.
image_path = saved_paths[0]
try:
analysis = self.analyze_image(image_path)
except Exception as exc:
logger.error(
"Image analysis failed for station=%s path=%s: %s",
station_id,
image_path,
exc,
)
result = self._empty_result(station_id, image_path=image_path)
self._save_result(result, station_id)
return result
analysis["station_id"] = station_id
analysis["image_path"] = image_path
self._save_result(analysis, station_id)
return analysis
def analyze_all_stations(self) -> dict[str, dict[str, Any]]:
"""Run crowd estimation for every station defined in the config.
Returns
-------
dict[str, dict]
Mapping of station_id to its crowd analysis result dict.
"""
results: dict[str, dict[str, Any]] = {}
for station_id in self.stations:
logger.info("Analysing crowd for station=%s", station_id)
results[station_id] = self.estimate_crowd_level(station_id)
logger.info(
"analyze_all_stations complete. Densities: %s",
{k: v.get("crowd_density") for k, v in results.items()},
)
return results
# ------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------
@staticmethod
def _classify_density(cars: int, people: int) -> str:
"""Map raw detection counts to a density label.
The classification uses whichever signal indicates the *highest*
crowd level – i.e. if cars suggest "high" but people suggest "low",
the result is "high".
Parameters
----------
cars:
Number of cars detected in the image.
people:
Number of people detected in the image.
Returns
-------
str
One of ``"low"``, ``"medium"``, or ``"high"``.
"""
def _level(value: int, low_threshold: int, high_threshold: int) -> int:
"""Return 0=low, 1=medium, 2=high for a given count."""
if value < low_threshold:
return 0
if value <= high_threshold:
return 1
return 2
car_level = _level(cars, _CAR_THRESHOLD_LOW, _CAR_THRESHOLD_HIGH)
person_level = _level(people, _PERSON_THRESHOLD_LOW, _PERSON_THRESHOLD_HIGH)
combined = max(car_level, person_level)
return ["low", "medium", "high"][combined]
def _load_model(self) -> Any:
"""Lazy-load the YOLOv8 model.
The model is cached in ``self._model`` after the first call.
Returns
-------
ultralytics.YOLO
Loaded model instance.
Raises
------
RuntimeError
If the ``ultralytics`` package is not installed.
"""
if self._model is not None:
return self._model
try:
from ultralytics import YOLO # noqa: PLC0415
except ImportError as exc:
raise RuntimeError(
"The 'ultralytics' package is required for crowd analysis. "
"Install it with: pip install ultralytics>=8.0.0"
) from exc
logger.info("Loading YOLO model: %s", self.model_weights)
# Suppress ultralytics INFO logs during model loading.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self._model = YOLO(self.model_weights)
return self._model
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", {})
@staticmethod
def _empty_result(station_id: str, image_path: str | None) -> dict[str, Any]:
"""Return a placeholder result when capture or analysis fails."""
return {
"station_id": station_id,
"image_path": image_path,
"cars_detected": 0,
"people_detected": 0,
"buses_detected": 0,
"total_vehicles": 0,
"crowd_density": "unknown",
"confidence_scores": [],
"timestamp": datetime.now().isoformat(timespec="seconds"),
}
def _save_result(self, result: dict[str, Any], station_id: str) -> None:
"""Persist an analysis result dict as a JSON file.
Filename format: ``crowd_{station_id}_{date}.json``
Parameters
----------
result:
Analysis dict to serialise.
station_id:
Used to construct the output filename.
"""
today = date.today().strftime("%Y-%m-%d")
filename = self.output_dir / f"crowd_{station_id}_{today}.json"
# Append to an existing file (list of results) or create a new one.
if filename.exists():
try:
existing = json.loads(filename.read_text(encoding="utf-8"))
if not isinstance(existing, list):
existing = [existing]
except (json.JSONDecodeError, OSError):
existing = []
else:
existing = []
existing.append(result)
filename.write_text(
json.dumps(existing, indent=2, ensure_ascii=False),
encoding="utf-8",
)
logger.info("Saved crowd analysis to %s", filename)
+184
View File
@@ -0,0 +1,184 @@
"""Download historical station data from infonieve.es TSV endpoints.
Infonieve provides daily operational data for ski stations going back to
the 2009-10 season via a TSV endpoint:
estacion-esqui.historico-nieve.tsv.php?id={station_id}&anyo={year}&data=parte
Columns in the TSV:
date, closedflag, turisticoflag, kmtotal, kmopen, pistastotal,
pistasopen, espesormin, espesormax, calidadnieve, kmprocessed,
pistasprocessed, minprocessed, maxprocessed, idestado
This module downloads all available seasons for the three target stations
and saves the combined data as CSVs in data/raw/.
"""
import io
import logging
import time
from pathlib import Path
import pandas as pd
import requests
logger = logging.getLogger(__name__)
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
_RAW_DIR = _PROJECT_ROOT / "data" / "raw"
_BASE_URL = "https://www.infonieve.es/estacion-esqui.historico-nieve.tsv.php"
# Infonieve internal IDs for our stations
_STATION_IDS = {
"pajares": 13,
"sanisidro": 14,
"fuentes": 5448,
}
# Seasons available (the year parameter is the year the season starts in autumn)
# e.g. 2024 = season 2024-25
_SEASONS = list(range(2009, 2026))
_USER_AGENT = (
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
)
def download_season(
station_id: str, infonieve_id: int, year: int, session: requests.Session
) -> pd.DataFrame | None:
"""Download a single season's daily data from infonieve.es.
Parameters
----------
station_id:
Our station key (e.g. 'pajares').
infonieve_id:
Infonieve internal numeric ID for the station.
year:
The season start year (e.g. 2024 for 2024-25 season).
session:
Requests session with appropriate headers.
Returns
-------
pd.DataFrame or None
DataFrame with daily records, or None if no data available.
"""
params = {"id": infonieve_id, "anyo": year, "data": "parte"}
try:
resp = session.get(_BASE_URL, params=params, timeout=30)
resp.raise_for_status()
except requests.RequestException as exc:
logger.warning("Failed to fetch %s season %d-%d: %s", station_id, year, year + 1, exc)
return None
text = resp.text.strip()
if not text or len(text) < 20:
logger.debug("No data for %s season %d-%d.", station_id, year, year + 1)
return None
try:
df = pd.read_csv(io.StringIO(text), sep="\t")
except Exception as exc:
logger.warning("Failed to parse TSV for %s season %d-%d: %s", station_id, year, year + 1, exc)
return None
if df.empty:
return None
# Normalize column names
df.columns = df.columns.str.strip().str.lower()
# Add metadata
df["station_id"] = station_id
df["season"] = f"{year}-{str(year + 1)[-2:]}"
logger.debug("Downloaded %s season %d-%d: %d rows.", station_id, year, year + 1, len(df))
return df
def download_all_history() -> pd.DataFrame:
"""Download all available historical data for all three stations.
Returns
-------
pd.DataFrame
Combined DataFrame with all seasons and stations.
"""
session = requests.Session()
session.headers.update({
"User-Agent": _USER_AGENT,
"Accept-Language": "es-ES,es;q=0.9",
"Referer": "https://www.infonieve.es/",
})
all_frames = []
for station_id, infonieve_id in _STATION_IDS.items():
logger.info("Downloading history for %s (infonieve id=%d)...", station_id, infonieve_id)
for year in _SEASONS:
df = download_season(station_id, infonieve_id, year, session)
if df is not None and not df.empty:
all_frames.append(df)
# Be polite to the server
time.sleep(0.3)
logger.info("Finished %s: %d seasons with data.", station_id,
sum(1 for f in all_frames if f["station_id"].iloc[0] == station_id))
if not all_frames:
logger.error("No historical data downloaded from any station.")
return pd.DataFrame()
combined = pd.concat(all_frames, ignore_index=True)
# Normalize the date column
if "date" in combined.columns:
combined["date"] = pd.to_datetime(combined["date"], format="mixed", dayfirst=True)
# Sort
combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True)
# Save
_RAW_DIR.mkdir(parents=True, exist_ok=True)
output_path = _RAW_DIR / "station_historical_all.csv"
combined.to_csv(output_path, index=False)
logger.info("Historical data saved to %s: %d total rows.", output_path, len(combined))
# Summary
for sid in _STATION_IDS:
station_data = combined[combined["station_id"] == sid]
if not station_data.empty:
logger.info(
" %s: %d rows, %s to %s, %d seasons",
sid,
len(station_data),
station_data["date"].min().strftime("%Y-%m-%d"),
station_data["date"].max().strftime("%Y-%m-%d"),
station_data["season"].nunique(),
)
return combined
if __name__ == "__main__":
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
)
df = download_all_history()
print(f"\nTotal: {len(df)} rows")
print(f"Columns: {list(df.columns)}")
print(f"\nPer station:")
print(df.groupby("station_id").agg(
rows=("date", "count"),
first_date=("date", "min"),
last_date=("date", "max"),
seasons=("season", "nunique"),
))
+405
View File
@@ -0,0 +1,405 @@
"""
station_scraper.py
Scrapes ski station operational data for the three northern Spain stations
managed by the government of Asturias/León:
- Valgrande-Pajares (station_id: pajares)
- San Isidro (station_id: sanisidro)
- Fuentes de Invierno(station_id: fuentes)
Primary source: infonieve.es (https://www.infonieve.es/estacion-esqui/{slug}/)
Fallback: returns None values with a logged warning when scraping fails.
Raw responses are saved to:
data/raw/station_{station_id}_{date}.json
"""
import json
import logging
import re
from datetime import date
from pathlib import Path
from typing import Optional
import requests
import yaml
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
_CONFIG_PATH = _PROJECT_ROOT / "config" / "stations.yaml"
_RAW_DATA_DIR = _PROJECT_ROOT / "data" / "raw"
_USER_AGENT = (
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
)
_REQUEST_TIMEOUT = 15 # seconds
# Mapping from station_id to the slug used on infonieve.es
_INFONIEVE_SLUGS: dict[str, str] = {
"pajares": "valgrande-pajares",
"sanisidro": "san-isidro",
"fuentes": "fuentes-de-invierno",
}
# Known snow quality label normalisations (infonieve uses Spanish)
_QUALITY_TRANSLATIONS: dict[str, str] = {
"polvo": "powder",
"nieve polvo": "powder",
"granulada": "granular",
"nieve granulada": "granular",
"compacta": "compact",
"nieve compacta": "compact",
"helada": "icy",
"nieve helada": "icy",
"húmeda": "wet",
"nieve húmeda": "wet",
"primaveral": "spring",
"nieve primaveral": "spring",
"artificial": "artificial",
"nieve artificial": "artificial",
}
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _load_config() -> dict:
"""Load station configuration from stations.yaml."""
with open(_CONFIG_PATH, encoding="utf-8") as fh:
return yaml.safe_load(fh)
def _get_session() -> requests.Session:
"""Return a requests Session with a browser-like User-Agent."""
session = requests.Session()
session.headers.update(
{
"User-Agent": _USER_AGENT,
"Accept-Language": "es-ES,es;q=0.9,en;q=0.8",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
}
)
return session
def _save_raw(station_id: str, payload: dict) -> None:
"""Persist raw scraped payload to data/raw/ as JSON."""
_RAW_DATA_DIR.mkdir(parents=True, exist_ok=True)
today = date.today().isoformat()
filename = _RAW_DATA_DIR / f"station_{station_id}_{today}.json"
try:
with open(filename, "w", encoding="utf-8") as fh:
json.dump(payload, fh, ensure_ascii=False, indent=2)
logger.debug("Raw data saved to %s", filename)
except OSError as exc:
logger.warning("Could not save raw data for %s: %s", station_id, exc)
def _parse_float(text: Optional[str]) -> Optional[float]:
"""Extract the first float-like value from a string, or return None."""
if not text:
return None
match = re.search(r"[\d]+[.,]?[\d]*", text.replace(",", "."))
if match:
try:
return float(match.group().replace(",", "."))
except ValueError:
pass
return None
def _parse_int(text: Optional[str]) -> Optional[int]:
"""Extract the first integer value from a string, or return None."""
value = _parse_float(text)
return int(value) if value is not None else None
def _normalise_quality(raw: Optional[str]) -> Optional[str]:
"""Normalise a Spanish snow quality label to a short English keyword."""
if not raw:
return None
key = raw.strip().lower()
return _QUALITY_TRANSLATIONS.get(key, raw.strip())
def _empty_record(station_id: str) -> dict:
"""Return a record with all operational fields set to None."""
return {
"station_id": station_id,
"date": date.today().isoformat(),
"open_status": None,
"km_open": None,
"lifts_open": None,
"snow_depth": None,
"snow_quality": None,
}
# ---------------------------------------------------------------------------
# Infonieve parser
# ---------------------------------------------------------------------------
def _fetch_infonieve_page(slug: str, session: requests.Session) -> Optional[BeautifulSoup]:
"""
Fetch and parse the infonieve.es station page.
Returns a BeautifulSoup tree on success, None on any network or HTTP error.
"""
url = f"https://www.infonieve.es/estacion-esqui/{slug}/"
try:
response = session.get(url, timeout=_REQUEST_TIMEOUT)
response.raise_for_status()
return BeautifulSoup(response.text, "lxml")
except requests.exceptions.Timeout:
logger.warning("Timeout fetching infonieve page for slug '%s'", slug)
except requests.exceptions.HTTPError as exc:
logger.warning("HTTP error fetching infonieve page for slug '%s': %s", slug, exc)
except requests.exceptions.RequestException as exc:
logger.warning("Request error fetching infonieve page for slug '%s': %s", slug, exc)
return None
def _parse_infonieve(soup: BeautifulSoup, station_id: str) -> dict:
"""Extract operational fields from a parsed infonieve.es page.
Infonieve uses a layout with keywords (Remontes, Kilómetros, Nieve)
followed by ``<strong>value</strong>/total`` patterns. This parser
works on the flattened page text with regex to be resilient to minor
HTML restructuring.
All fields default to None when the value cannot be reliably extracted.
"""
record = _empty_record(station_id)
page_text = soup.get_text(separator=" ")
# --- open_status ---
# Look for <strong>Abierta</strong> or <strong>Cerrada</strong>
status_tag = soup.find("strong", string=re.compile(r"abierta|cerrada", re.I))
if status_tag:
label = status_tag.get_text(strip=True).lower()
record["open_status"] = "abierta" in label
else:
# Fallback: scan page text
text_lower = page_text.lower()
if "abierta" in text_lower:
record["open_status"] = True
elif "cerrada" in text_lower:
record["open_status"] = False
# --- lifts_open ---
# Pattern: "Remontes" ... <strong>N</strong>/M
lifts_match = re.search(
r"Remontes\s*(\d+)\s*/\s*(\d+)",
page_text,
re.I,
)
if lifts_match:
record["lifts_open"] = int(lifts_match.group(1))
logger.debug("Parsed lifts_open=%s (total=%s)", lifts_match.group(1), lifts_match.group(2))
# --- km_open ---
# Pattern: "Kilómetros" ... <strong>N,NN</strong>/M,MM
km_match = re.search(
r"(?:Kil[óo]metros|Km)\s*([\d]+[.,]?\d*)\s*/\s*([\d]+[.,]?\d*)",
page_text,
re.I,
)
if km_match:
record["km_open"] = float(km_match.group(1).replace(",", "."))
logger.debug("Parsed km_open=%s (total=%s)", km_match.group(1), km_match.group(2))
# --- snow_depth ---
# Pattern: "Nieve" ... <strong>N</strong> cm
snow_match = re.search(
r"Nieve\s*(\d+)\s*cm",
page_text,
re.I,
)
if snow_match:
record["snow_depth"] = int(snow_match.group(1))
logger.debug("Parsed snow_depth=%s cm", snow_match.group(1))
# --- snow_quality ---
# Pattern: "Calidad" or "Tipo de nieve" followed by text
quality_match = re.search(
r"(?:calidad|tipo)\s+(?:de\s+)?(?:la\s+)?nieve[:\s]+([a-záéíóúñü]+)",
page_text,
re.I,
)
if quality_match:
record["snow_quality"] = _normalise_quality(quality_match.group(1))
return record
# ---------------------------------------------------------------------------
# Public scraper class
# ---------------------------------------------------------------------------
class StationScraper:
"""
Scrapes operational status data for the three Asturias/León ski stations.
Usage
-----
>>> scraper = StationScraper()
>>> record = scraper.scrape_station("pajares")
>>> all_records = scraper.scrape_all_stations()
The scraper attempts to collect data from infonieve.es. When a page
cannot be fetched or parsed, it logs a warning and returns a record with
None values so that the rest of the pipeline can continue.
"""
def __init__(self) -> None:
config = _load_config()
self._stations: dict = config.get("stations", {})
self._session: requests.Session = _get_session()
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def scrape_station(self, station_id: str) -> dict:
"""
Scrape operational data for a single station.
Parameters
----------
station_id:
One of the keys defined in config/stations.yaml
(e.g. 'pajares', 'sanisidro', 'fuentes').
Returns
-------
dict with keys:
station_id (str)
date (str, ISO-8601)
open_status (bool or None)
km_open (float or None)
lifts_open (int or None)
snow_depth (int or None, centimetres)
snow_quality(str or None)
"""
if station_id not in self._stations:
logger.error(
"Unknown station_id '%s'. Known stations: %s",
station_id,
list(self._stations.keys()),
)
return _empty_record(station_id)
logger.info("Scraping station: %s", station_id)
record = self._scrape_infonieve(station_id)
_save_raw(station_id, record)
return record
def scrape_all_stations(self) -> list[dict]:
"""
Scrape operational data for all stations defined in stations.yaml.
Returns
-------
List of dicts, one per station, in the same format as scrape_station().
"""
results = []
for station_id in self._stations:
record = self.scrape_station(station_id)
results.append(record)
return results
# ------------------------------------------------------------------
# Internal scraping logic
# ------------------------------------------------------------------
def _scrape_infonieve(self, station_id: str) -> dict:
"""
Attempt to scrape from infonieve.es and return an operational record.
Falls back to an empty record (all fields None) when the page cannot
be fetched or the content does not match expected patterns.
"""
slug = _INFONIEVE_SLUGS.get(station_id)
if slug is None:
logger.warning(
"No infonieve.es slug configured for station '%s'. "
"Returning empty record.",
station_id,
)
return _empty_record(station_id)
soup = _fetch_infonieve_page(slug, self._session)
if soup is None:
logger.warning(
"Could not fetch infonieve.es page for '%s' (slug: '%s'). "
"All fields will be None. Check network connectivity or "
"whether the URL has changed.",
station_id,
slug,
)
return _empty_record(station_id)
try:
record = _parse_infonieve(soup, station_id)
except Exception as exc: # pylint: disable=broad-except
logger.warning(
"Unexpected error parsing infonieve.es page for '%s': %s. "
"Returning empty record.",
station_id,
exc,
exc_info=True,
)
return _empty_record(station_id)
self._log_record_summary(record)
return record
# ------------------------------------------------------------------
# Utilities
# ------------------------------------------------------------------
@staticmethod
def _log_record_summary(record: dict) -> None:
"""Emit a one-line summary of the scraped record at INFO level."""
status_label = (
"OPEN" if record["open_status"] is True
else "CLOSED" if record["open_status"] is False
else "UNKNOWN"
)
logger.info(
"[%s] %s | km=%-5s lifts=%-3s depth=%-4s quality=%s",
record["station_id"],
status_label,
record["km_open"],
record["lifts_open"],
record["snow_depth"],
record["snow_quality"],
)
# ---------------------------------------------------------------------------
# CLI entry-point (for manual testing / cron scripts)
# ---------------------------------------------------------------------------
if __name__ == "__main__":
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
)
scraper = StationScraper()
records = scraper.scrape_all_stations()
print(json.dumps(records, indent=2, ensure_ascii=False))
+358
View File
@@ -0,0 +1,358 @@
"""Weather data collector using Open-Meteo API.
Fetches historical and forecast weather data for ski stations
defined in config/stations.yaml. No API key required.
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"
RAW_DATA_DIR = BASE_DIR / "data" / "raw"
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",
]
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()
RAW_DATA_DIR.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------------
# 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)
self._save(df, 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)
self._save(df, 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]
def _save(self, df: pd.DataFrame, station_id: str) -> None:
"""Persist a weather DataFrame to a CSV file.
Filename format: ``weather_{station_id}_{date}.csv``
where ``{date}`` is today's date (the collection date).
Parameters
----------
df:
DataFrame to save.
station_id:
Station identifier used in the filename.
"""
today = date.today().strftime("%Y-%m-%d")
filename = RAW_DATA_DIR / f"weather_{station_id}_{today}.csv"
df.to_csv(filename, index=False)
logger.info("Saved weather data to %s", filename)
+355
View File
@@ -0,0 +1,355 @@
"""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_<ts>.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.<id>.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