Files
skipredictor/tests/test_crowd_analyzer.py
T
dasemu 1afe2b73e0 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
2026-03-12 14:51:32 +01:00

484 lines
18 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.
"""Unit tests for CrowdAnalyzer in data_sources/crowd_analyzer.py.
Tests cover:
- Instantiation without loading the YOLO model.
- Crowd density threshold classification across all boundary conditions.
- analyze_image() with a mocked YOLO model.
- estimate_crowd_level() with mocked WebcamCollector and YOLO.
- analyze_all_stations() integration across all three stations.
- JSON persistence of results.
"""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
_STATIONS_CONFIG = {
"stations": {
"pajares": {
"name": "Valgrande-Pajares",
"latitude": 43.05,
"longitude": -5.77,
"altitude": 1500,
"wind_closure_threshold": 80,
"minimum_snow_depth": 30,
"max_km_skiable": 22.0,
"url": "https://www.valgrande-pajares.com",
"telegram_command": "/pajares",
"webcams": {
"primary_webcam_page": "https://www.infonieve.es/estacion-esqui/valgrande-pajares/webcams/",
"snapshots": [
{
"label": "Cuitu Negru - Telecabina",
"static": False,
}
],
},
},
"sanisidro": {
"name": "San Isidro",
"latitude": 43.07,
"longitude": -5.37,
"altitude": 1500,
"wind_closure_threshold": 80,
"minimum_snow_depth": 30,
"max_km_skiable": 31.0,
"url": "https://www.san-isidro.net",
"telegram_command": "/sanisidro",
"webcams": {
"snapshots": [
{
"label": "Cebolledo I",
"url": "https://www.nieveleonsanisidro.com/img/sanisidro/webcam/CebolledoI.jpg",
"static": True,
}
],
},
},
"fuentes": {
"name": "Fuentes de Invierno",
"latitude": 43.0833,
"longitude": -5.9333,
"altitude": 1500,
"wind_closure_threshold": 80,
"minimum_snow_depth": 30,
"max_km_skiable": 8.6,
"url": "https://www.fuentesdeinvierno.com",
"telegram_command": "/fuentes",
"webcams": {
"snapshots": [
{
"label": "Camara 1",
"url": "https://fuentesdeinvierno.com/tmp/camara1.jpg",
"static": True,
"ssl_verify": False,
}
],
},
},
}
}
def _make_analyzer(tmp_path: Path) -> "CrowdAnalyzer":
"""Return a CrowdAnalyzer with config loading and model instantiation bypassed."""
with patch(
"data_sources.crowd_analyzer.CrowdAnalyzer._load_stations",
return_value=_STATIONS_CONFIG["stations"],
):
from data_sources.crowd_analyzer import CrowdAnalyzer
analyzer = CrowdAnalyzer(
config_path=tmp_path / "stations.yaml",
output_dir=tmp_path,
)
return analyzer
def _make_yolo_result(
cls_names: list[str],
confidences: list[float],
) -> list[MagicMock]:
"""Build a fake YOLO results list with the given class names and confidences.
Parameters
----------
cls_names:
List of COCO class name strings for each detected box.
confidences:
Confidence score per detection (same order as cls_names).
"""
result = MagicMock()
result.names = {i: name for i, name in enumerate(set(cls_names))}
# Build a reverse lookup so the mock returns the right cls_id for each box.
name_to_id = {v: k for k, v in result.names.items()}
boxes = []
for name, conf in zip(cls_names, confidences):
box = MagicMock()
box.conf = [conf]
box.cls = [name_to_id[name]]
boxes.append(box)
result.boxes = boxes
return [result]
# ---------------------------------------------------------------------------
# Tests – instantiation
# ---------------------------------------------------------------------------
class TestInstantiation:
"""CrowdAnalyzer must be importable and instantiable without loading YOLO."""
def test_can_be_instantiated(self, tmp_path):
"""CrowdAnalyzer.__init__ must not attempt to load the YOLO model."""
analyzer = _make_analyzer(tmp_path)
# The model must remain un-loaded (lazy) after construction.
assert analyzer._model is None
def test_output_dir_is_created(self, tmp_path):
"""The output directory must exist after initialisation."""
out_dir = tmp_path / "outputs" / "raw"
with patch(
"data_sources.crowd_analyzer.CrowdAnalyzer._load_stations",
return_value=_STATIONS_CONFIG["stations"],
):
from data_sources.crowd_analyzer import CrowdAnalyzer
CrowdAnalyzer(
config_path=tmp_path / "stations.yaml",
output_dir=out_dir,
)
assert out_dir.is_dir()
def test_stations_are_loaded(self, tmp_path):
"""All three stations must be present in self.stations after init."""
analyzer = _make_analyzer(tmp_path)
assert set(analyzer.stations.keys()) == {"pajares", "sanisidro", "fuentes"}
# ---------------------------------------------------------------------------
# Tests – _classify_density thresholds
# ---------------------------------------------------------------------------
class TestClassifyDensity:
"""_classify_density must apply the documented car/person thresholds."""
# Import once so all methods share it.
@pytest.fixture(autouse=True)
def _import(self):
from data_sources.crowd_analyzer import CrowdAnalyzer
self.classify = CrowdAnalyzer._classify_density
# -- Low density --
def test_zero_cars_zero_people_is_low(self):
assert self.classify(0, 0) == "low"
def test_below_car_threshold_is_low(self):
"""19 cars and 0 people must produce 'low'."""
assert self.classify(19, 0) == "low"
def test_below_person_threshold_is_low(self):
"""0 cars and 9 people must produce 'low'."""
assert self.classify(0, 9) == "low"
# -- Medium density --
def test_car_at_low_threshold_is_medium(self):
"""Exactly 20 cars must cross into 'medium'."""
assert self.classify(20, 0) == "medium"
def test_car_at_high_threshold_is_medium(self):
"""Exactly 50 cars must still be 'medium' (not high)."""
assert self.classify(50, 0) == "medium"
def test_person_at_low_threshold_is_medium(self):
"""Exactly 10 people must cross into 'medium'."""
assert self.classify(0, 10) == "medium"
def test_person_at_high_threshold_is_medium(self):
"""Exactly 30 people must still be 'medium'."""
assert self.classify(0, 30) == "medium"
def test_mixed_medium_cars_low_people(self):
"""Medium cars + low people -> 'medium' (max wins)."""
assert self.classify(25, 5) == "medium"
# -- High density --
def test_above_car_threshold_is_high(self):
"""51 cars must produce 'high'."""
assert self.classify(51, 0) == "high"
def test_above_person_threshold_is_high(self):
"""31 people must produce 'high'."""
assert self.classify(0, 31) == "high"
def test_high_people_overrides_low_cars(self):
"""High person count must push density to 'high' even with few cars."""
assert self.classify(5, 35) == "high"
def test_high_cars_overrides_low_people(self):
"""High car count must push density to 'high' even with few people."""
assert self.classify(60, 2) == "high"
# -- Boundary correctness --
def test_boundary_19_cars_is_low(self):
assert self.classify(19, 0) == "low"
def test_boundary_20_cars_is_medium(self):
assert self.classify(20, 0) == "medium"
def test_boundary_50_cars_is_medium(self):
assert self.classify(50, 0) == "medium"
def test_boundary_51_cars_is_high(self):
assert self.classify(51, 0) == "high"
# ---------------------------------------------------------------------------
# Tests – analyze_image with mocked YOLO
# ---------------------------------------------------------------------------
class TestAnalyzeImage:
"""analyze_image must correctly aggregate YOLO detections."""
def _run(self, tmp_path: Path, cls_names: list[str], confidences: list[float]):
"""Helper: run analyze_image with a synthetic YOLO output."""
analyzer = _make_analyzer(tmp_path)
fake_results = _make_yolo_result(cls_names, confidences)
# Create a dummy image file so the path existence check passes.
img_path = tmp_path / "test_frame.jpg"
img_path.write_bytes(b"\xff\xd8\xff" + b"\x00" * 100)
# Mock both _load_model and the YOLO call.
mock_model = MagicMock(return_value=fake_results)
analyzer._model = mock_model
return analyzer.analyze_image(str(img_path))
def test_counts_cars_correctly(self, tmp_path):
"""Three cars in detections must produce cars_detected=3."""
result = self._run(tmp_path, ["car", "car", "car"], [0.9, 0.85, 0.8])
assert result["cars_detected"] == 3
def test_counts_people_correctly(self, tmp_path):
"""Two people detections must produce people_detected=2."""
result = self._run(tmp_path, ["person", "person"], [0.95, 0.88])
assert result["people_detected"] == 2
def test_counts_buses_correctly(self, tmp_path):
"""One bus detection must produce buses_detected=1."""
result = self._run(tmp_path, ["bus"], [0.7])
assert result["buses_detected"] == 1
def test_total_vehicles_excludes_people(self, tmp_path):
"""total_vehicles must count cars + buses + trucks, not people."""
result = self._run(
tmp_path,
["car", "person", "bus", "truck"],
[0.9, 0.9, 0.8, 0.75],
)
assert result["total_vehicles"] == 3 # car + bus + truck
assert result["people_detected"] == 1
def test_confidence_scores_are_included(self, tmp_path):
"""All detection confidence scores must be present in the result."""
result = self._run(tmp_path, ["car", "person"], [0.91, 0.82])
assert len(result["confidence_scores"]) == 2
assert all(0.0 <= s <= 1.0 for s in result["confidence_scores"])
def test_result_has_required_keys(self, tmp_path):
"""analyze_image must return all documented keys."""
result = self._run(tmp_path, [], [])
required = {
"cars_detected",
"people_detected",
"buses_detected",
"total_vehicles",
"crowd_density",
"confidence_scores",
"timestamp",
}
assert required.issubset(result.keys())
def test_crowd_density_is_valid_string(self, tmp_path):
"""crowd_density must be one of the three documented values."""
result = self._run(tmp_path, ["car"] * 5, [0.9] * 5)
assert result["crowd_density"] in {"low", "medium", "high"}
def test_empty_image_gives_low_density(self, tmp_path):
"""An image with no detections must yield density='low'."""
result = self._run(tmp_path, [], [])
assert result["crowd_density"] == "low"
def test_raises_file_not_found(self, tmp_path):
"""FileNotFoundError must be raised when the image path does not exist."""
analyzer = _make_analyzer(tmp_path)
analyzer._model = MagicMock()
with pytest.raises(FileNotFoundError):
analyzer.analyze_image(str(tmp_path / "nonexistent.jpg"))
# ---------------------------------------------------------------------------
# Tests – estimate_crowd_level
# ---------------------------------------------------------------------------
class TestEstimateCrowdLevel:
"""estimate_crowd_level must capture a webcam image and analyse it."""
def _run_with_mocks(
self,
tmp_path: Path,
station_id: str,
captured_paths: list[str],
cls_names: list[str],
confidences: list[float],
):
"""Run estimate_crowd_level with WebcamCollector and YOLO both mocked.
WebcamCollector is imported inside estimate_crowd_level at call-time,
so we patch it at its definition site in ``data_sources.webcam_collector``.
"""
analyzer = _make_analyzer(tmp_path)
# Ensure a real image file exists if the collector is to return a path.
for p in captured_paths:
Path(p).parent.mkdir(parents=True, exist_ok=True)
Path(p).write_bytes(b"\xff\xd8\xff" + b"\x00" * 100)
fake_results = _make_yolo_result(cls_names, confidences)
mock_yolo = MagicMock(return_value=fake_results)
analyzer._model = mock_yolo
# Patch at the definition module so the local import inside
# estimate_crowd_level picks up the mock.
with patch(
"data_sources.webcam_collector.WebcamCollector"
) as MockCollector:
mock_instance = MockCollector.return_value
mock_instance.capture.return_value = captured_paths
result = analyzer.estimate_crowd_level(station_id)
return result
def test_returns_crowd_density_string(self, tmp_path):
"""estimate_crowd_level must return a dict with a crowd_density key."""
img = str(tmp_path / "frame.jpg")
result = self._run_with_mocks(tmp_path, "pajares", [img], ["car"] * 5, [0.9] * 5)
assert "crowd_density" in result
assert result["crowd_density"] in {"low", "medium", "high", "unknown"}
def test_result_includes_station_id(self, tmp_path):
"""The returned dict must carry the station_id."""
img = str(tmp_path / "frame.jpg")
result = self._run_with_mocks(tmp_path, "sanisidro", [img], [], [])
assert result["station_id"] == "sanisidro"
def test_result_includes_image_path(self, tmp_path):
"""The returned dict must carry the image path used for analysis."""
img = str(tmp_path / "frame.jpg")
result = self._run_with_mocks(tmp_path, "fuentes", [img], [], [])
assert result["image_path"] == img
def test_unknown_density_when_no_capture(self, tmp_path):
"""When the webcam collector returns no images, density must be 'unknown'."""
result = self._run_with_mocks(tmp_path, "pajares", [], [], [])
assert result["crowd_density"] == "unknown"
def test_result_is_saved_to_json(self, tmp_path):
"""A JSON file must be written to output_dir after analysis."""
img = str(tmp_path / "frame.jpg")
self._run_with_mocks(tmp_path, "pajares", [img], ["person"] * 3, [0.9] * 3)
from datetime import date
today = date.today().strftime("%Y-%m-%d")
json_file = tmp_path / f"crowd_pajares_{today}.json"
assert json_file.exists()
def test_json_contains_valid_list(self, tmp_path):
"""The saved JSON file must contain a list with at least one result."""
img = str(tmp_path / "frame.jpg")
self._run_with_mocks(tmp_path, "pajares", [img], ["car"], [0.85])
from datetime import date
today = date.today().strftime("%Y-%m-%d")
json_file = tmp_path / f"crowd_pajares_{today}.json"
data = json.loads(json_file.read_text())
assert isinstance(data, list)
assert len(data) >= 1
def test_multiple_calls_append_to_json(self, tmp_path):
"""Successive calls must append results to the same JSON file."""
img = str(tmp_path / "frame.jpg")
self._run_with_mocks(tmp_path, "sanisidro", [img], ["car"], [0.9])
self._run_with_mocks(tmp_path, "sanisidro", [img], ["person"], [0.8])
from datetime import date
today = date.today().strftime("%Y-%m-%d")
json_file = tmp_path / f"crowd_sanisidro_{today}.json"
data = json.loads(json_file.read_text())
assert len(data) == 2
# ---------------------------------------------------------------------------
# Tests – analyze_all_stations
# ---------------------------------------------------------------------------
class TestAnalyzeAllStations:
"""analyze_all_stations must process every configured station."""
def test_returns_all_station_ids(self, tmp_path):
"""The result dict must contain keys for all three stations."""
analyzer = _make_analyzer(tmp_path)
# Patch estimate_crowd_level to avoid real I/O.
def _fake_estimate(station_id):
return {
"station_id": station_id,
"crowd_density": "low",
"cars_detected": 0,
"people_detected": 0,
"buses_detected": 0,
"total_vehicles": 0,
"confidence_scores": [],
"timestamp": "2026-01-01T12:00:00",
"image_path": None,
}
with patch.object(analyzer, "estimate_crowd_level", side_effect=_fake_estimate):
results = analyzer.analyze_all_stations()
assert set(results.keys()) == {"pajares", "sanisidro", "fuentes"}
def test_all_results_have_crowd_density(self, tmp_path):
"""Every station result must contain a crowd_density key."""
analyzer = _make_analyzer(tmp_path)
def _fake_estimate(station_id):
return {"station_id": station_id, "crowd_density": "medium"}
with patch.object(analyzer, "estimate_crowd_level", side_effect=_fake_estimate):
results = analyzer.analyze_all_stations()
for station_id, result in results.items():
assert "crowd_density" in result, f"Missing crowd_density for {station_id}"