forked from andrew/feedmill-recounter
755 lines
31 KiB
Python
755 lines
31 KiB
Python
import json
|
|
import os
|
|
import pytest
|
|
from shapely.geometry import Point
|
|
from src.zone_config import (
|
|
DEFAULT_ZONES,
|
|
build_counting_polygon,
|
|
build_static_roi,
|
|
build_truck_polygon,
|
|
list_zone_presets,
|
|
load_zone_config,
|
|
normalize_zone_preset,
|
|
resolve_zone,
|
|
save_zone_preset,
|
|
sync_fcp_zones,
|
|
validate_zone_preset,
|
|
)
|
|
|
|
# FCP's detection_poly_pts at reference resolution (predict.py:692-697).
|
|
FCP_COUNTING_AREA = [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
|
|
|
|
|
|
def test_load_zone_config_reads_json(tmp_path):
|
|
cfg = {"presets": {"test": {"count_line": {"x_start": 100, "x_end": 200, "y": 150}}}, "active_preset": "test"}
|
|
p = tmp_path / "zones.json"
|
|
p.write_text(json.dumps(cfg))
|
|
result = load_zone_config(str(p))
|
|
assert result["active_preset"] == "test"
|
|
assert result["presets"]["test"]["count_line"]["y"] == 150
|
|
|
|
|
|
def test_build_static_roi_from_zone_config():
|
|
zone = {
|
|
"truck_area": [[100, 50], [110, 300], [400, 310], [390, 40]],
|
|
"count_line": {"x_start": 110, "x_end": 400, "y": 150},
|
|
"reference_resolution": [640, 480],
|
|
}
|
|
roi = build_static_roi(zone, video_w=640, video_h=480)
|
|
assert roi.line_y == 150
|
|
assert roi.confidence == 1.0
|
|
assert roi.x1 < roi.x2
|
|
assert roi.y1 < roi.y2
|
|
|
|
|
|
def test_build_static_roi_scales_coords():
|
|
zone = {
|
|
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
|
}
|
|
roi = build_static_roi(zone, video_w=1920, video_h=1080)
|
|
assert roi.line_y == 330
|
|
assert roi.x1 == 600
|
|
assert roi.x2 == 1404
|
|
|
|
|
|
def test_build_static_roi_scales_from_1080p_to_720p():
|
|
zone = {
|
|
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
|
"reference_resolution": [1920, 1080],
|
|
}
|
|
roi = build_static_roi(zone, video_w=1280, video_h=720)
|
|
assert roi.line_y == int(330 * 720 / 1080)
|
|
assert roi.x1 == int(600 * 1280 / 1920)
|
|
assert roi.x2 == int(1404 * 1280 / 1920)
|
|
|
|
|
|
def test_build_static_roi_does_not_double_scale_count_line_fallbacks():
|
|
"""A count_line without x_start/x_end/y falls back to the frame-space bounds.
|
|
|
|
The fallbacks are already scaled (x1/x2/y1/y2 live in the analysis
|
|
frame) — scaling them a second time would move the counting window.
|
|
"""
|
|
zone = {"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"count_line": {"x_end": 1401, "y": 330},
|
|
"reference_resolution": [1920, 1080]}
|
|
roi = build_static_roi(zone, 1280, 720)
|
|
assert (roi.x1, roi.x2) == (400, 936)
|
|
assert roi.line_x_start == roi.x1 # not int(400 * 1280/1920)
|
|
assert roi.line_x_end == 934
|
|
assert roi.line_y == 220
|
|
|
|
zone_no_y = {"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"count_line": {"x_start": 577, "x_end": 1401},
|
|
"reference_resolution": [1920, 1080]}
|
|
roi2 = build_static_roi(zone_no_y, 1280, 720)
|
|
assert roi2.line_y == (roi2.y1 + roi2.y2) // 2 # not scaled twice
|
|
|
|
|
|
# ── Counting polygon (FCP detection_polygon parity) ──────────────────────
|
|
|
|
def _polygon_coords(poly):
|
|
"""Polygon ring as a list of (x, y) int tuples."""
|
|
return [(int(x), int(y)) for x, y in poly.exterior.coords]
|
|
|
|
|
|
def test_build_counting_polygon_matches_fcp_reference_polygon():
|
|
"""Scaled to 1280x720 the polygon equals FCP's detection_polygon.
|
|
|
|
FCP main predict.py:761-769 scales 1920x1080 points by 1280/1920 and
|
|
720/1080 and rounds with int(round(...)).
|
|
"""
|
|
zone = {"counting_area": FCP_COUNTING_AREA, "reference_resolution": [1920, 1080]}
|
|
poly = build_counting_polygon(zone, 1280, 720)
|
|
assert _polygon_coords(poly) == [
|
|
(383, 33), (391, 718), (945, 717), (931, 33), (383, 33),
|
|
]
|
|
|
|
|
|
def test_build_counting_polygon_defaults_to_1920x1080_reference():
|
|
"""A zone without reference_resolution uses FCP's 1920x1080 default."""
|
|
poly = build_counting_polygon({"counting_area": FCP_COUNTING_AREA}, 1280, 720)
|
|
assert _polygon_coords(poly) == [
|
|
(383, 33), (391, 718), (945, 717), (931, 33), (383, 33),
|
|
]
|
|
|
|
|
|
def test_build_counting_polygon_at_reference_resolution_is_unscaled():
|
|
"""At the reference resolution the points are unchanged."""
|
|
zone = {"counting_area": FCP_COUNTING_AREA, "reference_resolution": [1920, 1080]}
|
|
poly = build_counting_polygon(zone, 1920, 1080)
|
|
assert _polygon_coords(poly) == [
|
|
(574, 50), (586, 1077), (1418, 1076), (1397, 50), (574, 50),
|
|
]
|
|
|
|
|
|
def test_build_counting_polygon_none_without_counting_area():
|
|
"""No counting_area -> no polygon (the filter stays off)."""
|
|
assert build_counting_polygon({}, 1280, 720) is None
|
|
assert build_counting_polygon({"truck_area": [[0, 0]]}, 1280, 720) is None
|
|
assert build_counting_polygon({"counting_area": []}, 1280, 720) is None
|
|
|
|
|
|
def test_build_counting_polygon_contains_centroid_semantics():
|
|
"""contains() on the bbox centre mirrors FCP's detection_polygon check."""
|
|
poly = build_counting_polygon({"counting_area": FCP_COUNTING_AREA}, 1280, 720)
|
|
assert poly.contains(Point((620.0, 320.0))) # inside
|
|
assert not poly.contains(Point((70.0, 320.0))) # left of the polygon
|
|
assert not poly.contains(Point((1200.0, 320.0))) # right of the polygon
|
|
|
|
|
|
def test_list_zone_presets(tmp_path):
|
|
cfg = {"presets": {"p1": {"description": "Zone 1"}, "p2": {"description": "Zone 2"}}}
|
|
p = tmp_path / "zones.json"
|
|
p.write_text(json.dumps(cfg))
|
|
presets = list_zone_presets(str(p))
|
|
assert len(presets) == 2
|
|
names = [p["name"] for p in presets]
|
|
assert "p1" in names
|
|
assert "p2" in names
|
|
|
|
|
|
# ── Truck-area polygon (FCP predict.py:706-712) ──────────────────────────
|
|
|
|
# FCP's truck_poly_pts at reference resolution (predict.py:706-712).
|
|
FCP_TRUCK_AREA = [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
|
|
|
|
|
|
def test_build_truck_polygon_matches_fcp_reference_polygon():
|
|
"""The truck polygon is FCP's, scaled to the analysis frame with int(round(...))."""
|
|
poly = build_truck_polygon(
|
|
{"truck_area": FCP_TRUCK_AREA, "reference_resolution": [1920, 1080]},
|
|
1280,
|
|
720,
|
|
)
|
|
assert list(poly.exterior.coords) == [
|
|
(400.0, 257.0), (406.0, 717.0), (936.0, 719.0), (921.0, 229.0), (400.0, 257.0)
|
|
]
|
|
|
|
|
|
def test_build_truck_polygon_at_reference_resolution_is_unscaled():
|
|
poly = build_truck_polygon(
|
|
{"truck_area": FCP_TRUCK_AREA, "reference_resolution": [1920, 1080]},
|
|
1920,
|
|
1080,
|
|
)
|
|
assert list(poly.exterior.coords)[:4] == [
|
|
(600.0, 385.0), (609.0, 1076.0), (1404.0, 1078.0), (1381.0, 343.0)
|
|
]
|
|
|
|
|
|
def test_build_truck_polygon_defaults_to_1920x1080_reference():
|
|
poly = build_truck_polygon({"truck_area": FCP_TRUCK_AREA}, 1280, 720)
|
|
assert list(poly.exterior.coords)[0] == (400.0, 257.0)
|
|
|
|
|
|
def test_build_counting_polygon_none_on_a_degenerate_polygon():
|
|
"""Three collinear points have no interior — the filter would zero every count."""
|
|
assert build_counting_polygon(
|
|
{"counting_area": [[0, 0], [10, 0], [20, 0]]}, 1280, 720
|
|
) is None
|
|
|
|
|
|
def test_build_static_roi_rejects_a_missing_or_malformed_truck_area():
|
|
"""No calibration -> ValueError. An invented ROI must not pass as calibrated."""
|
|
import pytest
|
|
|
|
with pytest.raises(ValueError):
|
|
build_static_roi({"count_line": {"x_start": 577, "x_end": 1401, "y": 330}},
|
|
1280, 720)
|
|
with pytest.raises(ValueError):
|
|
build_static_roi({"truck_area": [[0, 0]]}, 1280, 720)
|
|
with pytest.raises(ValueError):
|
|
build_static_roi({"truck_area": [[0, 0], [1, 1], [2, 2]]}, 1280, 720)
|
|
with pytest.raises(ValueError):
|
|
build_static_roi({"truck_area": [["a", "b"], [1, 1], [2, 2], [3, 3]]},
|
|
1280, 720)
|
|
|
|
|
|
def test_build_truck_polygon_none_without_truck_area():
|
|
assert build_truck_polygon({}, 1280, 720) is None
|
|
assert build_truck_polygon({"truck_area": []}, 1280, 720) is None
|
|
|
|
|
|
def test_build_truck_polygon_none_with_too_few_points():
|
|
assert build_truck_polygon({"truck_area": [[0, 0], [10, 10]]}, 1280, 720) is None
|
|
|
|
|
|
def test_build_truck_polygon_none_on_malformed_truck_area():
|
|
"""A malformed calibration degrades to "no truck area", never raises."""
|
|
assert build_truck_polygon({"truck_area": [["a", "b"], [1, 2], [3, 4]]}, 1280, 720) is None
|
|
assert build_truck_polygon({"truck_area": [1, 2, 3]}, 1280, 720) is None
|
|
assert build_truck_polygon({"truck_area": "nope"}, 1280, 720) is None
|
|
assert build_truck_polygon({"truck_area": 5}, 1280, 720) is None
|
|
|
|
|
|
def test_build_truck_polygon_none_on_a_three_number_point():
|
|
"""A 3-number point is rejected, not silently truncated to two."""
|
|
assert build_truck_polygon(
|
|
{"truck_area": [[0, 0, 0], [10, 10], [20, 0]]}, 1280, 720
|
|
) is None
|
|
|
|
|
|
def test_build_truck_polygon_none_on_a_non_dict_zone():
|
|
"""A non-dict zone must not raise."""
|
|
assert build_truck_polygon(None, 1280, 720) is None
|
|
assert build_truck_polygon(["not", "a", "dict"], 1280, 720) is None
|
|
|
|
|
|
def test_build_truck_polygon_none_on_non_finite_coordinates():
|
|
"""NaN/inf coordinates would make shapely raise — degrade instead."""
|
|
assert build_truck_polygon(
|
|
{"truck_area": [[float("nan"), 0], [10, 10], [20, 0]]}, 1280, 720
|
|
) is None
|
|
assert build_truck_polygon(
|
|
{"truck_area": [[float("inf"), 0], [10, 10], [20, 0]]}, 1280, 720
|
|
) is None
|
|
|
|
|
|
def test_build_counting_polygon_none_on_malformed_counting_area():
|
|
"""The counting polygon builder never raises either (same contract)."""
|
|
assert build_counting_polygon({"counting_area": [["a", "b"], [1, 2], [3, 4]]}, 1280, 720) is None
|
|
assert build_counting_polygon({"counting_area": [1, 2, 3]}, 1280, 720) is None
|
|
assert build_counting_polygon({"counting_area": "nope"}, 1280, 720) is None
|
|
assert build_counting_polygon({"counting_area": 5}, 1280, 720) is None
|
|
|
|
|
|
def test_build_counting_polygon_none_on_a_three_number_point():
|
|
assert build_counting_polygon(
|
|
{"counting_area": [[0, 0, 0], [10, 10], [20, 0]]}, 1280, 720
|
|
) is None
|
|
|
|
|
|
def test_build_counting_polygon_none_on_a_non_dict_zone():
|
|
assert build_counting_polygon(None, 1280, 720) is None
|
|
assert build_counting_polygon(["not", "a", "dict"], 1280, 720) is None
|
|
|
|
|
|
def test_build_counting_polygon_none_on_non_finite_coordinates():
|
|
assert build_counting_polygon(
|
|
{"counting_area": [[float("nan"), 0], [10, 10], [20, 0]]}, 1280, 720
|
|
) is None
|
|
assert build_counting_polygon(
|
|
{"counting_area": [[float("inf"), 0], [10, 10], [20, 0]]}, 1280, 720
|
|
) is None
|
|
|
|
|
|
# ── Count-line x-window (FCP predict.py:701-703 parity) ──────────────────
|
|
|
|
|
|
def test_build_static_roi_carries_the_count_line_x_window():
|
|
"""The ROI carries FCP's calibrated count-line x-window.
|
|
|
|
FCP main predict.py:781-783 scales the count line to the 1280x720 analysis
|
|
frame with int(round(...)): x 385...934, y 220.
|
|
"""
|
|
zone = {
|
|
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
|
"reference_resolution": [1920, 1080],
|
|
}
|
|
roi = build_static_roi(zone, video_w=1280, video_h=720)
|
|
assert roi.line_x_start == 385 # int(round(577 * 1280 / 1920))
|
|
assert roi.line_x_end == 934 # int(round(1401 * 1280 / 1920))
|
|
assert roi.line_y == 220 # int(round(330 * 720 / 1080))
|
|
|
|
|
|
def test_build_static_roi_without_count_line_has_no_x_window():
|
|
"""No calibrated line -> no x-window; the counter falls back to the ROI bounds."""
|
|
roi = build_static_roi(
|
|
{"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]},
|
|
video_w=1280,
|
|
video_h=720,
|
|
)
|
|
assert roi.line_x_start is None
|
|
assert roi.line_x_end is None
|
|
|
|
|
|
# ── Shipped preset (FCP main calibration in native 1920x1080 space) ──────
|
|
|
|
|
|
def test_shipped_default_preset_matches_fcp_live_calibration():
|
|
"""The default preset is FCP main (91d8b48) in 1920x1080, scaled to 1280x720 at runtime."""
|
|
zone = {
|
|
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
|
"count_line": {"x_start": 577, "x_end": 1401, "y": 215},
|
|
"reference_resolution": [1920, 1080],
|
|
}
|
|
roi = build_static_roi(zone, video_w=1280, video_h=720)
|
|
assert (roi.x1, roi.y1, roi.x2, roi.y2) == (400, 193, 936, 719)
|
|
assert roi.line_y == 143
|
|
assert roi.line_x_start == 385
|
|
assert roi.line_x_end == 934
|
|
assert roi.confidence == 1.0
|
|
assert roi.fixed is True
|
|
|
|
|
|
def test_shipped_default_preset_polygons_are_usable():
|
|
"""Both shipped polygons are valid and scaled accurately to 1280x720."""
|
|
zone = {
|
|
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"reference_resolution": [1920, 1080],
|
|
}
|
|
counting = build_counting_polygon(zone, 1280, 720)
|
|
truck = build_truck_polygon(zone, 1280, 720)
|
|
assert counting is not None and counting.area > 0
|
|
assert truck is not None and truck.area > 0
|
|
assert _polygon_coords(counting) == [(383, 33), (391, 718), (945, 717), (931, 33), (383, 33)]
|
|
assert _polygon_coords(truck) == [(400, 193), (406, 717), (936, 719), (921, 193), (400, 193)]
|
|
assert counting.contains(Point(600, 300))
|
|
|
|
|
|
GOOD_PRESET = {
|
|
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
|
"reference_resolution": [1920, 1080],
|
|
}
|
|
|
|
|
|
def test_validate_zone_preset_accepts_good_geometry():
|
|
assert validate_zone_preset(GOOD_PRESET) == GOOD_PRESET
|
|
|
|
|
|
def test_validate_zone_preset_rejects_degenerate_polygon():
|
|
bad = {**GOOD_PRESET, "truck_area": [[600, 385], [600, 385], [600, 385], [600, 385]]}
|
|
with pytest.raises(ValueError, match="truck_area"):
|
|
validate_zone_preset(bad)
|
|
|
|
|
|
def test_validate_zone_preset_rejects_out_of_bounds_point():
|
|
bad = {**GOOD_PRESET, "counting_area": [[574, 50], [586, 1077], [1418, 1076], [1950, 50]]}
|
|
with pytest.raises(ValueError, match="counting_area"):
|
|
validate_zone_preset(bad)
|
|
|
|
|
|
def test_validate_zone_preset_rejects_inverted_count_line():
|
|
bad = {**GOOD_PRESET, "count_line": {"x_start": 1401, "x_end": 577, "y": 330}}
|
|
with pytest.raises(ValueError, match="count_line"):
|
|
validate_zone_preset(bad)
|
|
|
|
|
|
def test_save_zone_preset_preserves_siblings_and_active_preset(tmp_path):
|
|
path = str(tmp_path / "zones.json")
|
|
cfg = {"presets": {"other": {"count_line": {"x_start": 1, "x_end": 2, "y": 3}}},
|
|
"active_preset": "other"}
|
|
with open(path, "w") as f:
|
|
json.dump(cfg, f)
|
|
save_zone_preset(path, "default", GOOD_PRESET)
|
|
saved = json.load(open(path))
|
|
assert saved["presets"]["other"]["count_line"] == {"x_start": 1, "x_end": 2, "y": 3}
|
|
assert saved["active_preset"] == "other"
|
|
assert saved["presets"]["default"]["truck_area"] == GOOD_PRESET["truck_area"]
|
|
assert os.path.isfile(path + ".bak")
|
|
|
|
|
|
def test_save_zone_preset_keeps_knob_keys_of_the_edited_preset(tmp_path):
|
|
path = str(tmp_path / "zones.json")
|
|
cfg = {"presets": {"default": {**GOOD_PRESET, "duplicate_circle_radius": 30}},
|
|
"active_preset": "default"}
|
|
with open(path, "w") as f:
|
|
json.dump(cfg, f)
|
|
save_zone_preset(path, "default", {"truck_area": [[1, 1], [10, 1], [10, 10], [1, 10]]})
|
|
saved = json.load(open(path))
|
|
assert saved["presets"]["default"]["duplicate_circle_radius"] == 30
|
|
|
|
|
|
def test_repo_zones_json_ships_the_fcp_calibrations():
|
|
"""Guards the shipped file, not an inline fixture."""
|
|
repo_zones = os.path.join(os.path.dirname(os.path.dirname(__file__)), "zones.json")
|
|
cfg = load_zone_config(repo_zones)
|
|
assert cfg["active_preset"] == "default"
|
|
live = cfg["presets"]["default"]
|
|
assert live["reference_resolution"] == [1920, 1080]
|
|
assert live["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
|
assert live["truck_area"] == [[600, 290], [609, 1076], [1404, 1078], [1381, 290]]
|
|
assert live["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
|
|
assert live["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
|
|
assert DEFAULT_ZONES["default"]["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
|
|
roi = build_static_roi(live, 1280, 720)
|
|
assert (roi.x1, roi.y1, roi.x2, roi.y2) == (400, 193, 936, 719)
|
|
assert (roi.line_x_start, roi.line_x_end, roi.line_y) == (385, 934, 143)
|
|
legacy = cfg["presets"]["fcp-2026-10-15"]
|
|
assert legacy["reference_resolution"] == [1920, 1080]
|
|
assert legacy["count_line"] == {"x_start": 577, "x_end": 1401, "y": 330}
|
|
assert legacy["truck_area"] == [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
|
|
assert legacy["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
|
|
assert legacy["palet"] == [[612, 628], [1454, 630], [1458, 1074], [608, 1071]]
|
|
assert DEFAULT_ZONES["fcp-2026-10-15"]["palet"] == [[612, 628], [1454, 630], [1458, 1074], [608, 1071]]
|
|
|
|
|
|
# --- fix round 1: F1 reference_resolution, F2/F3 count_line, F4 truck_area ---
|
|
|
|
def test_validate_zone_preset_rejects_a_foreign_reference_resolution():
|
|
"""F1: raw validate_zone_preset rejects un-normalized non-1080p presets."""
|
|
bad = {**GOOD_PRESET, "reference_resolution": [1280, 720]}
|
|
with pytest.raises(ValueError, match="reference_resolution"):
|
|
validate_zone_preset(bad)
|
|
|
|
|
|
def test_validate_zone_preset_accepts_a_preset_without_reference_resolution():
|
|
"""F1: the key is optional; 1920x1080 is the native zone space."""
|
|
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
|
|
assert validate_zone_preset(preset) is not None
|
|
|
|
|
|
def test_validate_zone_preset_rejects_a_non_finite_count_line():
|
|
"""F2: int(float('inf')) raises OverflowError, which used to 500."""
|
|
bad = {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1401, "y": float("inf")}}
|
|
with pytest.raises(ValueError, match="count_line"):
|
|
validate_zone_preset(bad)
|
|
|
|
|
|
def test_validate_zone_preset_rejects_a_fractional_count_line():
|
|
"""F3: bounds were checked on the truncated int, the raw float was stored."""
|
|
bad = {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.9, "y": 330}}
|
|
with pytest.raises(ValueError, match="count_line"):
|
|
validate_zone_preset(bad)
|
|
|
|
|
|
def test_validate_zone_preset_normalizes_an_integral_float_count_line():
|
|
"""F3: 1920.0 is an integer in disguise and is stored as 1920."""
|
|
out = validate_zone_preset({**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.0, "y": 330.0}})
|
|
assert out["count_line"] == {"x_start": 577, "x_end": 1920, "y": 330}
|
|
assert all(isinstance(v, int) for v in out["count_line"].values())
|
|
|
|
|
|
def test_validate_zone_preset_requires_four_truck_area_points():
|
|
"""F4: build_static_roi needs 4 points; 3 would silently degrade the job."""
|
|
bad = {**GOOD_PRESET, "truck_area": [[600, 385], [609, 1076], [1404, 1078]]}
|
|
with pytest.raises(ValueError, match="truck_area"):
|
|
validate_zone_preset(bad)
|
|
|
|
|
|
def test_save_zone_preset_persists_the_normalized_preset(tmp_path):
|
|
"""F3: the normalized count_line must reach the file."""
|
|
path = str(tmp_path / "zones.json")
|
|
cfg = {"presets": {"default": GOOD_PRESET}, "active_preset": "default"}
|
|
with open(path, "w") as f:
|
|
json.dump(cfg, f)
|
|
save_zone_preset(path, "default", {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.0, "y": 330.0}})
|
|
saved = json.load(open(path))
|
|
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1920, "y": 330}
|
|
# 1920.0 == 1920 in Python, so the type is the real assertion here
|
|
assert all(isinstance(v, int) for v in saved["presets"]["default"]["count_line"].values())
|
|
|
|
|
|
def test_save_zone_preset_with_replace_drops_stored_keys(tmp_path):
|
|
"""F8: replace=True swaps the stored preset wholesale."""
|
|
path = str(tmp_path / "zones.json")
|
|
cfg = {"presets": {"default": {**GOOD_PRESET, "duplicate_circle_radius": 30}},
|
|
"active_preset": "default"}
|
|
with open(path, "w") as f:
|
|
json.dump(cfg, f)
|
|
save_zone_preset(path, "default", GOOD_PRESET, replace=True)
|
|
saved = json.load(open(path))
|
|
assert "duplicate_circle_radius" not in saved["presets"]["default"]
|
|
assert saved["active_preset"] == "default"
|
|
|
|
|
|
def test_save_zone_preset_uses_a_unique_temp_file(tmp_path):
|
|
"""F5: concurrent posts must not share one temp path."""
|
|
import src.zone_config as zc
|
|
path = str(tmp_path / "zones.json")
|
|
cfg = {"presets": {}, "active_preset": "default"}
|
|
with open(path, "w") as f:
|
|
json.dump(cfg, f)
|
|
seen = []
|
|
real_mkstemp = zc.tempfile.mkstemp
|
|
def spy(*args, **kwargs):
|
|
fd, name = real_mkstemp(*args, **kwargs)
|
|
seen.append(name)
|
|
return fd, name
|
|
zc.tempfile.mkstemp = spy
|
|
try:
|
|
save_zone_preset(path, "default", GOOD_PRESET)
|
|
save_zone_preset(path, "other", GOOD_PRESET)
|
|
finally:
|
|
zc.tempfile.mkstemp = real_mkstemp
|
|
assert len(seen) == 2
|
|
assert seen[0] != seen[1]
|
|
assert all(os.path.dirname(p) == str(tmp_path) for p in seen)
|
|
|
|
|
|
# --- fix round 2: R1 reference_resolution injection, R2/R3 file handling, R4 mode, R5 lock ---
|
|
|
|
def test_validate_zone_preset_injects_the_analysis_space_when_the_key_is_absent():
|
|
"""R1: missing reference_resolution defaults to native [1920, 1080]."""
|
|
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
|
|
out = validate_zone_preset(preset)
|
|
assert out["reference_resolution"] == [1920, 1080]
|
|
|
|
|
|
def test_save_zone_preset_persists_the_injected_analysis_space(tmp_path):
|
|
"""R1: the injected key must reach the file so build_static_roi scales 1080p -> 720p."""
|
|
path = str(tmp_path / "zones.json")
|
|
cfg = {"presets": {}, "active_preset": "default"}
|
|
with open(path, "w") as f:
|
|
json.dump(cfg, f)
|
|
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
|
|
save_zone_preset(path, "fresh", preset)
|
|
saved = json.load(open(path))
|
|
assert saved["presets"]["fresh"]["reference_resolution"] == [1920, 1080]
|
|
roi = build_static_roi(saved["presets"]["fresh"], 1280, 720)
|
|
assert (roi.x1, roi.x2) == (400, 936)
|
|
|
|
|
|
def test_save_zone_preset_rejects_a_non_object_presets(tmp_path):
|
|
"""R2: {"presets": []} used to raise TypeError inside the save."""
|
|
path = str(tmp_path / "zones.json")
|
|
with open(path, "w") as f:
|
|
json.dump({"presets": []}, f)
|
|
with pytest.raises(ValueError, match="presets"):
|
|
save_zone_preset(path, "default", GOOD_PRESET)
|
|
|
|
|
|
def test_save_zone_preset_rejects_a_non_object_config(tmp_path):
|
|
"""R2: a JSON array as the whole config is not a zone config."""
|
|
path = str(tmp_path / "zones.json")
|
|
with open(path, "w") as f:
|
|
json.dump([1, 2, 3], f)
|
|
with pytest.raises(ValueError, match="object"):
|
|
save_zone_preset(path, "default", GOOD_PRESET)
|
|
|
|
|
|
def test_save_zone_preset_refuses_to_create_a_missing_file(tmp_path):
|
|
"""R3: the write path must never bring a zones.json into existence."""
|
|
path = str(tmp_path / "zones.json")
|
|
with pytest.raises(FileNotFoundError):
|
|
save_zone_preset(path, "default", GOOD_PRESET)
|
|
assert not os.path.exists(path)
|
|
|
|
|
|
def test_save_zone_preset_keeps_the_file_mode(tmp_path):
|
|
"""R4: mkstemp creates 0600; the file must not silently become owner-only."""
|
|
path = str(tmp_path / "zones.json")
|
|
with open(path, "w") as f:
|
|
json.dump({"presets": {}, "active_preset": "default"}, f)
|
|
os.chmod(path, 0o644)
|
|
save_zone_preset(path, "default", GOOD_PRESET)
|
|
assert os.stat(path).st_mode & 0o777 == 0o644
|
|
|
|
|
|
def test_save_zone_preset_serializes_concurrent_writes(tmp_path, monkeypatch):
|
|
"""R5: two concurrent saves must not lose one of the presets."""
|
|
import threading
|
|
import time
|
|
|
|
import src.zone_config as zc
|
|
path = str(tmp_path / "zones.json")
|
|
with open(path, "w") as f:
|
|
json.dump({"presets": {}, "active_preset": "default"}, f)
|
|
# Widen the read-modify-write window so an unsynchronized save loses an update.
|
|
real_load = zc.load_zone_config
|
|
first_read = threading.Event()
|
|
|
|
def slow_load(p):
|
|
cfg = real_load(p)
|
|
first_read.set()
|
|
time.sleep(0.05)
|
|
return cfg
|
|
|
|
monkeypatch.setattr(zc, "load_zone_config", slow_load)
|
|
errors = []
|
|
|
|
def worker(name):
|
|
try:
|
|
zc.save_zone_preset(path, name, GOOD_PRESET)
|
|
except Exception as exc: # noqa: BLE001 - reported below
|
|
errors.append(exc)
|
|
|
|
t1 = threading.Thread(target=worker, args=("one",))
|
|
t2 = threading.Thread(target=worker, args=("two",))
|
|
t1.start()
|
|
assert first_read.wait(5)
|
|
t2.start()
|
|
t1.join(5)
|
|
t2.join(5)
|
|
assert not errors
|
|
saved = json.load(open(path))
|
|
assert set(saved["presets"]) == {"one", "two"}
|
|
|
|
|
|
# ── 1080p normalizer and FCP zones.json auto-sync ────────────────────────
|
|
|
|
|
|
def test_normalize_zone_preset_converts_fcp_flat_1080p_schema():
|
|
"""FCP main's flat zones.json maps cleanly to [1920, 1080] recounter format."""
|
|
fcp_flat = {
|
|
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
|
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"line_y": 215,
|
|
"line_x_start": 577,
|
|
"line_x_end": 1401,
|
|
"left_limit": 0.27578,
|
|
"external_stream_url": "http://192.168.192.96:8888/cam/",
|
|
}
|
|
out = normalize_zone_preset(fcp_flat)
|
|
assert out["reference_resolution"] == [1920, 1080]
|
|
assert out["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
|
|
assert out["truck_area"] == [[600, 290], [609, 1076], [1404, 1078], [1381, 290]]
|
|
assert out["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
|
|
assert out["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
|
assert out["left_limit"] == 0.27578
|
|
for transient in ("palet_area", "truck", "counting", "line_y", "line_x_start", "line_x_end"):
|
|
assert transient not in out
|
|
roi = build_static_roi(out, 1280, 720)
|
|
assert (roi.line_x_start, roi.line_x_end, roi.line_y) == (385, 934, 143)
|
|
|
|
|
|
def test_normalize_zone_preset_scales_720p_preset_to_1080p():
|
|
"""Legacy 1280x720 presets are scaled up by 1.5x into [1920, 1080]."""
|
|
legacy_720p = {
|
|
"truck_area": [[400, 194], [406, 718], [936, 718], [920, 194]],
|
|
"counting_area": [[382, 34], [390, 718], [946, 718], [932, 34]],
|
|
"count_line": {"x_start": 384, "x_end": 934, "y": 144},
|
|
"reference_resolution": [1280, 720],
|
|
}
|
|
out = normalize_zone_preset(legacy_720p)
|
|
assert out["reference_resolution"] == [1920, 1080]
|
|
assert out["truck_area"] == [[600, 291], [609, 1077], [1404, 1077], [1380, 291]]
|
|
assert out["counting_area"] == [[573, 51], [585, 1077], [1419, 1077], [1398, 51]]
|
|
assert out["count_line"] == {"x_start": 576, "x_end": 1401, "y": 216}
|
|
|
|
|
|
def test_normalize_zone_preset_supports_two_point_counting_line():
|
|
"""FCP's 2-point counting_line and coord_space='1280x720' normalize to [1920, 1080]."""
|
|
flat_720 = {
|
|
"coord_space": "1280x720",
|
|
"truck": [[400, 200], [400, 720], [936, 720], [920, 200]],
|
|
"counting": [[380, 40], [380, 720], [940, 720], [940, 40]],
|
|
"counting_line": [[934, 200], [384, 180]],
|
|
}
|
|
out = normalize_zone_preset(flat_720)
|
|
assert out["reference_resolution"] == [1920, 1080]
|
|
assert out["count_line"] == {"x_start": 576, "x_end": 1401, "y": 285}
|
|
assert "coord_space" not in out
|
|
assert "counting_line" not in out
|
|
|
|
|
|
def test_save_zone_preset_accepts_fcp_flat_payload(tmp_path):
|
|
path = str(tmp_path / "zones.json")
|
|
with open(path, "w") as f:
|
|
json.dump({"presets": {"default": GOOD_PRESET}, "active_preset": "default"}, f)
|
|
fcp_flat = {
|
|
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
|
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"line_y": 215,
|
|
"line_x_start": 577,
|
|
"line_x_end": 1401,
|
|
}
|
|
save_zone_preset(path, "default", fcp_flat)
|
|
saved = json.load(open(path))["presets"]["default"]
|
|
assert saved["reference_resolution"] == [1920, 1080]
|
|
assert saved["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
|
assert "truck" not in saved
|
|
assert "line_y" not in saved
|
|
|
|
|
|
def test_sync_fcp_zones_updates_default_when_fcp_file_is_newer(tmp_path):
|
|
recounter_zones = tmp_path / "recounter_zones.json"
|
|
fcp_zones = tmp_path / "fcp_zones.json"
|
|
recounter_zones.write_text(json.dumps({
|
|
"presets": {"default": GOOD_PRESET, "other": GOOD_PRESET},
|
|
"active_preset": "default",
|
|
}))
|
|
fcp_zones.write_text(json.dumps({
|
|
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
|
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"line_y": 250,
|
|
"line_x_start": 590,
|
|
"line_x_end": 1410,
|
|
}))
|
|
# Ensure FCP file mtime is strictly newer than recounter zones.json.
|
|
st = recounter_zones.stat()
|
|
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
|
|
|
updated = sync_fcp_zones(str(recounter_zones), str(fcp_zones))
|
|
assert updated is True
|
|
saved = json.loads(recounter_zones.read_text())
|
|
assert saved["presets"]["default"]["count_line"] == {"x_start": 590, "x_end": 1410, "y": 250}
|
|
assert saved["presets"]["other"] == GOOD_PRESET
|
|
|
|
|
|
def test_sync_fcp_zones_skips_when_local_zones_file_is_newer(tmp_path):
|
|
recounter_zones = tmp_path / "recounter_zones.json"
|
|
fcp_zones = tmp_path / "fcp_zones.json"
|
|
fcp_zones.write_text(json.dumps({
|
|
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"line_y": 250,
|
|
"line_x_start": 590,
|
|
"line_x_end": 1410,
|
|
}))
|
|
recounter_zones.write_text(json.dumps({
|
|
"presets": {"default": GOOD_PRESET},
|
|
"active_preset": "default",
|
|
}))
|
|
st = fcp_zones.stat()
|
|
os.utime(recounter_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
|
|
|
updated = sync_fcp_zones(str(recounter_zones), str(fcp_zones))
|
|
assert updated is False
|
|
saved = json.loads(recounter_zones.read_text())
|
|
assert saved["presets"]["default"] == GOOD_PRESET
|
|
|
|
|
|
def test_resolve_zone_loads_fixed_zone_and_polygons(tmp_path):
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps({
|
|
"presets": {"default": GOOD_PRESET},
|
|
"active_preset": "default",
|
|
}))
|
|
mode, roi, preset, cpoly, tpoly = resolve_zone("fixed", "", str(zones), (1280, 720))
|
|
assert mode == "fixed"
|
|
assert preset == "default"
|
|
assert roi is not None and roi.line_y == 220
|
|
assert cpoly is not None and tpoly is not None
|