Files
skipredictor/data_sources/crowd_analyzer.py
T

341 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 in the project SQLite database.
Typical usage::
analyzer = CrowdAnalyzer()
result = analyzer.estimate_crowd_level("pajares")
print(result["crowd_density"]) # "low" / "medium" / "high"
"""
from __future__ import annotations
import logging
import warnings
from datetime import datetime
from pathlib import Path
from typing import Any
import yaml
from storage import SQLiteStore
logger = logging.getLogger(__name__)
BASE_DIR = Path(__file__).resolve().parent.parent
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
# 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).
store:
SQLite store where analysis results are written.
"""
def __init__(
self,
config_path: Path = CONFIG_PATH,
model_weights: str = YOLO_MODEL_WEIGHTS,
store: SQLiteStore | None = None,
) -> None:
self.config_path = config_path
self.model_weights = model_weights
self.store = store if store is not None else SQLiteStore()
self.stations = self._load_stations()
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 to SQLite, 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)
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)
return result
analysis["station_id"] = station_id
analysis["image_path"] = image_path
self._save_result(analysis)
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]) -> None:
"""Persist an analysis result dict to SQLite."""
row_id = self.store.save_crowd_analysis(result)
logger.info(
"Saved crowd analysis row %d for station=%s",
row_id,
result.get("station_id"),
)