mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
refactor(crowd_analysis): simplify table + upgrade YOLO + add regional holidays
- Remove internal YOLO counts (cars/people/buses/total_vehicles) from crowd_analysis table - Keep only crowd_density and confidence_scores for persistence (no ML training impact) - Upgrade from YOLOv8n to YOLOv11m for better person detection (fewer false positives) - Add regional holidays: Día de Castilla y León (4/23), Santiago Apóstol (7/25, shared with Galicia) - Add Easter Monday (moveable, 2018-2035) for Castilla y León and Galicia - Update all tests to match simplified crowd_analysis schema Tests: all 38 SQLite/crowd_analyzer tests + 13 feature tests passing.
This commit is contained in:
1 parent
fa7d61b7db
commit
5e2a22340f
5 files changed
+25
-78
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
"""Crowd density estimator using YOLOv8 object detection.
|
"""Crowd density estimator using YOLOv11 object detection.
|
||||||
|
|
||||||
Analyses webcam snapshot images from ski stations to estimate crowd levels.
|
Analyses webcam snapshot images from ski stations to estimate crowd levels.
|
||||||
Uses the YOLOv8 nano model (``yolov8n.pt``) from the ``ultralytics`` package
|
Uses the YOLOv11 medium model (``yolov11m.pt``) from the ``ultralytics`` package
|
||||||
to detect people, cars, buses and trucks.
|
to detect people, cars, buses and trucks.
|
||||||
|
|
||||||
Detected object counts are mapped to three crowd density levels:
|
Detected object counts are mapped to three crowd density levels:
|
||||||
@@ -36,7 +36,7 @@ BASE_DIR = Path(__file__).resolve().parent.parent
|
|||||||
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
|
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
|
||||||
|
|
||||||
# YOLO model weights file – downloaded automatically on first use.
|
# YOLO model weights file – downloaded automatically on first use.
|
||||||
YOLO_MODEL_WEIGHTS = "yolov8n.pt"
|
YOLO_MODEL_WEIGHTS = "yolov11m.pt"
|
||||||
|
|
||||||
# COCO class names that count towards crowd estimation.
|
# COCO class names that count towards crowd estimation.
|
||||||
VEHICLE_CLASSES = {"car", "bus", "truck", "motorcycle"}
|
VEHICLE_CLASSES = {"car", "bus", "truck", "motorcycle"}
|
||||||
@@ -66,8 +66,8 @@ class CrowdAnalyzer:
|
|||||||
Path to the stations YAML configuration file. Defaults to
|
Path to the stations YAML configuration file. Defaults to
|
||||||
``config/stations.yaml`` relative to the project root.
|
``config/stations.yaml`` relative to the project root.
|
||||||
model_weights:
|
model_weights:
|
||||||
YOLOv8 weights identifier passed to ``ultralytics.YOLO()``.
|
YOLOv11 weights identifier passed to ``ultralytics.YOLO()``.
|
||||||
Defaults to ``"yolov8n.pt"`` (nano model).
|
Defaults to ``"yolov11m.pt"`` (medium model).
|
||||||
store:
|
store:
|
||||||
SQLite store where analysis results are written.
|
SQLite store where analysis results are written.
|
||||||
"""
|
"""
|
||||||
@@ -101,10 +101,6 @@ class CrowdAnalyzer:
|
|||||||
dict
|
dict
|
||||||
Keys:
|
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"``
|
* ``crowd_density`` – ``"low"``, ``"medium"``, or ``"high"``
|
||||||
* ``confidence_scores`` – list of per-detection confidence values
|
* ``confidence_scores`` – list of per-detection confidence values
|
||||||
* ``timestamp`` – ISO-8601 timestamp of when analysis ran
|
* ``timestamp`` – ISO-8601 timestamp of when analysis ran
|
||||||
@@ -153,10 +149,6 @@ class CrowdAnalyzer:
|
|||||||
total_vehicles = cars + buses + trucks
|
total_vehicles = cars + buses + trucks
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"cars_detected": cars,
|
|
||||||
"people_detected": people,
|
|
||||||
"buses_detected": buses,
|
|
||||||
"total_vehicles": total_vehicles,
|
|
||||||
"crowd_density": self._classify_density(cars, people),
|
"crowd_density": self._classify_density(cars, people),
|
||||||
"confidence_scores": confidence_scores,
|
"confidence_scores": confidence_scores,
|
||||||
"timestamp": datetime.now().isoformat(timespec="seconds"),
|
"timestamp": datetime.now().isoformat(timespec="seconds"),
|
||||||
@@ -321,10 +313,6 @@ class CrowdAnalyzer:
|
|||||||
return {
|
return {
|
||||||
"station_id": station_id,
|
"station_id": station_id,
|
||||||
"image_path": image_path,
|
"image_path": image_path,
|
||||||
"cars_detected": 0,
|
|
||||||
"people_detected": 0,
|
|
||||||
"buses_detected": 0,
|
|
||||||
"total_vehicles": 0,
|
|
||||||
"crowd_density": "unknown",
|
"crowd_density": "unknown",
|
||||||
"confidence_scores": [],
|
"confidence_scores": [],
|
||||||
"timestamp": datetime.now().isoformat(timespec="seconds"),
|
"timestamp": datetime.now().isoformat(timespec="seconds"),
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ _SPANISH_HOLIDAYS: set[tuple[int, int]] = {
|
|||||||
(1, 1), # New Year's Day
|
(1, 1), # New Year's Day
|
||||||
(1, 6), # Epiphany
|
(1, 6), # Epiphany
|
||||||
(5, 1), # Labour Day
|
(5, 1), # Labour Day
|
||||||
|
(7, 25), # Santiago Apóstol (National + Día de Galicia)
|
||||||
(8, 15), # Assumption of Mary
|
(8, 15), # Assumption of Mary
|
||||||
(10, 12), # National Day of Spain
|
(10, 12), # National Day of Spain
|
||||||
(11, 1), # All Saints' Day
|
(11, 1), # All Saints' Day
|
||||||
@@ -32,6 +33,8 @@ _SPANISH_HOLIDAYS: set[tuple[int, int]] = {
|
|||||||
(12, 25), # Christmas Day
|
(12, 25), # Christmas Day
|
||||||
# Asturian regional
|
# Asturian regional
|
||||||
(9, 8), # Day of Asturias
|
(9, 8), # Day of Asturias
|
||||||
|
# Castilla y León regional
|
||||||
|
(4, 23), # Día de Castilla y León
|
||||||
}
|
}
|
||||||
|
|
||||||
# Approximate Good Friday dates for years 2018-2035 (moveable feast).
|
# Approximate Good Friday dates for years 2018-2035 (moveable feast).
|
||||||
@@ -57,6 +60,16 @@ _GOOD_FRIDAY: dict[int, tuple[int, int]] = {
|
|||||||
2035: (3, 23),
|
2035: (3, 23),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Easter Monday dates for years 2018-2035 (Good Friday + 3 days).
|
||||||
|
# Regional holiday in Castilla y León and Galicia.
|
||||||
|
_EASTER_MONDAY: dict[int, tuple[int, int]] = {
|
||||||
|
2018: (4, 2), 2019: (4, 22), 2020: (4, 13), 2021: (4, 5),
|
||||||
|
2022: (4, 18), 2023: (4, 10), 2024: (4, 1), 2025: (4, 21),
|
||||||
|
2026: (4, 6), 2027: (3, 29), 2028: (4, 17), 2029: (4, 2),
|
||||||
|
2030: (4, 22), 2031: (4, 14), 2032: (3, 29), 2033: (4, 18),
|
||||||
|
2034: (4, 10), 2035: (3, 26),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def _build_holiday_set(years: Optional[list[int]] = None) -> set[pd.Timestamp]:
|
def _build_holiday_set(years: Optional[list[int]] = None) -> set[pd.Timestamp]:
|
||||||
"""Return a set of Timestamps for every known holiday across the given years.
|
"""Return a set of Timestamps for every known holiday across the given years.
|
||||||
@@ -81,6 +94,10 @@ def _build_holiday_set(years: Optional[list[int]] = None) -> set[pd.Timestamp]:
|
|||||||
if gf:
|
if gf:
|
||||||
holidays.add(pd.Timestamp(year=year, month=gf[0], day=gf[1]))
|
holidays.add(pd.Timestamp(year=year, month=gf[0], day=gf[1]))
|
||||||
|
|
||||||
|
em = _EASTER_MONDAY.get(year)
|
||||||
|
if em:
|
||||||
|
holidays.add(pd.Timestamp(year=year, month=em[0], day=em[1]))
|
||||||
|
|
||||||
return holidays
|
return holidays
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+2
-15
@@ -318,24 +318,16 @@ class SQLiteStore:
|
|||||||
analysis_date,
|
analysis_date,
|
||||||
station_id,
|
station_id,
|
||||||
image_path,
|
image_path,
|
||||||
cars_detected,
|
|
||||||
people_detected,
|
|
||||||
buses_detected,
|
|
||||||
total_vehicles,
|
|
||||||
crowd_density,
|
crowd_density,
|
||||||
confidence_scores_json
|
confidence_scores_json
|
||||||
)
|
)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
analyzed_at,
|
analyzed_at,
|
||||||
analysis_date,
|
analysis_date,
|
||||||
result.get("station_id"),
|
result.get("station_id"),
|
||||||
result.get("image_path"),
|
result.get("image_path"),
|
||||||
int(result.get("cars_detected", 0)),
|
|
||||||
int(result.get("people_detected", 0)),
|
|
||||||
int(result.get("buses_detected", 0)),
|
|
||||||
int(result.get("total_vehicles", 0)),
|
|
||||||
result.get("crowd_density"),
|
result.get("crowd_density"),
|
||||||
json.dumps(result.get("confidence_scores") or [], ensure_ascii=False),
|
json.dumps(result.get("confidence_scores") or [], ensure_ascii=False),
|
||||||
),
|
),
|
||||||
@@ -370,8 +362,7 @@ class SQLiteStore:
|
|||||||
|
|
||||||
query = f"""
|
query = f"""
|
||||||
SELECT analyzed_at, analysis_date, station_id, image_path,
|
SELECT analyzed_at, analysis_date, station_id, image_path,
|
||||||
cars_detected, people_detected, buses_detected,
|
crowd_density, confidence_scores_json
|
||||||
total_vehicles, crowd_density, confidence_scores_json
|
|
||||||
FROM crowd_analysis
|
FROM crowd_analysis
|
||||||
{where}
|
{where}
|
||||||
ORDER BY analyzed_at ASC, id ASC
|
ORDER BY analyzed_at ASC, id ASC
|
||||||
@@ -645,10 +636,6 @@ class SQLiteStore:
|
|||||||
analysis_date TEXT NOT NULL,
|
analysis_date TEXT NOT NULL,
|
||||||
station_id TEXT NOT NULL,
|
station_id TEXT NOT NULL,
|
||||||
image_path TEXT,
|
image_path TEXT,
|
||||||
cars_detected INTEGER NOT NULL,
|
|
||||||
people_detected INTEGER NOT NULL,
|
|
||||||
buses_detected INTEGER NOT NULL,
|
|
||||||
total_vehicles INTEGER NOT NULL,
|
|
||||||
crowd_density TEXT NOT NULL,
|
crowd_density TEXT NOT NULL,
|
||||||
confidence_scores_json TEXT NOT NULL
|
confidence_scores_json TEXT NOT NULL
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -274,31 +274,6 @@ class TestAnalyzeImage:
|
|||||||
|
|
||||||
return analyzer.analyze_image(str(img_path))
|
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):
|
def test_confidence_scores_are_included(self, tmp_path):
|
||||||
"""All detection confidence scores must be present in the result."""
|
"""All detection confidence scores must be present in the result."""
|
||||||
result = self._run(tmp_path, ["car", "person"], [0.91, 0.82])
|
result = self._run(tmp_path, ["car", "person"], [0.91, 0.82])
|
||||||
@@ -308,15 +283,7 @@ class TestAnalyzeImage:
|
|||||||
def test_result_has_required_keys(self, tmp_path):
|
def test_result_has_required_keys(self, tmp_path):
|
||||||
"""analyze_image must return all documented keys."""
|
"""analyze_image must return all documented keys."""
|
||||||
result = self._run(tmp_path, [], [])
|
result = self._run(tmp_path, [], [])
|
||||||
required = {
|
required = {"crowd_density", "confidence_scores", "timestamp"}
|
||||||
"cars_detected",
|
|
||||||
"people_detected",
|
|
||||||
"buses_detected",
|
|
||||||
"total_vehicles",
|
|
||||||
"crowd_density",
|
|
||||||
"confidence_scores",
|
|
||||||
"timestamp",
|
|
||||||
}
|
|
||||||
assert required.issubset(result.keys())
|
assert required.issubset(result.keys())
|
||||||
|
|
||||||
def test_crowd_density_is_valid_string(self, tmp_path):
|
def test_crowd_density_is_valid_string(self, tmp_path):
|
||||||
@@ -455,10 +422,6 @@ class TestAnalyzeAllStations:
|
|||||||
return {
|
return {
|
||||||
"station_id": station_id,
|
"station_id": station_id,
|
||||||
"crowd_density": "low",
|
"crowd_density": "low",
|
||||||
"cars_detected": 0,
|
|
||||||
"people_detected": 0,
|
|
||||||
"buses_detected": 0,
|
|
||||||
"total_vehicles": 0,
|
|
||||||
"confidence_scores": [],
|
"confidence_scores": [],
|
||||||
"timestamp": "2026-01-01T12:00:00",
|
"timestamp": "2026-01-01T12:00:00",
|
||||||
"image_path": None,
|
"image_path": None,
|
||||||
|
|||||||
@@ -107,10 +107,6 @@ def test_crowd_analysis_roundtrip(tmp_path):
|
|||||||
"timestamp": "2026-03-13T11:00:00",
|
"timestamp": "2026-03-13T11:00:00",
|
||||||
"station_id": "sanisidro",
|
"station_id": "sanisidro",
|
||||||
"image_path": "/tmp/frame.jpg",
|
"image_path": "/tmp/frame.jpg",
|
||||||
"cars_detected": 5,
|
|
||||||
"people_detected": 2,
|
|
||||||
"buses_detected": 0,
|
|
||||||
"total_vehicles": 5,
|
|
||||||
"crowd_density": "low",
|
"crowd_density": "low",
|
||||||
"confidence_scores": [0.91, 0.88],
|
"confidence_scores": [0.91, 0.88],
|
||||||
}
|
}
|
||||||
@@ -120,10 +116,6 @@ def test_crowd_analysis_roundtrip(tmp_path):
|
|||||||
"timestamp": "2026-03-13T12:00:00",
|
"timestamp": "2026-03-13T12:00:00",
|
||||||
"station_id": "sanisidro",
|
"station_id": "sanisidro",
|
||||||
"image_path": "/tmp/frame2.jpg",
|
"image_path": "/tmp/frame2.jpg",
|
||||||
"cars_detected": 25,
|
|
||||||
"people_detected": 4,
|
|
||||||
"buses_detected": 1,
|
|
||||||
"total_vehicles": 26,
|
|
||||||
"crowd_density": "medium",
|
"crowd_density": "medium",
|
||||||
"confidence_scores": [0.77],
|
"confidence_scores": [0.77],
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user