initial commit

This commit is contained in:
2026-11-25 15:45:36 +05:30
commit e6007d7b07
50 changed files with 3818 additions and 0 deletions
View File
+36
View File
@@ -0,0 +1,36 @@
"""Shared helpers for tests."""
from __future__ import annotations
import cv2
import numpy as np
def synthetic_image(h: int = 480, w: int = 640) -> np.ndarray:
"""Deterministic RGB test image (not a claim about detections - used for contract checks)."""
rng = np.random.default_rng(0)
img = rng.integers(90, 160, size=(h, w, 3), dtype=np.uint8)
cv2.rectangle(img, (w // 4, h // 4), (w // 2, 3 * h // 4), (200, 40, 40), -1)
cv2.circle(img, (3 * w // 4, h // 2), h // 6, (40, 40, 200), -1)
return img
def assert_result_contract(result: dict, image: np.ndarray, model_name: str) -> None:
h, w = image.shape[:2]
assert result["model_name"] == model_name
assert result["image_width"] == w and result["image_height"] == h
n = result["num_detections"]
assert n == len(result["boxes"]) == len(result["labels"]) == len(result["scores"])
assert result["inference_time"] > 0
for (x1, y1, x2, y2), score in zip(result["boxes"], result["scores"]):
assert 0 <= x1 <= x2 <= w and 0 <= y1 <= y2 <= h
assert 0.0 <= score <= 1.0
def make_video(path, frames: int = 10, size=(320, 240), fps: int = 10) -> None:
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, size)
assert writer.isOpened(), "OpenCV could not open a video writer (mp4v)"
for i in range(frames):
frame = np.full((size[1], size[0], 3), 100, dtype=np.uint8)
cv2.rectangle(frame, (10 + 5 * i, 40), (90 + 5 * i, 140), (0, 180, 255), -1)
writer.write(frame)
writer.release()
+31
View File
@@ -0,0 +1,31 @@
"""Real Grounding DINO inference (downloads weights on first run)."""
import pytest
from models import ModelLoadError
from models.model_manager import ModelManager
from tests.helpers import assert_result_contract, synthetic_image
@pytest.fixture(scope="module")
def manager():
return ModelManager()
def test_grounding_dino_result_contract(manager):
try:
manager.get_detector("Grounding DINO", "auto")
except ModelLoadError as exc:
pytest.skip(f"Grounding DINO unavailable: {exc}")
image = synthetic_image()
result = manager.detect("Grounding DINO", image, ["person", "safety helmet", "red box"], conf=0.2)
assert_result_contract(result, image, "Grounding DINO")
def test_grounding_dino_prompt_change_does_not_crash(manager):
try:
manager.get_detector("Grounding DINO", "auto")
except ModelLoadError as exc:
pytest.skip(str(exc))
image = synthetic_image()
for prompts in (["laptop"], ["gas cylinder", "fire blanket"]):
assert_result_contract(manager.detect("Grounding DINO", image, prompts, conf=0.2), image, "Grounding DINO")
+23
View File
@@ -0,0 +1,23 @@
"""End-to-end image pipeline with a real model (YOLO-World, the faster one)."""
import pytest
from detection.image_detection import run_image_detection
from detection.visualization import draw_detections, result_to_dataframe, save_annotated_image
from models import ModelLoadError
from models.model_manager import ModelManager
from tests.helpers import assert_result_contract, synthetic_image
def test_image_pipeline_original_coordinates_and_saving(tmp_path):
manager = ModelManager()
try:
manager.get_detector("YOLO-World", "auto")
except ModelLoadError as exc:
pytest.skip(str(exc))
image = synthetic_image(900, 1400)
result = run_image_detection(manager, "YOLO-World", image, ["person", "laptop"], conf=0.05, max_side=640)
assert_result_contract(result, image, "YOLO-World") # boxes within the ORIGINAL 1400x900 frame
annotated = draw_detections(image, result)
assert annotated.shape == image.shape
assert len(result_to_dataframe(result)) == result["num_detections"]
assert save_annotated_image(annotated, tmp_path, "t").exists()
+62
View File
@@ -0,0 +1,62 @@
import math
import numpy as np
from benchmarking.metrics import average_precision, evaluate_detections, iou_xyxy, pair_boxes
def test_iou_known_values():
a = np.array([[0, 0, 10, 10]])
assert iou_xyxy(a, a)[0, 0] == 1.0
assert iou_xyxy(a, np.array([[20, 20, 30, 30]]))[0, 0] == 0.0
assert abs(iou_xyxy(a, np.array([[5, 0, 15, 10]]))[0, 0] - (50 / 150)) < 1e-9
def test_perfect_detection():
gt = {"i1": {"boxes": [[0, 0, 10, 10]], "labels": ["cat"]}}
pr = {"i1": {"boxes": [[0, 0, 10, 10]], "labels": ["cat"], "scores": [0.9]}}
o = evaluate_detections(pr, gt, ["cat"], 0.5, 0.25)["overall"]
assert (o["precision"], o["recall"], o["f1"]) == (1.0, 1.0, 1.0)
assert o["map50"] == 1.0 and o["map50_95"] == 1.0
def test_duplicate_prediction_matches_once():
gt = {"i1": {"boxes": [[0, 0, 10, 10]], "labels": ["cat"]}}
pr = {"i1": {"boxes": [[0, 0, 10, 10], [0, 0, 10, 10]], "labels": ["cat", "cat"], "scores": [0.9, 0.8]}}
o = evaluate_detections(pr, gt, ["cat"], 0.5, 0.25)["overall"]
assert (o["tp"], o["fp"], o["fn"]) == (1, 1, 0)
assert o["precision"] == 0.5 and o["recall"] == 1.0
def test_missed_object_and_wrong_class():
gt = {"i1": {"boxes": [[0, 0, 10, 10], [50, 50, 60, 60]], "labels": ["cat", "dog"]}}
pr = {"i1": {"boxes": [[0, 0, 10, 10], [50, 50, 60, 60]], "labels": ["cat", "cat"], "scores": [0.9, 0.9]}}
res = evaluate_detections(pr, gt, ["cat", "dog"], 0.5, 0.25)
rows = {r["category"]: r for r in res["per_class"]}
assert rows["cat"]["tp"] == 1 and rows["cat"]["fp"] == 1
assert rows["dog"]["fn"] == 1 and rows["dog"]["recall"] == 0.0
def test_confidence_threshold_filters_pr_but_not_ap():
gt = {"i1": {"boxes": [[0, 0, 10, 10]], "labels": ["cat"]}}
pr = {"i1": {"boxes": [[0, 0, 10, 10]], "labels": ["cat"], "scores": [0.1]}}
o = evaluate_detections(pr, gt, ["cat"], 0.5, 0.25)["overall"]
assert o["recall"] == 0.0 and o["map50"] == 1.0 # AP sees the low-score detection
def test_undefined_precision_is_nan_not_zero():
gt = {"i1": {"boxes": [[0, 0, 10, 10]], "labels": ["cat"]}}
o = evaluate_detections({}, gt, ["cat"], 0.5, 0.25)["overall"]
assert math.isnan(o["precision"]) and o["recall"] == 0.0 and o["map50"] == 0.0
def test_average_precision_ranking():
# TP, FP, TP with 2 GT -> precision envelope 1.0 up to recall .5, then 2/3
ap = average_precision([(0.9, True), (0.8, False), (0.7, True)], 2)
assert 0.8 < ap < 0.9
def test_pair_boxes_one_to_one():
a = np.array([[0, 0, 10, 10], [100, 100, 110, 110]])
b = np.array([[0, 0, 10, 10]])
assert pair_boxes(a, b, 0.5) == [1.0]
+43
View File
@@ -0,0 +1,43 @@
import numpy as np
import pandas as pd
from benchmarking.pdf_report import create_pdf_report
from benchmarking.report_generator import build_category_metric_tables
def test_create_pdf_report_renders_tables_and_images():
report = create_pdf_report(
"Detection report",
{"Model": "YOLO-World", "Detections": 1},
{"Results": pd.DataFrame([{"label": "person", "confidence": 0.9}] * 27)},
{"Annotated image": np.zeros((8, 8, 3), dtype=np.uint8)},
{"Detections by category": ("bar", pd.DataFrame({"Detections": [2, 1]}, index=["person", "helmet"]),
"Detections")},
)
assert report.startswith(b"%PDF")
assert len(report) > 1000
def test_category_metric_tables_include_model_values_and_uncommon_f1():
per_category = pd.DataFrame([
{"model": "Grounding DINO", "category": "person", "precision": 0.8, "recall": 0.6, "f1": 0.685},
{"model": "YOLO-World", "category": "person", "precision": 0.9, "recall": 0.5, "f1": 0.643},
{"model": "Grounding DINO", "category": "ambulance", "precision": float("nan"), "recall": 0.0, "f1": 0.0},
{"model": "YOLO-World", "category": "ambulance", "precision": 0.5, "recall": 1.0, "f1": 0.667},
])
tables = build_category_metric_tables(per_category, ["Ambulance"])
assert tables["Per-category precision and recall"].iloc[0].to_dict() == {
"Category": "Person",
"Grounding DINO precision": "0.800",
"Grounding DINO recall": "0.600",
"YOLO-World precision": "0.900",
"YOLO-World recall": "0.500",
}
assert tables["Uncommon category F1"].iloc[0].to_dict() == {
"Category": "Ambulance",
"Grounding DINO F1": "0.000",
"YOLO-World F1": "0.667",
}
+43
View File
@@ -0,0 +1,43 @@
"""Pipeline logic tests with a STUB manager (no model weights needed).
These verify box rescaling, frame skipping, FPS definitions and video writing only.
Real inference is covered by the model tests.
"""
import numpy as np
from detection.image_detection import run_image_detection
from detection.video_detection import process_video
from models import build_result
from tests.helpers import make_video, synthetic_image
class StubManager:
"""Returns one fixed box (in the coordinates of the image it receives)."""
def __init__(self):
self.calls = 0
def detect(self, model_name, image, prompts, device="auto", conf=None, text_threshold=None, imgsz=None):
self.calls += 1
h, w = image.shape[:2]
return build_result(model_name, [[w * 0.25, h * 0.25, w * 0.75, h * 0.75]], [prompts[0]], [0.9], 0.01, (h, w))
def test_boxes_mapped_back_to_original_coordinates():
image = synthetic_image(1200, 1600)
res = run_image_detection(StubManager(), "YOLO-World", image, ["thing"], max_side=800)
assert (res["image_width"], res["image_height"]) == (1600, 1200)
x1, y1, x2, y2 = res["boxes"][0]
assert abs(x1 - 400) < 2 and abs(x2 - 1200) < 2 and abs(y1 - 300) < 2 and abs(y2 - 900) < 2
def test_video_frame_skip_and_fps_definitions(tmp_path):
src, out = tmp_path / "in.mp4", tmp_path / "out.mp4"
make_video(src, frames=10, fps=10)
stats = process_video(StubManager(), "YOLO-World", src, out, ["thing"], frame_skip=2, warmup=False)
assert stats["processed_frames"] == 5 and stats["frame_skip_enabled"]
assert out.exists() and out.stat().st_size > 0
assert abs(stats["avg_inference_ms"] - 10.0) < 1e-6 # stub reports 0.01 s per frame
assert abs(stats["inference_fps"] - 100.0) < 1e-6 # 5 frames / 0.05 s of model time
assert stats["input_fps"] == 10.0 and stats["inference_fps"] != stats["input_fps"]
assert stats["end_to_end_fps"] > 0 and "Frame skipping enabled" in stats["note"]
+33
View File
@@ -0,0 +1,33 @@
import pytest
from detection.prompt_manager import (PromptError, match_label_to_prompt, parse_prompts,
prepare_for_grounding_dino, prepare_for_yolo_world)
def test_parse_commas_newlines_duplicates_whitespace():
raw = "person, Safety helmet\nperson\n\n safety helmet ,fire extinguisher;"
assert parse_prompts(raw) == ["person", "Safety helmet", "fire extinguisher"]
def test_parse_list_input():
assert parse_prompts(["a", " b ", "A", ""]) == ["a", "b"]
def test_grounding_dino_format():
assert prepare_for_grounding_dino(["Person", "Safety Helmet"]) == "person . safety helmet ."
def test_yolo_world_format():
assert prepare_for_yolo_world("person, laptop") == ["person", "laptop"]
def test_empty_prompts_raise():
with pytest.raises(PromptError):
prepare_for_grounding_dino([" ", ""])
def test_match_label_to_prompt():
prompts = ["safety helmet", "safety vest", "person"]
assert match_label_to_prompt("Person", prompts) == "person"
assert match_label_to_prompt("safety vest .", prompts) == "safety vest"
assert match_label_to_prompt("unknown thing", prompts) == "unknown thing"
+22
View File
@@ -0,0 +1,22 @@
"""End-to-end video pipeline with a real model."""
import pytest
from detection.video_detection import process_video
from models import ModelLoadError
from models.model_manager import ModelManager
from tests.helpers import make_video
def test_video_pipeline_real_model(tmp_path):
manager = ModelManager()
try:
manager.get_detector("YOLO-World", "auto")
except ModelLoadError as exc:
pytest.skip(str(exc))
src, out = tmp_path / "in.mp4", tmp_path / "out.mp4"
make_video(src, frames=8, fps=8)
stats = process_video(manager, "YOLO-World", src, out, ["person", "laptop"], conf=0.05, frame_skip=2)
assert stats["processed_frames"] == 4
assert out.exists() and out.stat().st_size > 0
assert stats["inference_fps"] > 0 and stats["end_to_end_fps"] > 0
assert stats["end_to_end_fps"] <= stats["inference_fps"] + 1e-6 # e2e includes extra work
+35
View File
@@ -0,0 +1,35 @@
"""Real YOLO-World inference (downloads weights on first run)."""
import pytest
from models import ModelLoadError
from models.model_manager import ModelManager
from tests.helpers import assert_result_contract, synthetic_image
@pytest.fixture(scope="module")
def manager():
return ModelManager()
def test_yolo_world_result_contract_and_custom_classes(manager):
try:
detector = manager.get_detector("YOLO-World", "auto")
except ModelLoadError as exc:
pytest.skip(f"YOLO-World unavailable: {exc}")
image = synthetic_image()
result = manager.detect("YOLO-World", image, ["person", "safety helmet"], conf=0.05)
assert_result_contract(result, image, "YOLO-World")
assert detector.current_classes == ("person", "safety helmet")
assert set(result["labels"]) <= {"person", "safety helmet"}
def test_yolo_world_vocabulary_can_change(manager):
try:
detector = manager.get_detector("YOLO-World", "auto")
except ModelLoadError as exc:
pytest.skip(str(exc))
image = synthetic_image()
manager.detect("YOLO-World", image, ["laptop"], conf=0.05)
assert detector.current_classes == ("laptop",)
manager.detect("YOLO-World", image, ["gas cylinder", "ear protection"], conf=0.05)
assert detector.current_classes == ("gas cylinder", "ear protection")