"""MTCNN two-pass recall behaviour.""" from PIL import Image import core.models as models _LANDMARKS = [20.0, 25.0, 15.0, 20.0, 25.0, 20.0, 20.0, 30.0, 30.0, 30.0] _BOX = [10.0, 10.0, 50.0, 50.0, 0.5] class FakeDetector: def __init__(self, passes): self.min_face_size = 20 self.thresholds = [0.6, 0.7, 0.7] self.nms_thresholds = [0.7, 0.7, 0.7] self.factor = 0.85 self._passes = list(passes) self.calls: list[dict] = [] def detect_faces(self, image, min_face_size, thresholds, nms_thresholds, factor): self.calls.append({ "min_face_size": min_face_size, "thresholds": list(thresholds), "nms_thresholds": list(nms_thresholds), "factor": factor, }) return self._passes.pop(0) def _image(): return Image.new("RGB", (64, 64), (128, 128, 128)) def test_detect_faces_retries_with_relaxed_settings(monkeypatch): detector = FakeDetector([ ([], []), ([_BOX], [_LANDMARKS]), ]) monkeypatch.setattr(models, "load_face_detector", lambda: detector) monkeypatch.setattr(models, "MTCNN_RETRY_MIN_FACE_SIZE", 12) monkeypatch.setattr(models, "MTCNN_RETRY_CONFIDENCE", 0.45) faces = models.detect_faces(_image(), confidence_threshold=0.6) assert len(faces) == 1 assert faces[0]["score"] == 0.5 assert len(detector.calls) == 2 assert detector.calls[1]["min_face_size"] == 12 assert detector.calls[1]["thresholds"] == [0.45, 0.45, 0.45] def test_detect_faces_does_not_retry_when_first_pass_matches(monkeypatch): detector = FakeDetector([ ([[10.0, 10.0, 50.0, 50.0, 0.9]], [_LANDMARKS]), ]) monkeypatch.setattr(models, "load_face_detector", lambda: detector) monkeypatch.setattr(models, "MTCNN_RETRY_MIN_FACE_SIZE", 12) monkeypatch.setattr(models, "MTCNN_RETRY_CONFIDENCE", 0.45) faces = models.detect_faces(_image(), confidence_threshold=0.6) assert len(faces) == 1 assert len(detector.calls) == 1 def test_detect_faces_returns_empty_after_two_failed_passes(monkeypatch): detector = FakeDetector([([], []), ([], [])]) monkeypatch.setattr(models, "load_face_detector", lambda: detector) monkeypatch.setattr(models, "MTCNN_RETRY_MIN_FACE_SIZE", 12) monkeypatch.setattr(models, "MTCNN_RETRY_CONFIDENCE", 0.45) assert models.detect_faces(_image(), confidence_threshold=0.6) == [] assert len(detector.calls) == 2 def test_detect_faces_skips_retry_when_not_more_permissive(monkeypatch): detector = FakeDetector([([], [])]) monkeypatch.setattr(models, "load_face_detector", lambda: detector) monkeypatch.setattr(models, "MTCNN_RETRY_MIN_FACE_SIZE", 20) monkeypatch.setattr(models, "MTCNN_RETRY_CONFIDENCE", 0.7) assert models.detect_faces(_image(), confidence_threshold=0.6) == [] assert len(detector.calls) == 1