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

+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)