commit e6007d7b0768b482274ca54deba89d6440c0ddf8 Author: harshada Date: Wed Nov 25 15:45:36 2026 +0530 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..82d447e --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# Environments +venv/ +.venv/ +env/ +.env +.env.* +# Python +__pycache__/ +*.py[cod] +.pytest_cache/ +.ipynb_checkpoints/ +# Model weights +*.pt +*.pth +*.onnx +*.engine +*.safetensors +weights/*/* +!weights/*/.gitkeep +# Data and outputs +dataset/images/* +dataset/videos/* +!dataset/images/.gitkeep +!dataset/videos/.gitkeep +dataset/annotations/annotations.json +dataset/prompts/saved_prompts.json +outputs/images/* +outputs/videos/* +outputs/reports/* +!outputs/images/.gitkeep +!outputs/videos/.gitkeep +!outputs/reports/.gitkeep +# Logs / temp +logs/ +*.log +*.tmp +*.tmp.mp4 +.streamlit/secrets.toml +# OS / IDE +.DS_Store +Thumbs.db +.vscode/ +.idea/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8ff8c9a --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Project authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a4b885c --- /dev/null +++ b/README.md @@ -0,0 +1,262 @@ +# Open-Vocabulary Object Detection + +Find objects in images and videos by **typing their names** (for example `safety helmet` or `stretcher`). +No training is needed. The project compares two ready-made (pretrained) models, **Grounding DINO** and **YOLO-World**, +in a simple web dashboard that runs on your NVIDIA GPU. + +What you can do in the dashboard: + +- Detect objects in an **image** or a **video** +- Run **both models on the same image** and compare them +- **Download a report** (PDF or HTML) for every test +- Run a **benchmark** (precision, recall, speed) if you have a labelled dataset + +## Project folder structure + +```text +open_vocabulary_detection/ + app.py Streamlit dashboard + run_app.bat Windows launcher using the project environment + config/ App and model configuration + models/ Grounding DINO, YOLO-World, and model manager + detection/ Image/video pipelines, prompt manager, visualization + benchmarking/ Evaluation, metrics, monitoring, and reports + dataset/ + images/ Evaluation images + videos/ Video inputs + annotations/ COCO annotations and format example + prompts/ Built-in and saved prompt sets + outputs/ Generated images, videos, and reports + weights/ Downloaded model weights and caches + utils/ Configuration, device, image, and video helpers + tests/ Unit and model tests + requirements.txt Python dependencies + README.md Project guide + LICENSE +``` + +--- + +## 1. The two models + +| | Grounding DINO | YOLO-World | +|---|---|---| +| Model used | `IDEA-Research/grounding-dino-tiny` | `yolov8s-worldv2.pt` | +| Library | Hugging Face Transformers | Ultralytics | +| How you give object names | One text line: `person . safety helmet .` | A list: `["person", "safety helmet"]` | +| Speed | Slower | Faster (good for video) | +| Good at | Longer phrases, unusual objects | Speed and real-time style use | +| Download size | about 0.7 GB | about 25 MB + CLIP text model about 340 MB | + +**In one sentence:** Grounding DINO reads your text together with the image every time (more flexible, slower), while +YOLO-World converts your names once and then runs like a normal fast YOLO detector. + +--- + +## 2. What you need + +- Windows 10/11 with an **NVIDIA GPU** and an up-to-date driver (the command `nvidia-smi` must work) +- **Python 3.11** (3.10 or 3.12 also work). Do **not** use Python 3.13 or 3.14. +- **Git** (needed once to install a small package called CLIP) +- About 4 GB free disk space +- Optional: **ffmpeg** (lets annotated videos play in the browser) + +--- + +## 3. Installation + +### Easiest way (two double-clicks) + +1. Double-click `setup.bat` (one time only, takes 10-20 minutes) +2. Double-click `run.bat` to start the app + +### Step by step (PowerShell) + +Open PowerShell inside the project folder and run these lines one by one: + +```powershell +# 1) Create a fresh virtual environment with Python 3.11 +py -3.11 -m venv .venv + +# 2) Activate it (your prompt should now start with (.venv)) +./.venv/Scripts/Activate.ps1 + +# 3) Install everything (this also installs the GPU version of PyTorch) +python -m pip install --upgrade pip +pip install -r requirements.txt + +# 4) Check that all is fine and the GPU is found +python check_env.py +``` + +If PowerShell refuses to activate, run this once and try step 2 again: + +```powershell +Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass +``` + +`python check_env.py` should end with **"everything looks good"** and show your GPU name. + +--- + +## 4. Run the app + +Every time you want to use the project: + +```powershell +cd D:/open_vocabulary_detection +./.venv/Scripts/Activate.ps1 +streamlit run app.py +``` + +Then open **http://localhost:8501** in your browser. +(Or just double-click `run.bat`.) + +--- + +## 5. How to use the dashboard + +1. **Image tab** - upload an image, type the objects to find (one per line), press **Run detection**. +2. **Video tab** - upload a video, type the objects, press **Process video**. +3. **Compare models tab** - upload one image, press **Run both models** to see both results side by side. +4. Under any result press **Generate report** and download the **PDF** or **HTML** report. It contains the original image, + the image with boxes, confidence scores, timing and all settings used. +5. Settings (model, GPU, thresholds, image size) are in the **Control Center** at the top of the page. + +The green **"CUDA ready"** label at the top confirms that the GPU is being used. +The app **stops with an error** if no GPU is found. This is on purpose, because the GPU is required. + +## What is a prompt, and how is it used? + +A **prompt** is the object name or category you ask the detector to find, such as `safety helmet` or `stretcher`. +It tells the model what to look for; it does not train the model or provide the correct answers for evaluation. + +- Enter one or more object names in the image, video, or model-comparison workflow. The app removes blank entries + and duplicates. +- Built-in test sets are stored in `dataset/prompts/test_prompts.json`; the prompt manager also supports saving + custom sets in `dataset/prompts/saved_prompts.json`. +- Grounding DINO receives the names as a lower-case, period-separated text string. YOLO-World receives them as a + list of class names. +- Dataset benchmarks use the categories in the COCO annotation file as prompts. The annotations provide the + ground-truth boxes needed to calculate precision, recall, and mAP. + +Command line (optional): + +```powershell +python -m detection.image_detection --image photo.jpg --model "Grounding DINO" --prompts "person, safety helmet" +python -m detection.video_detection --video clip.mp4 --model "YOLO-World" --prompts "person, safety vest" +``` + +--- + +## 6. The 15 test categories + +Person, Safety Helmet, Safety Vest, Fire Extinguisher, Mobile Phone, Laptop, Traffic Cone, Toolbox, Welding Machine, +Industrial Safety Equipment, Vending Machine, Ambulance, Telescope, Stretcher, Suitcase + +--- + +## 7. Measuring accuracy (needs a labelled dataset in COCO format) + +Precision, recall and mAP can only be measured if every test image has correct boxes drawn by a person (called +*ground truth*). The app never shows accuracy numbers without it. Helper tools are included: + +```powershell +# put your images in dataset/images, then: +python tools/make_coco_skeleton.py --images-dir dataset/images --output dataset/annotations/annotations.json + +# draw the boxes in CVAT, Label Studio or Roboflow, export as "COCO 1.0" and replace annotations.json +# (if the tool exports YOLO text files, convert them with tools/yolo_to_coco.py) + +# check the file before using it +python tools/validate_coco.py --annotations dataset/annotations/annotations.json --images-dir dataset/images --draw outputs/annotation_check + +# run the benchmark for both models +python -m benchmarking.compare_models +``` + +Results (tables and charts) are saved in `outputs/reports/`. + +--- + +## 8. Challenges we faced + +### 8.1 Creating the benchmark dataset (COCO format) +- No ready dataset exists for these 15 categories, so we must **collect images and draw every box by hand**. +- COCO is strict: boxes are `[x, y, width, height]`, category names must match the prompts exactly. One small mistake + (box outside the image, missing image file, renamed category) silently spoils the results. +- **Industrial Safety Equipment** overlaps with helmet and vest. A fixed rule is needed for what belongs to it. +- Some categories (ambulance, stretcher, vending machine) are harder to photograph, and photos of people need care + for privacy and image licences. +- If a model is used to pre-draw boxes, the benchmark becomes biased towards that model. Check every box by hand. +- Few images per category means noisy numbers. Aim for about 30 or more images per category. +- *How we help:* the three `tools/` scripts create, convert and validate the COCO file. + +### 8.2 Setting up the computer +- **Two Pythons installed (3.11 and 3.14):** Streamlit started from the wrong one and failed with `No module named 'cv2'`. + Fix: always use the project `.venv` made with `py -3.11`. +- **GPU not used:** the normal Windows PyTorch from PyPI is CPU-only. Fix: `requirements.txt` installs the CUDA build. +- **Version conflicts:** some package versions do not work together (OpenCV, NumPy, huggingface-hub, Transformers, Streamlit). + Fix: exact versions are pinned in `requirements.txt`. +- **PowerShell:** multi-line `python -c` commands fail. Use `python check_env.py` instead. + +### 8.3 Grounding DINO +- **Slower and heavier** than YOLO-World, even on a GPU, so it is less suited to video. +- **Labels can come back partial or merged**, for example two neighbouring prompts joined in one label. + The project maps each label back to the closest prompt. +- **Results depend on wording.** `welding machine` and `arc welder` can give different results. +- **Two thresholds** (box and text) must be tuned, and they do not mean the same as YOLO-World's confidence. +- **Library changes:** the threshold argument was renamed between Transformers versions. The code checks which name exists. +- Large first download (about 0.7 GB). + +### 8.4 YOLO-World +- **Names must be loaded with `set_classes()`** every time the prompt list changes. The app does this and checks it worked. +- **Needs the CLIP package and Git.** Ultralytics tries to install it automatically, which needs Git and a restart. + Fix: CLIP is installed from `requirements.txt`. +- **Extra download:** the CLIP text model (about 340 MB) is fetched on first use. +- **Unusual or ambiguous names are easier to miss**, and it can only return names from the list you give. +- Detection quality depends on the confidence setting: too high misses objects, too low adds false ones. + +### 8.5 Comparing the two fairly +- The first run is slower (model start-up), so one warm-up run is done and not timed. +- Each model is benchmarked in a **separate process** so memory numbers are not mixed. +- **Confidence is not accuracy.** A model can be sure and wrong. Only ground truth measures accuracy. +- Testing on one image is only an example. Use the dataset benchmark for real conclusions. +- Reported GPU memory is what PyTorch allocated, not everything the driver reserved. + +### 8.6 Video +- Browsers cannot play the default OpenCV video format. Install **ffmpeg** to convert it automatically, or download the file. +- Skipping frames makes processing faster but can miss objects. + +--- + +## 9. Quick fixes + +| Problem | What to do | +|---|---| +| "GPU (CUDA) is required" message | `pip uninstall -y torch torchvision`, then `pip install -r requirements.txt`, then `python check_env.py` | +| `No module named 'cv2'` | You are not inside `.venv`. Activate it and run `python check_env.py` | +| Error about `clip` or Git | Install Git for Windows, then run `pip install -r requirements.txt` again | +| First run is very slow | Normal: models are downloading (one time only) | +| Out of GPU memory | Lower "Max long side" or the YOLO size in the Control Center | +| No PDF in the report | `pip install reportlab` (the HTML report always works) | +| Code changes not showing | Stop Streamlit (Ctrl+C) and start it again | + +--- + +## 10. Reference links + +- Grounding DINO paper: https://arxiv.org/abs/2303.05499 +- Grounding DINO model page: https://huggingface.co/IDEA-Research/grounding-dino-tiny +- Transformers documentation: https://huggingface.co/docs/transformers/model_doc/grounding-dino +- YOLO-World paper: https://arxiv.org/abs/2401.17270 +- YOLO-World in Ultralytics: https://docs.ultralytics.com/models/yolo-world/ +- COCO annotation format: https://cocodataset.org/#format-data +- Labelling tools: https://www.cvat.ai/ , https://labelstud.io/ , https://roboflow.com/ +- Install PyTorch with CUDA: https://pytorch.org/get-started/locally/ +- Streamlit documentation: https://docs.streamlit.io/ + +## Licence note + +The project code is MIT. Ultralytics (YOLO-World) is AGPL-3.0, and the model weights have their own licences. +Check them before any commercial use. \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 0000000..e957611 --- /dev/null +++ b/app.py @@ -0,0 +1,978 @@ +"""Open-Vocabulary Object Detection - Streamlit dashboard. + +Run: streamlit run app.py +""" +from __future__ import annotations + +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +import cv2 +import numpy as np +import pandas as pd +import streamlit as st + +from benchmarking.metrics import pair_boxes +from benchmarking.performance_monitor import PerformanceMonitor +from benchmarking.pdf_report import create_pdf_report +from benchmarking.report_generator import ( + NOT_EVALUATED, + build_category_metric_tables, + generate_report, + load_summaries, + reports_dir, +) +from detection.image_detection import run_image_detection +from detection.prompt_manager import ( + PromptError, + get_all_presets, + load_test_prompts, + parse_prompts, + save_prompt_preset, +) +from detection.video_detection import process_video +from detection.visualization import draw_detections, result_to_dataframe, save_annotated_image +from models import DetectionError, ModelLoadError +from models.model_manager import MODEL_NAMES, ModelManager +from utils.config_loader import PROJECT_ROOT, ensure_project_dirs, load_config, resolve_path +from utils.device import device_info, resolve_device +from utils.image_utils import ImageLoadError, load_image_rgb, validate_extension +from utils.logger import get_logger +from utils.video_utils import VideoError, get_video_info + +logger = get_logger("app") +CFG = load_config() +ensure_project_dirs() +KNOWN_ERRORS = (ImageLoadError, VideoError, PromptError, ModelLoadError, DetectionError, ValueError, FileNotFoundError) +DEFAULT_PROMPTS = ( + "person\nsafety helmet\nsafety vest\nfire extinguisher\nmobile phone\n" + "laptop\ntraffic cone\ntoolbox\nwelding machine\nindustrial safety equipment\n" + "Vending Machine\nAmbulance\nTelescope\nStretcher\nSuitcase" +) + +st.set_page_config(page_title=CFG["app"]["name"], page_icon="๐ŸŽฏ", layout="wide") + +st.markdown( + """ + +
+
+
AI VISION WORKSPACE
+

Open-Vocabulary
Object Detection

+

Explore images and video with flexible, natural-language prompts. Compare two powerful zero-shot models without training or fine-tuning.

+
Grounding DINOYOLO-WorldCustom promptsImage ยท Video ยท Benchmarks
+
+
+ """, + unsafe_allow_html=True, +) + + +@st.cache_resource(show_spinner=False) +def get_manager() -> ModelManager: + """One manager for the whole server: model weights stay in memory across reruns/sessions.""" + return ModelManager() + + +manager = get_manager() + + +# ------------------------------------------------------------------ helpers +def show_error(exc: Exception) -> None: + if isinstance(exc, KNOWN_ERRORS): + st.error(str(exc)) + else: + logger.exception("Unexpected error") + st.error(f"Unexpected error: {exc}") + + +def png_bytes(image_rgb: np.ndarray) -> bytes: + ok, buf = cv2.imencode(".png", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)) + return buf.tobytes() if ok else b"" + + +def _load_preset(key: str) -> None: + choice = st.session_state.get(f"{key}_preset") + presets = get_all_presets() + if choice in presets: + st.session_state[f"{key}_text"] = "\n".join(presets[choice]) + + +def prompt_input(key: str) -> list[str]: + """Prompt editor with presets. Edits take effect immediately (no restart needed).""" + st.session_state.setdefault(f"{key}_text", DEFAULT_PROMPTS) + presets = get_all_presets() + st.selectbox("Load a prompt set", ["(keep current text)"] + list(presets), key=f"{key}_preset", + on_change=_load_preset, args=(key,)) + st.text_area("Object categories (one per line or comma-separated)", key=f"{key}_text", height=150, + help="Examples: person, safety helmet, fire extinguisher, Vending Machine") + prompts = parse_prompts(st.session_state[f"{key}_text"]) + c1, c2 = st.columns([3, 1]) + name = c1.text_input("Save as prompt set", key=f"{key}_save_name", placeholder="e.g. workshop PPE", + label_visibility="collapsed") + if c2.button("Save set", key=f"{key}_save_btn", use_container_width=True): + try: + save_prompt_preset(name, prompts) + st.success(f"Saved '{name}'.") + except PromptError as exc: + st.warning(str(exc)) + st.caption(f"{len(prompts)} categories after cleaning (duplicates and blanks removed).") + return prompts + + +def record_run(kind: str, filename: str, result: dict) -> None: + """Keep lightweight inference metadata for the current Streamlit session.""" + history = st.session_state.setdefault("run_history", []) + history.insert(0, { + "time": time.strftime("%H:%M:%S"), + "type": kind, + "file": filename, + "model": result["model_name"], + "detections": result["num_detections"], + "inference_ms": round(result["inference_time"] * 1000, 1), + "device": str(result.get("device", "-")).upper(), + }) + del history[100:] + + +def run_with_performance(callback, device: str) -> tuple[dict, dict]: + """Run one inference while sampling its latency and system resource usage.""" + monitor = PerformanceMonitor(device, interval=float(CFG["benchmark"]["monitor_interval_s"])) + monitor.start() + started = time.perf_counter() + try: + result = callback() + monitor.record_inference(result["inference_time"]) + monitor.record_item(time.perf_counter() - started) + finally: + monitor.stop() + return result, monitor.summary() + + +def _performance_number(performance: dict, key: str) -> float | None: + value = performance.get(key) + if value is None or not np.isfinite(value): + return None + return float(value) + + +def _format_performance(performance: dict, key: str, unit: str, multiplier: float = 1.0) -> str: + value = _performance_number(performance, key) + return "N/A" if value is None else f"{value * multiplier:.1f}{unit}" + + +def show_runtime_benchmark(performance: dict, time_label: str = "Detection pipeline time") -> None: + st.markdown("**Runtime benchmark**") + metrics = st.columns(5) + metrics[0].metric(time_label, _format_performance(performance, "e2e_total_s", " ms", 1000)) + metrics[1].metric("Peak GPU memory", _format_performance(performance, "gpu_peak_allocated_mb", " MB")) + metrics[2].metric("Peak GPU utilization", _format_performance(performance, "gpu_util_max_pct", "%")) + metrics[3].metric("Peak process RAM", _format_performance(performance, "ram_peak_mb", " MB")) + metrics[4].metric("Peak CPU utilization", _format_performance(performance, "cpu_peak_pct", "%")) + st.caption("Runtime measurements do not measure accuracy. Precision, recall, and mAP require annotated ground truth.") + + +# ------------------------------------------------------------------ sidebar +with st.sidebar: + st.header("Open-Vocabulary Object Detection") + model = st.selectbox("Model", MODEL_NAMES) + device_choice = st.selectbox("Device", ["auto", "cuda", "cpu"], index=["auto", "cuda", "cpu"].index(CFG["device"]["default"])) + resolved = resolve_device(device_choice) + info = device_info() + st.caption(f"Running on **{resolved.upper()}**" + (f" - {info.get('gpu_name')}" if resolved == "cuda" else "")) + if device_choice != "cpu" and not info["cuda_available"]: + st.warning( + f"PyTorch ({info['torch']}) cannot access CUDA, so inference is running on CPU. " + "Install a CUDA-enabled PyTorch build in this environment and restart the app to use the GPU." + ) + + st.subheader("Thresholds") + is_dino = model == "Grounding DINO" + conf = st.slider("Detection threshold" + (" (box)" if is_dino else " (confidence)"), 0.01, 0.95, + float(manager.default_conf(model)), 0.01, key=f"conf_{model}") + text_thr = st.slider("Text threshold (Grounding DINO)", 0.01, 0.95, float(CFG["detection"]["dino_text_threshold"]), + 0.01, disabled=not is_dino) + + st.subheader("Resolution") + max_side = st.select_slider("Image: max long side before inference (0 = original)", + options=[0, 320, 480, 640, 800, 1024, 1280, 1600, 1920, 2560], + value=CFG["image"]["inference_max_side"]) + imgsz = st.select_slider("YOLO-World inference size", options=[320, 480, 640, 800, 1024, 1280], + value=CFG["image"]["yolo_imgsz"], disabled=is_dino) + + st.subheader("Video") + frame_skip = st.number_input("Frame skip (1 = every frame)", 1, 60, int(CFG["video"]["frame_skip"])) + video_side = st.select_slider("Video: resize long side (0 = original)", + options=[0, 320, 480, 640, 800, 1024, 1280, 1920], + value=CFG["video"]["resize_long_side"]) + max_frames = st.number_input("Max frames to process (0 = all)", 0, 100000, int(CFG["video"]["max_frames"])) + st.caption("First use of a model downloads its weights and runs a warm-up pass.") + +tab_home, tab_img, tab_vid, tab_cmp, tab_bench, tab_info = st.tabs( + ["๐Ÿ  Overview", "๐Ÿ–ผ๏ธ Image Detection", "๐ŸŽฌ Video Detection", "โš–๏ธ Model Comparison", + "๐Ÿ“Š Benchmark Dashboard", "โ„น๏ธ Project Information"]) + + +# ------------------------------------------------------------------ overview tab +with tab_home: + st.subheader("Workspace overview") + st.caption("A quick view of your inference activity in this browser session.") + history = st.session_state.get("run_history", []) + if history: + history_df = pd.DataFrame(history) + total_detections = int(history_df["detections"].sum()) + average_ms = float(history_df["inference_ms"].mean()) + model_count = int(history_df["model"].nunique()) + summary = st.columns(4) + summary[0].metric("Inference runs", len(history_df)) + summary[1].metric("Detections", total_detections) + summary[2].metric("Avg recorded inference", f"{average_ms:.1f} ms") + summary[3].metric("Models used", model_count) + + model_activity, type_activity = st.columns(2) + with model_activity: + st.markdown("**Runs by model**") + st.bar_chart(history_df["model"].value_counts().rename("Runs")) + with type_activity: + st.markdown("**Runs by workflow**") + st.bar_chart(history_df["type"].value_counts().rename("Runs")) + + st.markdown("**Recent activity**") + st.dataframe(history_df, hide_index=True, use_container_width=True) + h1, h2 = st.columns([1, 5]) + h1.download_button("Export run history", history_df.to_csv(index=False).encode("utf-8"), + file_name="detection_run_history.csv", mime="text/csv") + if h2.button("Clear session history", key="clear_run_history"): + st.session_state["run_history"] = [] + st.rerun() + else: + st.info("No inference runs yet. Start with an image, process a video, or compare both models.") + + st.markdown("**Quick start**") + q1, q2, q3 = st.columns(3) + q1.markdown( + '
STEP 01' + "

Choose a model

Select Grounding DINO or YOLO-World and tune thresholds in the sidebar.

", + unsafe_allow_html=True, + ) + q2.markdown( + '
STEP 02' + "

Describe objects

Enter categories in natural language or load a reusable prompt set.

", + unsafe_allow_html=True, + ) + q3.markdown( + '
STEP 03' + "

Explore results

Inspect detections, compare models, or review benchmark performance.

", + unsafe_allow_html=True, + ) + + +# ------------------------------------------------------------------ image tab +with tab_img: + left, right = st.columns(2) + with left: + uploaded = st.file_uploader("Upload an image", type=[e.strip(".") for e in CFG["image"]["allowed_extensions"]], + key="img_upload") + with right: + img_prompts = prompt_input("img") + + if st.button("Detect", type="primary", disabled=uploaded is None or not img_prompts, key="img_run"): + try: + validate_extension(uploaded.name, CFG["image"]["allowed_extensions"]) + image = load_image_rgb(uploaded) + with st.spinner(f"Running {model}..."): + manager.get_detector(model, resolved) + result, performance = run_with_performance( + lambda: run_image_detection(manager, model, image, img_prompts, device=resolved, conf=conf, + text_threshold=text_thr, max_side=max_side, imgsz=imgsz), + resolved, + ) + annotated = draw_detections(image, result) + saved = save_annotated_image(annotated, stem=Path(uploaded.name).stem) + st.session_state["img_out"] = {"name": uploaded.name, "original": image, "annotated": annotated, + "result": result, "performance": performance, "saved": str(saved), + "settings": {"prompts": img_prompts, "confidence_threshold": conf, + "text_threshold": text_thr, "max_side": max_side, + "imgsz": imgsz}} + record_run("Image", uploaded.name, result) + except Exception as exc: # noqa: BLE001 + show_error(exc) + + out = st.session_state.get("img_out") + if out: + res = out["result"] + st.markdown(f"**Result for `{out['name']}`** - {res['model_name']}") + m = st.columns(5) + m[0].metric("Detections", res["num_detections"]) + m[1].metric("Inference time", f"{res['inference_time'] * 1000:.1f} ms") + m[2].metric("Avg confidence", f"{np.mean(res['scores']) * 100:.1f}%" if res["scores"] else "-") + m[3].metric("Image size", f"{res['image_width']}x{res['image_height']}") + m[4].metric("Device", str(res.get("device", "-")).upper()) + if "performance" in out: + show_runtime_benchmark(out["performance"]) + c1, c2 = st.columns(2) + c1.image(out["original"], caption="Original", use_container_width=True) + c2.image(out["annotated"], caption="Annotated", use_container_width=True) + if res["num_detections"] == 0: + st.info("No objects found. Try lowering the threshold or rephrasing the categories.") + else: + df = result_to_dataframe(res) + min_display_conf = st.slider("Minimum confidence shown in insights", 0, 100, 0, 1, + format="%d%%", key="img_min_display_conf") + visible_df = df[df["confidence_%"] >= min_display_conf] + st.caption(f"Showing {len(visible_df)} of {len(df)} detections in the insights below. " + "The annotated image includes all detections from inference.") + if visible_df.empty: + st.info("No detections meet this display filter. Lower the slider to see more results.") + else: + insights_left, insights_right = st.columns(2) + with insights_left: + st.markdown("**Detections by category**") + st.bar_chart(visible_df["label"].value_counts().rename("Detections")) + with insights_right: + st.markdown("**Mean confidence by category**") + confidence_by_label = visible_df.groupby("label")["confidence_%"].mean().sort_values( + ascending=False).rename("Mean confidence (%)") + st.bar_chart(confidence_by_label) + st.dataframe(visible_df, use_container_width=True, hide_index=True) + st.download_button("Download detection data (CSV)", visible_df.to_csv(index=False).encode("utf-8"), + file_name=f"{Path(out['name']).stem}_detections.csv", mime="text/csv") + st.download_button("Download annotated image (PNG)", png_bytes(out["annotated"]), + file_name=Path(out["saved"]).name, mime="image/png") + report_details = { + "Image": out["name"], + "Model": res["model_name"], + "Device": res.get("device", "-"), + "Image size": f"{res['image_width']}x{res['image_height']}", + "Detections": res["num_detections"], + "Inference time (ms)": round(res["inference_time"] * 1000, 2), + "Average confidence": round(float(np.mean(res["scores"])), 4) if res["scores"] else "N/A", + **out.get("settings", {}), + } + for key, value in out.get("performance", {}).items(): + report_details[f"Runtime {key}"] = value + image_report_detections = result_to_dataframe(res) + display_confidence = st.session_state.get("img_min_display_conf", 0) + visible_report_detections = image_report_detections[ + image_report_detections["confidence_%"] >= display_confidence + ] + image_charts = {} + if not visible_report_detections.empty: + image_charts = { + "Detections by category": ( + "bar", + visible_report_detections["label"].value_counts().rename("Detections").to_frame(), + "Detections", + ), + "Mean confidence by category": ( + "bar", + visible_report_detections.groupby("label")["confidence_%"].mean().sort_values( + ascending=False + ).rename("Mean confidence (%)").to_frame(), + "Mean confidence (%)", + ), + } + image_report = out.get("pdf_report") + if image_report is None or out.get("pdf_report_filter") != display_confidence: + image_report = create_pdf_report( + f"Image detection - {out['name']}", + report_details, + {"Detections": image_report_detections}, + {"Annotated image": out["annotated"]}, + image_charts, + ) + out["pdf_report"] = image_report + out["pdf_report_filter"] = display_confidence + st.download_button( + "Download image report (PDF)", + image_report, + file_name=f"{Path(out['name']).stem}_detection_report.pdf", + mime="application/pdf", + ) + st.caption(f"Saved to {out['saved']}. Time covers model inference + post-processing; " + "image decoding, resizing and drawing are excluded.") + + +# ------------------------------------------------------------------ video tab +def _save_upload(upload) -> str: + """Write the upload to a temp file once per file; remove the previous temp file.""" + key = f"{upload.name}-{upload.size}" + if st.session_state.get("vid_src_key") != key: + old = st.session_state.get("vid_src_path") + if old: + Path(old).unlink(missing_ok=True) + suffix = Path(upload.name).suffix.lower() or ".mp4" + with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as fh: + fh.write(upload.getvalue()) + st.session_state["vid_src_key"] = key + st.session_state["vid_src_path"] = fh.name + return st.session_state["vid_src_path"] + + +with tab_vid: + left, right = st.columns(2) + with left: + vid = st.file_uploader("Upload a video", type=[e.strip(".") for e in CFG["video"]["allowed_extensions"]], + key="vid_upload") + if vid is not None: + try: + src_path = _save_upload(vid) + vinfo = get_video_info(src_path) + st.video(vid.getvalue()) + a = st.columns(4) + a[0].metric("Resolution", f"{vinfo['width']}x{vinfo['height']}") + a[1].metric("Input FPS", f"{vinfo['fps']:.2f}") + a[2].metric("Total frames", vinfo["total_frames"]) + a[3].metric("Duration", f"{vinfo['duration_s']:.1f} s") + except Exception as exc: # noqa: BLE001 + show_error(exc) + vid = None + with right: + vid_prompts = prompt_input("vid") + if frame_skip > 1: + st.warning(f"Frame skipping is ON: only every {frame_skip}th frame is processed and written.") + + if st.button("Process Video", type="primary", disabled=vid is None or not vid_prompts, key="vid_run"): + progress = st.progress(0.0, text="Starting...") + preview = st.empty() + try: + validate_extension(vid.name, CFG["video"]["allowed_extensions"]) + out_path = resolve_path(CFG["paths"]["videos_out"]) / f"{Path(vid.name).stem}_{int(time.time())}_annotated.mp4" + manager.get_detector(model, resolved) + monitor = PerformanceMonitor(resolved, interval=float(CFG["benchmark"]["monitor_interval_s"])) + monitor.start() + + def on_progress(frame_no, total, processed, frame): + if total: + progress.progress(min(frame_no / total, 1.0), text=f"Frame {frame_no}/{total}") + else: + progress.progress(0.0, text=f"Frame {frame_no}") + if processed % 3 == 0: + preview.image(frame, caption="Live preview", use_container_width=True) + + try: + stats = process_video(manager, model, st.session_state["vid_src_path"], out_path, vid_prompts, + device=resolved, conf=conf, text_threshold=text_thr, + frame_skip=int(frame_skip), resize_side=video_side, imgsz=imgsz, + max_frames=int(max_frames), progress_callback=on_progress) + e2e_per_frame = stats["total_processing_time_s"] / stats["processed_frames"] + for frame in stats["per_frame"]: + monitor.record_inference(frame["inference_ms"] / 1000) + monitor.record_item(e2e_per_frame) + finally: + monitor.stop() + stats["performance"] = monitor.summary() + stats.update({"input_name": vid.name, "prompts": list(vid_prompts), "device": resolved, + "confidence_threshold": conf, "text_threshold": text_thr}) + progress.progress(1.0, text="Done") + st.session_state["vid_out"] = stats + record_run("Video", vid.name, { + "model_name": model, + "num_detections": stats["total_detections"], + "inference_time": stats["avg_inference_ms"] / 1000, + "device": resolved, + }) + except Exception as exc: # noqa: BLE001 + show_error(exc) + finally: + preview.empty() + + stats = st.session_state.get("vid_out") + if stats: + st.subheader("Results") + r1 = st.columns(4) + r1[0].metric("Processed frames", stats["processed_frames"]) + r1[1].metric("Avg inference time", f"{stats['avg_inference_ms']:.1f} ms") + r1[2].metric("Inference FPS (model only)", f"{stats['inference_fps']:.2f}") + r1[3].metric("End-to-end FPS", f"{stats['end_to_end_fps']:.2f}") + r2 = st.columns(4) + r2[0].metric("Total processing time", f"{stats['total_processing_time_s']:.1f} s") + r2[1].metric("Input FPS (not a model FPS)", f"{stats['input_fps']:.2f}") + r2[2].metric("Input frames", stats["input_total_frames"]) + r2[3].metric("Total detections", stats["total_detections"]) + st.caption(stats["note"]) + if "performance" in stats: + show_runtime_benchmark(stats["performance"], "Video processing time") + out_file = Path(stats["output_path"]) + if out_file.exists(): + data = out_file.read_bytes() + if stats["browser_playable"]: + st.video(data) + else: + st.info("The output uses the OpenCV 'mp4v' codec, which browsers often cannot play. " + "Download it, or install ffmpeg so it is converted to H.264 automatically.") + st.download_button("Download annotated video", data, file_name=out_file.name, mime="video/mp4") + st.caption(f"Saved to {out_file}") + per_frame = pd.DataFrame(stats["per_frame"]) + if not per_frame.empty: + st.line_chart(per_frame.set_index("frame")[["inference_ms"]]) + report_details = { + "Video": stats.get("input_name", Path(stats["output_path"]).name), + "Model": stats["model_name"], + "Device": stats.get("device", "-"), + "Input resolution": stats["input_resolution"], + "Input duration (seconds)": round(stats["input_duration_s"], 2), + "Input frames": stats["input_total_frames"], + "Processed frames": stats["processed_frames"], + "Frame skip": stats["frame_skip"], + "Total detections": stats["total_detections"], + "Average inference time (ms)": round(stats["avg_inference_ms"], 2), + "Inference FPS": round(stats["inference_fps"], 2), + "End-to-end FPS": round(stats["end_to_end_fps"], 2), + "Total processing time (seconds)": round(stats["total_processing_time_s"], 2), + "Prompts": stats.get("prompts", []), + "Confidence threshold": stats.get("confidence_threshold"), + "Text threshold": stats.get("text_threshold"), + "Annotated video": stats["output_path"], + } + for key, value in stats.get("performance", {}).items(): + report_details[f"Runtime {key}"] = value + video_report = stats.get("pdf_report") + if video_report is None: + video_report = create_pdf_report( + f"Video detection - {report_details['Video']}", + report_details, + {"Per-frame results": per_frame}, + charts={ + "Inference time by frame": ( + "line", + per_frame.set_index("frame")[["inference_ms"]], + "Inference time (ms)", + ), + } if not per_frame.empty else None, + ) + stats["pdf_report"] = video_report + st.download_button( + "Download video report (PDF)", + video_report, + file_name=f"{Path(report_details['Video']).stem}_video_report.pdf", + mime="application/pdf", + ) + + +# ------------------------------------------------------------------ comparison tab +def _agreement(a: dict, b: dict, thr: float = 0.5) -> pd.DataFrame: + rows = [] + for label in sorted(set(a["labels"]) | set(b["labels"])): + ba = np.array([x for x, l in zip(a["boxes"], a["labels"]) if l == label]).reshape(-1, 4) + bb = np.array([x for x, l in zip(b["boxes"], b["labels"]) if l == label]).reshape(-1, 4) + ious = pair_boxes(ba, bb, thr) + rows.append({"label": label, "Grounding DINO": len(ba), "YOLO-World": len(bb), + f"matched (IoU>={thr})": len(ious), + "mean IoU of matches": round(float(np.mean(ious)), 3) if ious else None}) + return pd.DataFrame(rows) + + +with tab_cmp: + st.markdown("Run the **same image and prompts** through both models.") + left, right = st.columns(2) + with left: + cmp_up = st.file_uploader("Test image", type=[e.strip(".") for e in CFG["image"]["allowed_extensions"]], + key="cmp_upload") + t1, t2 = st.columns(2) + dino_conf = t1.slider("Grounding DINO box threshold", 0.01, 0.95, float(CFG["detection"]["dino_box_threshold"]), 0.01) + yolo_conf = t2.slider("YOLO-World confidence", 0.01, 0.95, float(CFG["detection"]["yolo_conf"]), 0.01) + with right: + cmp_prompts = prompt_input("cmp") + + if st.button("Run both models", type="primary", disabled=cmp_up is None or not cmp_prompts, key="cmp_run"): + try: + image = load_image_rgb(cmp_up) + results = {} + performances = {} + for name, c in (("Grounding DINO", dino_conf), ("YOLO-World", yolo_conf)): + with st.spinner(f"Running {name}..."): + manager.get_detector(name, resolved) + results[name], performances[name] = run_with_performance( + lambda: run_image_detection(manager, name, image, cmp_prompts, device=resolved, + conf=c, text_threshold=text_thr, max_side=max_side, + imgsz=imgsz), + resolved, + ) + st.session_state["cmp_out"] = {"name": cmp_up.name, "image": image, "results": results, + "performances": performances, + "annotated": {n: draw_detections(image, r) for n, r in results.items()}, + "prompts": list(cmp_prompts), + "settings": {"dino_conf": dino_conf, "yolo_conf": yolo_conf, + "text_threshold": text_thr, "max_side": max_side, + "imgsz": imgsz}} + for name, result in results.items(): + record_run("Comparison", cmp_up.name, result) + except Exception as exc: # noqa: BLE001 + show_error(exc) + + cmp_out = st.session_state.get("cmp_out") + if cmp_out: + cols = st.columns(2) + rows = [] + for col, name in zip(cols, MODEL_NAMES): + r = cmp_out["results"][name] + performance = cmp_out.get("performances", {}).get(name, {}) + col.image(cmp_out["annotated"][name], caption=name, use_container_width=True) + end_to_end_s = _performance_number(performance, "e2e_total_s") + rows.append({"Model": name, "Detections": r["num_detections"], + "Avg confidence %": round(float(np.mean(r["scores"])) * 100, 1) if r["scores"] else None, + "Max confidence %": round(max(r["scores"]) * 100, 1) if r["scores"] else None, + "Inference ms": round(r["inference_time"] * 1000, 1), + "Detection pipeline ms": round(end_to_end_s * 1000, 1) if end_to_end_s is not None else None, + "Peak GPU MB": _performance_number(performance, "gpu_peak_allocated_mb"), + "Peak GPU util %": _performance_number(performance, "gpu_util_max_pct"), + "Peak RAM MB": _performance_number(performance, "ram_peak_mb")}) + comparison_summary = pd.DataFrame(rows) + st.dataframe(comparison_summary, hide_index=True, use_container_width=True) + st.bar_chart(comparison_summary.set_index("Model")[["Inference ms"]]) + st.download_button("Download model comparison (CSV)", comparison_summary.to_csv(index=False).encode("utf-8"), + file_name=f"{Path(cmp_out['name']).stem}_model_comparison.csv", + mime="text/csv") + st.markdown("**Box agreement between the two models** (greedy one-to-one matching per category)") + agreement_df = _agreement(*(cmp_out["results"][n] for n in MODEL_NAMES)) + st.dataframe(agreement_df, hide_index=True, use_container_width=True) + st.download_button("Download box agreement (CSV)", agreement_df.to_csv(index=False).encode("utf-8"), + file_name="model_box_agreement.csv", mime="text/csv") + comparison_detections = [] + for model_name, result in cmp_out["results"].items(): + detections = result_to_dataframe(result) + detections.insert(0, "model", model_name) + comparison_detections.append(detections) + comparison_detection_df = pd.concat(comparison_detections, ignore_index=True) + report_details = { + "Image": cmp_out["name"], + "Models": ", ".join(MODEL_NAMES), + "Prompts": cmp_out.get("prompts", []), + "Grounding DINO threshold": cmp_out.get("settings", {}).get("dino_conf", "-"), + "YOLO-World threshold": cmp_out.get("settings", {}).get("yolo_conf", "-"), + } + for model_name, performance in cmp_out.get("performances", {}).items(): + for key, value in performance.items(): + report_details[f"{model_name} runtime {key}"] = value + comparison_report = cmp_out.get("pdf_report") + if comparison_report is None: + comparison_report = create_pdf_report( + f"Model comparison - {cmp_out['name']}", + report_details, + {"Model summary": comparison_summary, "Box agreement": agreement_df, + "Detections": comparison_detection_df}, + {name: cmp_out["annotated"][name] for name in MODEL_NAMES}, + {"Inference time by model": ( + "bar", + comparison_summary.set_index("Model")[["Inference ms"]], + "Inference time (ms)", + )}, + ) + cmp_out["pdf_report"] = comparison_report + st.download_button( + "Download model comparison report (PDF)", + comparison_report, + file_name=f"{Path(cmp_out['name']).stem}_comparison_report.pdf", + mime="application/pdf", + ) + st.caption("Agreement is not accuracy - without ground truth neither model is the reference. " + "Thresholds differ in meaning between the two models.") + + +# ------------------------------------------------------------------ benchmark tab +with tab_bench: + success_message = st.session_state.pop("benchmark_success_message", None) + if success_message: + st.success(success_message) + benchmark_pdf = st.session_state.get("benchmark_pdf") + if benchmark_pdf: + st.download_button( + "Download dataset benchmark report (PDF)", + benchmark_pdf["data"], + file_name=benchmark_pdf["filename"], + mime="application/pdf", + ) + default_annotations = resolve_path(CFG["benchmark"]["annotations"]) + st.caption("Runtime timing and resource benchmarks appear with image, video, and comparison results. " + "Precision, recall, and mAP require a COCO-annotated image dataset.") + if not default_annotations.is_file(): + st.warning( + f"Dataset accuracy benchmarking needs a COCO annotation file. The configured file is missing: " + f"`{default_annotations}`. `annotation_format_example.json` is only a template, not ground truth." + ) + + summaries = load_summaries() + rdir = reports_dir() + table_path = rdir / "comparison_table.csv" + if not summaries: + st.warning("Evaluation has not been completed yet - no benchmark results exist. " + "Add images and COCO-style annotations, then run the benchmark below or from the command line.") + else: + for name, s in summaries.items(): + st.caption(f"{name}: {s['num_images_evaluated']} images on {s['device']} - {s['timestamp']}") + if table_path.exists(): + st.subheader("Model comparison") + st.dataframe(pd.read_csv(table_path), hide_index=True, use_container_width=True) + acc = pd.DataFrame({m: {k: s["overall"].get(k) for k in ("precision", "recall", "f1", "map50", "map50_95")} + for m, s in summaries.items()}) + perf = pd.DataFrame({m: {"Avg inference (ms)": s["performance"].get("avg_inference_ms"), + "Inference FPS": s["performance"].get("inference_fps"), + "End-to-end FPS": s["performance"].get("end_to_end_fps"), + "Peak GPU MB": s["performance"].get("gpu_peak_allocated_mb"), + "Peak RAM MB": s["performance"].get("ram_peak_mb")} for m, s in summaries.items()}) + c1, c2 = st.columns(2) + c1.markdown("**Accuracy (IoU 0.50)**") + c1.bar_chart(acc.fillna(0.0)) + c2.markdown("**Speed and memory**") + c2.dataframe(perf, use_container_width=True) + for fname in ("inference_time.png", "fps.png", "gpu_memory.png", "ram.png", "per_category_precision.png", + "per_category_recall.png", "uncommon_categories.png"): + if (rdir / fname).exists(): + st.image(str(rdir / fname), use_container_width=True) + per_cat = rdir / "per_category_comparison.csv" + if per_cat.exists(): + st.subheader("Per-category results") + st.dataframe(pd.read_csv(per_cat), hide_index=True, use_container_width=True) + + with st.expander("Run a dataset benchmark"): + benchmark_target = st.selectbox( + "Models to evaluate", + ["Both models", *MODEL_NAMES], + help="A single-model run is useful for checking one detector; both models builds the comparison report.", + ) + b1, b2 = st.columns(2) + images_dir = b1.text_input("Images folder", CFG["benchmark"]["images_dir"]) + ann_path = b2.text_input("COCO annotation JSON", CFG["benchmark"]["annotations"]) + b3, b4, b5 = st.columns(3) + b_dino = b3.number_input("Grounding DINO box threshold", 0.01, 0.95, float(CFG["detection"]["dino_box_threshold"]), 0.01) + b_yolo = b4.number_input("YOLO-World confidence", 0.01, 0.95, float(CFG["detection"]["yolo_conf"]), 0.01) + b_limit = b5.number_input("Limit images (0 = all)", 0, 100000, 0) + if st.button("Run benchmark", key="bench_run"): + image_path = resolve_path(images_dir) + annotation_path = resolve_path(ann_path) + if not image_path.is_dir(): + st.error(f"Image folder does not exist: {image_path}") + elif not any(path.is_file() for path in image_path.iterdir()): + st.error(f"No image files found in: {image_path}") + elif not annotation_path.is_file(): + st.error( + f"COCO annotation file not found: {annotation_path}. " + "Create real ground-truth annotations; the example JSON is only a format template." + ) + else: + if benchmark_target == "Both models": + cmd = [sys.executable, "-m", "benchmarking.compare_models", "--images-dir", str(image_path), + "--annotations", str(annotation_path), "--device", resolved, "--dino-conf", str(b_dino), + "--yolo-conf", str(b_yolo), "--text-threshold", str(text_thr)] + else: + selected_conf = b_dino if benchmark_target == "Grounding DINO" else b_yolo + cmd = [sys.executable, "-m", "benchmarking.evaluate", "--model", benchmark_target, + "--images-dir", str(image_path), "--annotations", str(annotation_path), + "--device", resolved, "--conf", str(selected_conf), "--text-threshold", str(text_thr), + "--max-side", str(max_side), "--imgsz", str(imgsz)] + if b_limit: + cmd += ["--limit", str(int(b_limit))] + with st.spinner("Benchmarking - this can take several minutes..."): + proc = subprocess.run(cmd, cwd=PROJECT_ROOT, capture_output=True, text=True) + if proc.returncode == 0: + if benchmark_target != "Both models": + generate_report() + report_summaries = load_summaries() + if not report_summaries: + st.error("Benchmark completed, but no evaluation summary was found to build the PDF report.") + else: + per_category = pd.DataFrame([ + {"model": name, **row} + for name, summary in report_summaries.items() + for row in summary.get("per_class", []) + ]) + category_tables = build_category_metric_tables( + per_category, + load_test_prompts().get("uncommon", []), + ) + accuracy_chart = pd.DataFrame({ + name: {key: summary["overall"].get(key) + for key in ("precision", "recall", "f1", "map50", "map50_95")} + for name, summary in report_summaries.items() + }).fillna(0.0) + benchmark_chart_files = { + "Inference time": "inference_time.png", + "Throughput": "fps.png", + "GPU memory": "gpu_memory.png", + "Process RAM": "ram.png", + "Per-category precision": "per_category_precision.png", + "Per-category recall": "per_category_recall.png", + "Uncommon category F1": "uncommon_categories.png", + } + benchmark_images = { + title: rdir / filename + for title, filename in benchmark_chart_files.items() + if (rdir / filename).is_file() + } + report_details = { + "Models shown": ", ".join(report_summaries), + "Run target": benchmark_target, + "Images folder": str(image_path), + "Annotations": str(annotation_path), + "Image limit": int(b_limit) or "All", + } + for name, summary in report_summaries.items(): + report_details[f"{name} evaluated images"] = summary["num_images_evaluated"] + report_details[f"{name} device"] = summary["device"] + report_details[f"{name} timestamp"] = summary["timestamp"] + st.session_state["benchmark_pdf"] = { + "data": create_pdf_report( + "Dataset benchmark report", + report_details, + { + "Overall metrics": pd.DataFrame([ + {"Model": name, "Metric": metric, "Value": value} + for name, summary in report_summaries.items() + for section in ("overall", "performance") + for metric, value in summary.get(section, {}).items() + ]), + **category_tables, + }, + images=benchmark_images, + charts={ + "Accuracy (IoU 0.50)": ("bar", accuracy_chart, "Score"), + }, + ), + "filename": f"dataset_benchmark_{time.strftime('%Y%m%d_%H%M%S')}.pdf", + } + st.session_state["benchmark_success_message"] = ( + f"Benchmark complete for {benchmark_target}. Updated results are shown below." + ) + st.rerun() + else: + st.error("Benchmark failed. See the command output below.") + st.code((proc.stdout + "\n" + proc.stderr)[-4000:]) + + +# ------------------------------------------------------------------ info tab +with tab_info: + st.markdown( + """ +### Objective +Evaluate **open-vocabulary object detection** for industrial computer-vision use: detect objects named +by free-text prompts with pretrained models only - **no training and no fine-tuning**. + +### Grounding DINO (`IDEA-Research/grounding-dino-tiny`) +A DINO transformer detector fused with a text encoder. Image and text features are combined inside the network +(feature enhancer, language-guided query selection, cross-modality decoder), so the prompt directly shapes every +detection. Prompts are one string with categories separated by periods. Strong with phrases and attributes, but +heavier and slower. + +### YOLO-World (`yolov8s-worldv2.pt`) +A YOLOv8-based detector with a CLIP text encoder. The vocabulary is encoded once with `set_classes()` and reused, +so inference runs like a normal YOLO model - much faster and well suited to video. Changing categories means +calling `set_classes()` again. + +### Technologies +Python, PyTorch, Hugging Face Transformers, Ultralytics, OpenCV, Streamlit, NumPy, Pillow, Pandas, Matplotlib, +Psutil, NVIDIA CUDA / NVML. + +### Limitations +- Confidence scores are not accuracy; precision/recall/mAP need ground-truth annotations. +- Thresholds mean different things in the two models, so equal sliders are not equal operating points. +- Rare or ambiguous prompts can be missed or confused; wording matters. +- Grounding DINO may return merged labels for adjacent prompts; labels are mapped back to the closest prompt. +- Peak GPU memory shown is PyTorch-allocated memory, not the total reserved by the driver. +- Uncommon categories here means rare in typical datasets - not a claim they were unseen during pretraining. + """ + ) diff --git a/benchmarking/__init__.py b/benchmarking/__init__.py new file mode 100644 index 0000000..1d9f943 --- /dev/null +++ b/benchmarking/__init__.py @@ -0,0 +1 @@ +"""Evaluation metrics, performance monitoring, benchmarking and reporting.""" diff --git a/benchmarking/compare_models.py b/benchmarking/compare_models.py new file mode 100644 index 0000000..4b1a46e --- /dev/null +++ b/benchmarking/compare_models.py @@ -0,0 +1,70 @@ +"""Run both models (each in its own process for fair RAM/GPU numbers) and build the report. + +Usage: + python -m benchmarking.compare_models --images-dir dataset/images \ + --annotations dataset/annotations/annotations.json +""" +from __future__ import annotations + +import argparse +import subprocess +import sys + +from benchmarking.report_generator import MODELS, build_comparison_table, generate_report, load_summaries +from utils.config_loader import PROJECT_ROOT, ensure_project_dirs, load_config +from utils.logger import get_logger + +logger = get_logger("compare_models") + + +def run_model_subprocess(model: str, extra_args: list[str]) -> subprocess.CompletedProcess: + """Evaluate one model in a fresh Python process so models do not share RAM/GPU memory.""" + cmd = [sys.executable, "-m", "benchmarking.evaluate", "--model", model, *extra_args] + logger.info("Running: %s", " ".join(cmd)) + return subprocess.run(cmd, cwd=PROJECT_ROOT, capture_output=True, text=True) + + +def main(argv: list[str] | None = None) -> int: + cfg = load_config() + p = argparse.ArgumentParser(description="Benchmark Grounding DINO vs YOLO-World.") + p.add_argument("--images-dir", default=cfg["benchmark"]["images_dir"]) + p.add_argument("--annotations", default=cfg["benchmark"]["annotations"]) + p.add_argument("--device", default=cfg["device"]["default"]) + p.add_argument("--dino-conf", type=float, default=None) + p.add_argument("--yolo-conf", type=float, default=None) + p.add_argument("--text-threshold", type=float, default=None) + p.add_argument("--limit", type=int, default=None) + p.add_argument("--report-only", action="store_true", help="Skip inference; rebuild the report from saved summaries") + args = p.parse_args(argv) + ensure_project_dirs() + + if not args.report_only: + for model in MODELS: + extra = ["--images-dir", args.images_dir, "--annotations", args.annotations, "--device", args.device] + conf = args.dino_conf if model == "Grounding DINO" else args.yolo_conf + if conf is not None: + extra += ["--conf", str(conf)] + if args.text_threshold is not None: + extra += ["--text-threshold", str(args.text_threshold)] + if args.limit: + extra += ["--limit", str(args.limit)] + proc = run_model_subprocess(model, extra) + print(proc.stdout) + if proc.returncode != 0: + print(proc.stderr, file=sys.stderr) + print(f"ERROR: evaluation of {model} failed (exit {proc.returncode}).", file=sys.stderr) + return proc.returncode + + outputs = generate_report() + if outputs is None: + print("Evaluation has not been completed - no summaries found.") + return 1 + print(build_comparison_table(load_summaries()).to_string(index=False)) + print("\nReport files:") + for name, path in outputs.items(): + print(f" {name}: {path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/benchmarking/evaluate.py b/benchmarking/evaluate.py new file mode 100644 index 0000000..b83d05a --- /dev/null +++ b/benchmarking/evaluate.py @@ -0,0 +1,217 @@ +"""Evaluate one model on an annotated image set (COCO-style ground truth). + +Usage: + python -m benchmarking.evaluate --model "Grounding DINO" \ + --images-dir dataset/images --annotations dataset/annotations/annotations.json + +Ground truth format: COCO detection JSON ("images", "annotations", "categories"), bbox = [x, y, w, h]. +Nothing is computed without ground truth; a missing/invalid annotation file stops with a clear error. +""" +from __future__ import annotations + +import argparse +import json +import math +import sys +import time +from datetime import datetime +from pathlib import Path + +import numpy as np +import pandas as pd + +from benchmarking.metrics import evaluate_detections +from benchmarking.performance_monitor import PerformanceMonitor +from detection.image_detection import run_image_detection +from utils.config_loader import ensure_project_dirs, load_config, resolve_path +from utils.device import resolve_device +from utils.image_utils import ImageLoadError, load_image_rgb +from utils.logger import get_logger + +logger = get_logger("evaluate") + + +class AnnotationFormatError(ValueError): + """Raised when the annotation file is missing or not valid COCO-style JSON.""" + + +def load_coco_annotations(path: str | Path) -> tuple[dict, list[str], list[str]]: + """Return (ground_truths by file_name, ordered file names, category names as written).""" + path = Path(path) + if not path.exists(): + raise AnnotationFormatError( + f"Annotation file not found: {path}. Ground truth is required - evaluation has NOT been completed.") + try: + data = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + raise AnnotationFormatError(f"Annotation file is not valid JSON: {exc}") from exc + for key in ("images", "annotations", "categories"): + if not isinstance(data, dict) or key not in data: + raise AnnotationFormatError(f"Annotation file must be COCO-style and contain '{key}'.") + images = {img["id"]: img["file_name"] for img in data["images"] if "id" in img and "file_name" in img} + categories = {c["id"]: str(c["name"]) for c in data["categories"] if "id" in c and "name" in c} + if not images or not categories: + raise AnnotationFormatError("Annotation file has no usable 'images' or 'categories'.") + gts = {name: {"boxes": [], "labels": []} for name in images.values()} + for ann in data["annotations"]: + try: + x, y, w, h = (float(v) for v in ann["bbox"]) + name = images[ann["image_id"]] + label = categories[ann["category_id"]] + except (KeyError, ValueError, TypeError) as exc: + raise AnnotationFormatError(f"Invalid annotation entry {ann!r}: {exc}") from exc + if w <= 0 or h <= 0: + raise AnnotationFormatError(f"Annotation {ann.get('id')} has a non-positive box size.") + gts[name]["boxes"].append([x, y, x + w, y + h]) + gts[name]["labels"].append(label) + return gts, list(images.values()), list(categories.values()) + + +def _clean(obj): + """Make values JSON-safe (NaN -> None, numpy -> python).""" + if isinstance(obj, dict): + return {k: _clean(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [_clean(v) for v in obj] + if isinstance(obj, (np.floating, float)): + return None if math.isnan(float(obj)) else float(obj) + if isinstance(obj, np.integer): + return int(obj) + return obj + + +def run_evaluation(manager, model_name: str, images_dir: str | Path, annotations_path: str | Path, + prompts: list[str] | None = None, device: str = "auto", conf: float | None = None, + text_threshold: float | None = None, imgsz: int | None = None, + max_side: int | None = None, warmup_runs: int | None = None, + out_dir: str | Path | None = None, limit: int | None = None, + progress_callback=None) -> dict: + """Run a model over every annotated image and compute metrics + performance statistics.""" + from models.model_manager import model_slug, normalize_model_name + + cfg = load_config() + bench = cfg["benchmark"] + model_name = normalize_model_name(model_name) + device = resolve_device(device) + conf = manager.default_conf(model_name) if conf is None else conf + text_threshold = cfg["detection"]["dino_text_threshold"] if text_threshold is None else text_threshold + warmup_runs = bench["warmup_runs"] if warmup_runs is None else warmup_runs + out_dir = Path(out_dir) if out_dir else resolve_path(cfg["paths"]["reports_out"]) + out_dir.mkdir(parents=True, exist_ok=True) + images_dir = resolve_path(images_dir) + + gts, file_names, categories = load_coco_annotations(resolve_path(annotations_path)) + if limit: + file_names = file_names[:limit] + prompts = prompts or categories + missing = [c for c in categories if c.lower() not in {p.lower() for p in prompts}] + if missing: + logger.warning("Categories in annotations but not in prompts (will have zero recall): %s", missing) + + existing = [f for f in file_names if (images_dir / f).exists()] + skipped = [f for f in file_names if f not in existing] + if skipped: + logger.warning("%d annotated images not found in %s (skipped).", len(skipped), images_dir) + if not existing: + raise AnnotationFormatError(f"None of the annotated images were found in {images_dir}.") + + # Untimed warm-up on real data (model load + CUDA kernels excluded from steady-state timings). + first_img = load_image_rgb(images_dir / existing[0]) + manager.get_detector(model_name, device) + manager.warmup(model_name, first_img, prompts, device=device, runs=warmup_runs, conf=conf, + text_threshold=text_threshold, imgsz=imgsz) + + infer_conf = min(conf, bench["map_conf_threshold"]) # low threshold -> full ranking for AP + monitor = PerformanceMonitor(device, interval=bench["monitor_interval_s"]) + predictions, per_image = {}, [] + monitor.start() + try: + for i, name in enumerate(existing, start=1): + t0 = time.perf_counter() + try: + image = load_image_rgb(images_dir / name) + except ImageLoadError as exc: + logger.warning("Skipping unreadable image %s: %s", name, exc) + skipped.append(name) + continue + result = run_image_detection(manager, model_name, image, prompts, device=device, + conf=infer_conf, text_threshold=text_threshold, + max_side=max_side, imgsz=imgsz) + e2e = time.perf_counter() - t0 + monitor.record_inference(result["inference_time"]) + monitor.record_item(e2e) + predictions[name] = {"boxes": result["boxes"], "labels": result["labels"], "scores": result["scores"]} + per_image.append({"image": name, "inference_ms": result["inference_time"] * 1000, + "end_to_end_ms": e2e * 1000, + "detections_at_operating_conf": int(sum(s >= conf for s in result["scores"]))}) + if progress_callback: + progress_callback(i, len(existing), name) + finally: + monitor.stop() + + eval_gts = {n: gts[n] for n in predictions} + metrics = evaluate_detections(predictions, eval_gts, categories, bench["iou_threshold"], conf) + perf = monitor.summary() + + summary = { + "model_name": model_name, "device": device, + "timestamp": datetime.now().isoformat(timespec="seconds"), + "images_dir": str(images_dir), "annotations": str(annotations_path), + "num_images_evaluated": len(predictions), "num_images_skipped": len(skipped), + "categories": categories, "prompts": prompts, + "operating_conf": conf, "text_threshold": text_threshold, "inference_conf_for_ap": infer_conf, + "warmup_runs": warmup_runs, "max_side": max_side, "imgsz": imgsz, + "overall": metrics["overall"], "per_class": metrics["per_class"], "performance": perf, + } + slug = model_slug(model_name) + (out_dir / f"summary_{slug}.json").write_text(json.dumps(_clean(summary), indent=2), encoding="utf-8") + (out_dir / f"predictions_{slug}.json").write_text(json.dumps(_clean(predictions)), encoding="utf-8") + pd.DataFrame(metrics["per_class"]).to_csv(out_dir / f"per_category_{slug}.csv", index=False) + pd.DataFrame(per_image).to_csv(out_dir / f"per_image_{slug}.csv", index=False) + monitor.export_csv(out_dir / f"monitor_{slug}.csv") + logger.info("Saved evaluation for %s to %s", model_name, out_dir) + return summary + + +def build_parser() -> argparse.ArgumentParser: + cfg = load_config() + p = argparse.ArgumentParser(description="Evaluate one open-vocabulary model against ground truth.") + p.add_argument("--model", required=True, help="'Grounding DINO' or 'YOLO-World'") + p.add_argument("--images-dir", default=cfg["benchmark"]["images_dir"]) + p.add_argument("--annotations", default=cfg["benchmark"]["annotations"]) + p.add_argument("--device", default=cfg["device"]["default"]) + p.add_argument("--conf", type=float, default=None, help="Operating confidence / box threshold") + p.add_argument("--text-threshold", type=float, default=None) + p.add_argument("--imgsz", type=int, default=None) + p.add_argument("--max-side", type=int, default=None) + p.add_argument("--warmup-runs", type=int, default=None) + p.add_argument("--limit", type=int, default=None, help="Evaluate only the first N images") + p.add_argument("--prompts", default=None, help="Optional comma-separated prompts (default: annotation categories)") + return p + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + from detection.prompt_manager import parse_prompts + from models.model_manager import ModelManager + + ensure_project_dirs() + try: + summary = run_evaluation(ModelManager(), args.model, args.images_dir, args.annotations, + parse_prompts(args.prompts) if args.prompts else None, args.device, + args.conf, args.text_threshold, args.imgsz, args.max_side, + args.warmup_runs, limit=args.limit) + except AnnotationFormatError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + o, p = summary["overall"], summary["performance"] + print(f"\n{summary['model_name']} on {summary['device']} ({summary['num_images_evaluated']} images)") + print(f" precision={o['precision']:.3f} recall={o['recall']:.3f} f1={o['f1']:.3f} " + f"mAP@50={o['map50']:.3f} mAP@50-95={o['map50_95']:.3f}") + print(f" avg inference={p['avg_inference_ms']:.1f} ms | inference FPS={p['inference_fps']:.2f} | " + f"end-to-end FPS={p['end_to_end_fps']:.2f}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/benchmarking/metrics.py b/benchmarking/metrics.py new file mode 100644 index 0000000..2e5d6ed --- /dev/null +++ b/benchmarking/metrics.py @@ -0,0 +1,178 @@ +"""Detection metrics: IoU, one-to-one matching, precision/recall/F1, AP and mAP. + +Matching procedure (documented, used everywhere): + 1. Predictions of one class are sorted by confidence, highest first. + 2. Each prediction is compared with the not-yet-matched ground-truth boxes of the SAME class + in the SAME image; the one with the highest IoU is taken if IoU >= threshold -> True Positive. + 3. Otherwise the prediction is a False Positive. Each ground-truth box can be matched once. + 4. Unmatched ground-truth boxes are False Negatives. +AP uses the COCO 101-point interpolated precision envelope. mAP@50-95 averages AP over +IoU thresholds 0.50, 0.55, ..., 0.95. Precision/Recall/F1 are computed at the operating +confidence threshold; AP uses all predictions (low threshold) so the full ranking is evaluated. +""" +from __future__ import annotations + +import math + +import numpy as np + +IOU_THRESHOLDS_50_95 = [round(0.5 + 0.05 * i, 2) for i in range(10)] +NAN = float("nan") + + +def iou_xyxy(a: np.ndarray, b: np.ndarray) -> np.ndarray: + """Pairwise IoU between boxes a (N,4) and b (M,4) in xyxy format -> (N,M).""" + a = np.asarray(a, dtype=float).reshape(-1, 4) + b = np.asarray(b, dtype=float).reshape(-1, 4) + if len(a) == 0 or len(b) == 0: + return np.zeros((len(a), len(b))) + ix1 = np.maximum(a[:, None, 0], b[None, :, 0]) + iy1 = np.maximum(a[:, None, 1], b[None, :, 1]) + ix2 = np.minimum(a[:, None, 2], b[None, :, 2]) + iy2 = np.minimum(a[:, None, 3], b[None, :, 3]) + inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None) + area_a = np.clip(a[:, 2] - a[:, 0], 0, None) * np.clip(a[:, 3] - a[:, 1], 0, None) + area_b = np.clip(b[:, 2] - b[:, 0], 0, None) * np.clip(b[:, 3] - b[:, 1], 0, None) + union = area_a[:, None] + area_b[None, :] - inter + return np.where(union > 0, inter / np.maximum(union, 1e-12), 0.0) + + +def pair_boxes(a: np.ndarray, b: np.ndarray, threshold: float = 0.5) -> list[float]: + """Greedy one-to-one pairing of two box sets by highest IoU. Returns IoUs of the pairs.""" + m = iou_xyxy(a, b).copy() + ious: list[float] = [] + while m.size: + i, j = np.unravel_index(int(np.argmax(m)), m.shape) + if m[i, j] < threshold: + break + ious.append(float(m[i, j])) + m[i, :] = -1.0 + m[:, j] = -1.0 + return ious + + +def _norm(label) -> str: + return " ".join(str(label).lower().split()) + + +def match_class_predictions(preds: list[tuple], gt_boxes_by_image: dict, iou_threshold: float) -> list[tuple[float, bool]]: + """preds: [(image_id, score, box)]. Returns [(score, is_true_positive)] sorted by score desc.""" + ordered = sorted(preds, key=lambda p: -p[1]) + used = {img: np.zeros(len(boxes), dtype=bool) for img, boxes in gt_boxes_by_image.items()} + flags: list[tuple[float, bool]] = [] + for image_id, score, box in ordered: + gts = gt_boxes_by_image.get(image_id) + is_tp = False + if gts is not None and len(gts): + ious = iou_xyxy(np.asarray([box]), gts)[0] + ious = np.where(used[image_id], -1.0, ious) + j = int(np.argmax(ious)) + if ious[j] >= iou_threshold: + used[image_id][j] = True + is_tp = True + flags.append((float(score), is_tp)) + return flags + + +def average_precision(flags: list[tuple[float, bool]], num_gt: int) -> float: + """COCO-style 101-point interpolated AP from score-sorted TP flags.""" + if num_gt == 0: + return NAN + if not flags: + return 0.0 + tp = np.cumsum([1 if f[1] else 0 for f in flags], dtype=float) + fp = np.cumsum([0 if f[1] else 1 for f in flags], dtype=float) + recall = tp / num_gt + precision = tp / np.maximum(tp + fp, 1e-12) + envelope = np.maximum.accumulate(precision[::-1])[::-1] + grid = np.linspace(0.0, 1.0, 101) + idx = np.searchsorted(recall, grid, side="left") + sampled = np.array([envelope[i] if i < len(envelope) else 0.0 for i in idx]) + return float(sampled.mean()) + + +def _prf(tp: int, fp: int, fn: int) -> tuple[float, float, float]: + precision = tp / (tp + fp) if (tp + fp) > 0 else NAN + recall = tp / (tp + fn) if (tp + fn) > 0 else NAN + f1 = 2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) > 0 else NAN # == 2PR/(P+R) + return precision, recall, f1 + + +def confidence_stats(scores: list[float]) -> dict: + """Average/max/min confidence and detection count (confidence is NOT accuracy).""" + if not scores: + return {"avg_confidence": NAN, "max_confidence": NAN, "min_confidence": NAN, "detection_count": 0} + arr = np.asarray(scores, dtype=float) + return {"avg_confidence": float(arr.mean()), "max_confidence": float(arr.max()), + "min_confidence": float(arr.min()), "detection_count": int(arr.size)} + + +def evaluate_detections(predictions: dict, ground_truths: dict, classes: list[str], + iou_threshold: float = 0.5, operating_conf: float = 0.0) -> dict: + """Compute overall and per-class precision, recall, F1, AP@50 and AP@50-95. + + predictions: {image_id: {"boxes": [[x1,y1,x2,y2]], "labels": [str], "scores": [float]}} + ground_truths: {image_id: {"boxes": [[x1,y1,x2,y2]], "labels": [str]}} + classes: categories to evaluate. Predictions of other labels are ignored (counted separately). + """ + class_names = [] + for c in classes: + if _norm(c) not in class_names: + class_names.append(_norm(c)) + image_ids = list(dict.fromkeys(list(ground_truths) + list(predictions))) + + per_class_preds = {c: [] for c in class_names} + per_class_gt = {c: {} for c in class_names} + ignored = 0 + for img in image_ids: + gt = ground_truths.get(img, {"boxes": [], "labels": []}) + for c in class_names: + boxes = [b for b, l in zip(gt["boxes"], gt["labels"]) if _norm(l) == c] + per_class_gt[c][img] = np.asarray(boxes, dtype=float).reshape(-1, 4) + pred = predictions.get(img) + if pred: + for b, l, s in zip(pred["boxes"], pred["labels"], pred["scores"]): + if _norm(l) in per_class_preds: + per_class_preds[_norm(l)].append((img, float(s), b)) + else: + ignored += 1 + + rows = [] + tot_tp = tot_fp = tot_fn = 0 + ap50_vals, ap5095_vals = [], [] + for c in class_names: + n_gt = int(sum(len(v) for v in per_class_gt[c].values())) + all_preds = per_class_preds[c] + kept = [p for p in all_preds if p[1] >= operating_conf] + flags = match_class_predictions(kept, per_class_gt[c], iou_threshold) + tp = sum(1 for _, t in flags if t) + fp = len(flags) - tp + fn = n_gt - tp + precision, recall, f1 = _prf(tp, fp, fn) + aps = [average_precision(match_class_predictions(all_preds, per_class_gt[c], t), n_gt) + for t in IOU_THRESHOLDS_50_95] + ap50 = aps[0] + ap5095 = float(np.mean(aps)) if n_gt > 0 else NAN + if n_gt > 0: + ap50_vals.append(ap50) + ap5095_vals.append(ap5095) + tot_tp, tot_fp, tot_fn = tot_tp + tp, tot_fp + fp, tot_fn + fn + rows.append({"category": c, "num_gt": n_gt, "num_pred": len(kept), "tp": tp, "fp": fp, "fn": fn, + "precision": precision, "recall": recall, "f1": f1, "ap50": ap50, "ap50_95": ap5095}) + + precision, recall, f1 = _prf(tot_tp, tot_fp, tot_fn) + kept_scores = [p[1] for c in class_names for p in per_class_preds[c] if p[1] >= operating_conf] + overall = { + "precision": precision, "recall": recall, "f1": f1, + "map50": float(np.mean(ap50_vals)) if ap50_vals else NAN, + "map50_95": float(np.mean(ap5095_vals)) if ap5095_vals else NAN, + "tp": tot_tp, "fp": tot_fp, "fn": tot_fn, + "iou_threshold": iou_threshold, "operating_conf": operating_conf, + "ignored_predictions": ignored, + **confidence_stats(kept_scores), + } + return {"overall": overall, "per_class": rows} + + +def is_nan(value) -> bool: + return isinstance(value, float) and math.isnan(value) diff --git a/benchmarking/pdf_report.py b/benchmarking/pdf_report.py new file mode 100644 index 0000000..50ef3d1 --- /dev/null +++ b/benchmarking/pdf_report.py @@ -0,0 +1,94 @@ +"""Create downloadable PDF reports for detection and benchmark results.""" +from __future__ import annotations + +from io import BytesIO +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pandas as pd # noqa: E402 +from matplotlib.backends.backend_pdf import PdfPages # noqa: E402 + + +def _format_value(value: object) -> str: + if value is None: + return "N/A" + if isinstance(value, (float, np.floating)) and not np.isfinite(value): + return "N/A" + if isinstance(value, (list, tuple)): + return ", ".join(str(item) for item in value) + return str(value) + + +def create_pdf_report(title: str, details: dict[str, object], + tables: dict[str, pd.DataFrame] | None = None, + images: dict[str, np.ndarray | str | Path] | None = None, + charts: dict[str, tuple[str, pd.DataFrame, str]] | None = None) -> bytes: + """Render summary, chart, table, and image pages into a downloadable PDF.""" + output = BytesIO() + with PdfPages(output) as pdf: + detail_items = list(details.items()) or [("Status", "No summary details available")] + for page_no, start in enumerate(range(0, len(detail_items), 14)): + fig = plt.figure(figsize=(11.69, 8.27)) + fig.suptitle(title, fontsize=18, fontweight="bold", x=0.08, ha="left", y=0.94) + fig.text(0.08, 0.88, "Processing report", fontsize=10, color="#0f766e") + y = 0.82 + for key, value in detail_items[start:start + 14]: + fig.text(0.08, y, f"{key}: {_format_value(value)}", fontsize=10, va="top", wrap=True) + y -= 0.052 + if page_no: + fig.text(0.92, 0.04, f"Summary page {page_no + 1}", fontsize=8, ha="right", color="#64748b") + pdf.savefig(fig, bbox_inches="tight") + plt.close(fig) + + for caption, (kind, frame, ylabel) in (charts or {}).items(): + if frame.empty: + continue + if kind not in {"bar", "line"}: + raise ValueError(f"Unsupported PDF chart type: {kind}") + chart_data = frame.apply(pd.to_numeric, errors="coerce") + fig, ax = plt.subplots(figsize=(11.69, 8.27)) + plot_options = {"marker": "o"} if kind == "line" else {} + chart_data.plot(kind=kind, ax=ax, legend=len(chart_data.columns) > 1, **plot_options) + ax.set_title(caption, loc="left", fontsize=15, fontweight="bold", pad=18) + ax.set_xlabel("") + ax.set_ylabel(ylabel) + ax.set_axisbelow(True) + ax.grid(axis="y", alpha=0.3) + ax.tick_params(axis="x", labelrotation=40 if len(chart_data.index) > 8 else 0) + if kind == "bar": + for container in ax.containers: + ax.bar_label(container, fmt="%.2g", padding=2, fontsize=7) + fig.tight_layout() + pdf.savefig(fig, bbox_inches="tight") + plt.close(fig) + + for section, frame in (tables or {}).items(): + if frame.empty: + continue + page_size = 24 + for start in range(0, len(frame), page_size): + page = frame.iloc[start:start + page_size].fillna("").astype(str) + fig, ax = plt.subplots(figsize=(11.69, 8.27)) + ax.axis("off") + ax.set_title(section, loc="left", fontsize=15, fontweight="bold", pad=18) + table = ax.table(cellText=page.values, colLabels=page.columns, loc="center", + cellLoc="left", colLoc="left") + table.auto_set_font_size(False) + table.set_fontsize(7 if len(page.columns) > 7 else 8) + table.scale(1, 1.25) + pdf.savefig(fig, bbox_inches="tight") + plt.close(fig) + + for caption, image in (images or {}).items(): + fig, ax = plt.subplots(figsize=(11.69, 8.27)) + ax.imshow(plt.imread(str(image)) if isinstance(image, (str, Path)) else image) + ax.set_title(caption, loc="left", fontsize=15, fontweight="bold", pad=18) + ax.axis("off") + pdf.savefig(fig, bbox_inches="tight") + plt.close(fig) + + return output.getvalue() diff --git a/benchmarking/performance_monitor.py b/benchmarking/performance_monitor.py new file mode 100644 index 0000000..4454247 --- /dev/null +++ b/benchmarking/performance_monitor.py @@ -0,0 +1,186 @@ +"""Reusable performance monitor: timing, FPS, RAM, CPU, GPU memory and GPU utilisation.""" +from __future__ import annotations + +import subprocess +import threading +import time +from contextlib import contextmanager +from pathlib import Path + +import numpy as np +import pandas as pd +import psutil + +from utils.device import cuda_sync +from utils.logger import get_logger + +logger = get_logger("performance_monitor") +MB = 1024 ** 2 + + +@contextmanager +def timer(device: str = "cpu"): + """Time a block with CUDA synchronisation before and after. Usage: `with timer(dev) as t: ...; t['elapsed']`.""" + cuda_sync(device) + box = {"elapsed": 0.0} + start = time.perf_counter() + try: + yield box + finally: + cuda_sync(device) + box["elapsed"] = time.perf_counter() - start + + +class PerformanceMonitor: + """Samples RAM/CPU/GPU in a background thread and accumulates per-item timings. + + Model inference time and end-to-end time are recorded separately by the caller via + record_inference() and record_item(). Call start() before and stop() after the measured work. + """ + + def __init__(self, device: str = "cpu", interval: float = 0.2): + self.device = device + self.interval = interval + self._proc = psutil.Process() + self._samples: list[dict] = [] + self._inference: list[float] = [] + self._e2e: list[float] = [] + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._nvml = None + self._nvml_handle = None + self._smi_last = 0.0 + self._smi_value: float | None = None + self._smi_ok = True + self._t0 = 0.0 + self.ram_initial_mb = 0.0 + self.ram_final_mb = 0.0 + self._cuda = device.startswith("cuda") + + # ------------------------------------------------------------ lifecycle + def start(self) -> "PerformanceMonitor": + self._samples.clear(); self._inference.clear(); self._e2e.clear() + self._stop.clear() + self.ram_initial_mb = self._proc.memory_info().rss / MB + psutil.cpu_percent(None) # prime + if self._cuda: + import torch + + torch.cuda.synchronize() + torch.cuda.reset_peak_memory_stats() + try: + import pynvml + + pynvml.nvmlInit() + self._nvml = pynvml + self._nvml_handle = pynvml.nvmlDeviceGetHandleByIndex(torch.cuda.current_device()) + except Exception as exc: # noqa: BLE001 - NVML optional; fall back to nvidia-smi + logger.info("pynvml unavailable (%s); using nvidia-smi for GPU utilisation.", exc) + self._t0 = time.perf_counter() + self._sample() + self._thread = threading.Thread(target=self._loop, daemon=True) + self._thread.start() + return self + + def stop(self) -> None: + self._stop.set() + if self._thread: + self._thread.join(timeout=2) + self._sample() + self.ram_final_mb = self._proc.memory_info().rss / MB + + def __enter__(self): + return self.start() + + def __exit__(self, *exc): + self.stop() + + # ------------------------------------------------------------- sampling + def _loop(self) -> None: + while not self._stop.wait(self.interval): + self._sample() + + def _gpu_util(self) -> float | None: + if not self._cuda: + return None + if self._nvml is not None: + try: + return float(self._nvml.nvmlDeviceGetUtilizationRates(self._nvml_handle).gpu) + except Exception: # noqa: BLE001 + return None + if self._smi_ok and time.time() - self._smi_last > 1.0: + self._smi_last = time.time() + try: + out = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu", + "--format=csv,noheader,nounits"], capture_output=True, + text=True, timeout=2) + self._smi_value = float(out.stdout.strip().splitlines()[0]) + except Exception: # noqa: BLE001 + self._smi_ok = False + return self._smi_value + + def _sample(self) -> None: + row = {"t_s": time.perf_counter() - self._t0, + "ram_mb": self._proc.memory_info().rss / MB, + "cpu_pct": psutil.cpu_percent(None), + "gpu_util_pct": self._gpu_util(), "gpu_alloc_mb": None} + if self._cuda: + import torch + + row["gpu_alloc_mb"] = torch.cuda.memory_allocated() / MB + self._samples.append(row) + + # ------------------------------------------------------------ recording + def record_inference(self, seconds: float) -> None: + """Model inference time of one item (excludes decoding, preprocessing and drawing).""" + self._inference.append(float(seconds)) + + def record_item(self, seconds: float) -> None: + """End-to-end time of one item (everything the pipeline does for it).""" + self._e2e.append(float(seconds)) + + # -------------------------------------------------------------- summary + def summary(self) -> dict: + s = pd.DataFrame(self._samples) if self._samples else pd.DataFrame(columns=["ram_mb", "cpu_pct"]) + nan = float("nan") + inf = np.asarray(self._inference, dtype=float) + e2e = np.asarray(self._e2e, dtype=float) + out = { + "ram_initial_mb": self.ram_initial_mb, + "ram_peak_mb": float(max(s["ram_mb"].max() if len(s) else 0.0, self.ram_initial_mb, self.ram_final_mb)), + "ram_final_mb": self.ram_final_mb, + "cpu_avg_pct": float(s["cpu_pct"].mean()) if len(s) else nan, + "cpu_peak_pct": float(s["cpu_pct"].max()) if len(s) else nan, + "gpu_available": self._cuda, + "gpu_total_mb": nan, "gpu_allocated_mb": nan, "gpu_peak_allocated_mb": nan, + "gpu_util_avg_pct": nan, "gpu_util_max_pct": nan, + "inference_count": int(inf.size), + "avg_inference_ms": float(inf.mean() * 1000) if inf.size else nan, + "min_inference_ms": float(inf.min() * 1000) if inf.size else nan, + "max_inference_ms": float(inf.max() * 1000) if inf.size else nan, + "inference_fps": float(inf.size / inf.sum()) if inf.size and inf.sum() > 0 else nan, + "e2e_count": int(e2e.size), + "e2e_total_s": float(e2e.sum()) if e2e.size else nan, + "end_to_end_fps": float(e2e.size / e2e.sum()) if e2e.size and e2e.sum() > 0 else nan, + } + if self._cuda: + import torch + + out["gpu_total_mb"] = torch.cuda.get_device_properties(0).total_memory / MB + out["gpu_allocated_mb"] = torch.cuda.memory_allocated() / MB + out["gpu_peak_allocated_mb"] = torch.cuda.max_memory_allocated() / MB + if "gpu_util_pct" in s and s["gpu_util_pct"].notna().any(): + out["gpu_util_avg_pct"] = float(s["gpu_util_pct"].mean()) + out["gpu_util_max_pct"] = float(s["gpu_util_pct"].max()) + return out + + def to_dataframe(self) -> pd.DataFrame: + return pd.DataFrame(self._samples) + + def export_csv(self, path: str | Path) -> Path: + """Write raw samples to CSV and the summary to _summary.csv.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + self.to_dataframe().to_csv(path, index=False) + pd.DataFrame([self.summary()]).to_csv(path.with_name(path.stem + "_summary.csv"), index=False) + return path diff --git a/benchmarking/report_generator.py b/benchmarking/report_generator.py new file mode 100644 index 0000000..0bbae5b --- /dev/null +++ b/benchmarking/report_generator.py @@ -0,0 +1,235 @@ +"""Build comparison tables, CSV files, charts and a Markdown report from evaluation summaries.""" +from __future__ import annotations + +import json +import math +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pandas as pd # noqa: E402 + +from detection.prompt_manager import load_test_prompts # noqa: E402 +from utils.config_loader import load_config, resolve_path # noqa: E402 +from utils.logger import get_logger # noqa: E402 + +logger = get_logger("report_generator") +MODELS = ["Grounding DINO", "YOLO-World"] +SLUGS = {"Grounding DINO": "grounding_dino", "YOLO-World": "yolo_world"} +NOT_EVALUATED = "Not evaluated" + +# (row label, getter path) - getter looks into summary["overall"] or summary["performance"] +TABLE_ROWS = [ + ("Precision", "overall", "precision"), + ("Recall", "overall", "recall"), + ("F1 Score", "overall", "f1"), + ("mAP@50", "overall", "map50"), + ("mAP@50-95", "overall", "map50_95"), + ("Average inference time (ms)", "performance", "avg_inference_ms"), + ("Inference FPS", "performance", "inference_fps"), + ("End-to-end FPS", "performance", "end_to_end_fps"), + ("Peak GPU memory (MB)", "performance", "gpu_peak_allocated_mb"), + ("Peak RAM (MB)", "performance", "ram_peak_mb"), + ("Average confidence", "overall", "avg_confidence"), +] + + +def reports_dir() -> Path: + path = resolve_path(load_config()["paths"]["reports_out"]) + path.mkdir(parents=True, exist_ok=True) + return path + + +def load_summaries(directory: Path | None = None) -> dict[str, dict]: + directory = directory or reports_dir() + found = {} + for model in MODELS: + path = directory / f"summary_{SLUGS[model]}.json" + if path.exists(): + found[model] = json.loads(path.read_text(encoding="utf-8")) + return found + + +def _value(summary: dict | None, section: str, key: str): + if not summary: + return None + return summary.get(section, {}).get(key) + + +def build_comparison_table(summaries: dict[str, dict]) -> pd.DataFrame: + rows = [] + for label, section, key in TABLE_ROWS: + row = {"Metric": label} + for model in MODELS: + val = _value(summaries.get(model), section, key) + row[model] = NOT_EVALUATED if val is None else round(float(val), 4) + rows.append(row) + return pd.DataFrame(rows) + + +def build_per_category_table(summaries: dict[str, dict]) -> pd.DataFrame: + frames = [] + for model, summary in summaries.items(): + df = pd.DataFrame(summary.get("per_class", [])) + if df.empty: + continue + df.insert(0, "model", model) + frames.append(df) + return pd.concat(frames, ignore_index=True) if frames else pd.DataFrame() + + +def build_category_metric_tables(per_category: pd.DataFrame, + uncommon_categories: list[str]) -> dict[str, pd.DataFrame]: + """Build readable per-category precision/recall and uncommon F1 tables.""" + models_by_category = { + (str(row["category"]).strip().lower(), str(row["model"])): row + for _, row in per_category.iterrows() + } + categories = list(dict.fromkeys(per_category.get("category", pd.Series(dtype=str)).astype(str))) + + def metric_value(category: str, model: str, metric: str) -> str: + row = models_by_category.get((category.lower(), model)) + value = row.get(metric) if row is not None else None + return "N/A" if value is None or pd.isna(value) else f"{float(value):.3f}" + + precision_recall = [ + { + "Category": category.title(), + **{ + f"{model} {metric}": metric_value(category, model, metric) + for model in MODELS + for metric in ("precision", "recall") + }, + } + for category in categories + ] + uncommon = {category.strip().lower() for category in uncommon_categories} + uncommon_f1 = [ + { + "Category": category.title(), + **{f"{model} F1": metric_value(category, model, "f1") for model in MODELS}, + } + for category in categories if category.lower() in uncommon + ] + return { + "Per-category precision and recall": pd.DataFrame(precision_recall), + "Uncommon category F1": pd.DataFrame(uncommon_f1), + } + + +def _num(value) -> float: + return float("nan") if value is None else float(value) + + +def _grouped_bar(path: Path, title: str, ylabel: str, labels: list[str], values: dict[str, list[float]]) -> None: + fig, ax = plt.subplots(figsize=(max(6, 1.3 * len(labels) + 3), 4.2)) + width = 0.8 / max(1, len(values)) + x = np.arange(len(labels)) + for i, (model, vals) in enumerate(values.items()): + arr = np.array([0.0 if (v is None or math.isnan(v)) else v for v in vals]) + bars = ax.bar(x + i * width - 0.4 + width / 2, arr, width, label=model) + for bar, raw in zip(bars, vals): + txt = "n/a" if (raw is None or math.isnan(raw)) else f"{raw:.2f}" + ax.annotate(txt, (bar.get_x() + bar.get_width() / 2, bar.get_height()), + ha="center", va="bottom", fontsize=7) + ax.set_xticks(x) + ax.set_xticklabels(labels, rotation=30 if len(labels) > 4 else 0, ha="right" if len(labels) > 4 else "center") + ax.set_title(title) + ax.set_ylabel(ylabel) + ax.legend() + ax.grid(axis="y", alpha=0.3) + fig.tight_layout() + fig.savefig(path, dpi=150) + plt.close(fig) + + +def _metric_chart(path, title, ylabel, summaries, items): + labels = [lbl for lbl, _, _ in items] + values = {m: [_num(_value(summaries.get(m), sec, key)) for _, sec, key in items] for m in summaries} + _grouped_bar(path, title, ylabel, labels, values) + + +def generate_report(directory: Path | None = None) -> dict | None: + """Create CSVs, charts and report.md from the saved summaries. Returns paths, or None if no data.""" + directory = directory or reports_dir() + summaries = load_summaries(directory) + if not summaries: + logger.warning("No evaluation summaries found in %s - evaluation has not been completed.", directory) + return None + + outputs: dict[str, str] = {} + table = build_comparison_table(summaries) + table.to_csv(directory / "comparison_table.csv", index=False) + outputs["comparison_table"] = str(directory / "comparison_table.csv") + per_cat = build_per_category_table(summaries) + if not per_cat.empty: + per_cat.to_csv(directory / "per_category_comparison.csv", index=False) + outputs["per_category"] = str(directory / "per_category_comparison.csv") + + charts = { + "accuracy.png": ("Accuracy metrics (IoU 0.50 matching)", "score", + [("Precision", "overall", "precision"), ("Recall", "overall", "recall"), + ("F1", "overall", "f1"), ("mAP@50", "overall", "map50"), + ("mAP@50-95", "overall", "map50_95")]), + "inference_time.png": ("Average inference time", "ms / image", + [("avg", "performance", "avg_inference_ms"), + ("min", "performance", "min_inference_ms"), + ("max", "performance", "max_inference_ms")]), + "fps.png": ("Throughput", "frames (images) per second", + [("Inference FPS", "performance", "inference_fps"), + ("End-to-end FPS", "performance", "end_to_end_fps")]), + "gpu_memory.png": ("GPU memory (PyTorch allocated)", "MB", + [("Allocated (end)", "performance", "gpu_allocated_mb"), + ("Peak allocated", "performance", "gpu_peak_allocated_mb"), + ("Total GPU", "performance", "gpu_total_mb")]), + "ram.png": ("Process RAM", "MB", + [("Initial", "performance", "ram_initial_mb"), ("Peak", "performance", "ram_peak_mb"), + ("Final", "performance", "ram_final_mb")]), + } + for fname, (title, ylabel, items) in charts.items(): + _metric_chart(directory / fname, title, ylabel, summaries, items) + outputs[fname] = str(directory / fname) + + if not per_cat.empty: + cats = list(dict.fromkeys(per_cat["category"])) + for metric in ("precision", "recall"): + vals = {} + for model in summaries: + sub = per_cat[per_cat["model"] == model].set_index("category") + vals[model] = [_num(sub[metric].get(c)) if c in sub.index else float("nan") for c in cats] + _grouped_bar(directory / f"per_category_{metric}.png", f"Per-category {metric}", metric, cats, vals) + outputs[f"per_category_{metric}.png"] = str(directory / f"per_category_{metric}.png") + + uncommon = [u.lower() for u in load_test_prompts().get("uncommon", [])] + unc = [c for c in cats if c.lower() in uncommon] + if unc: + vals = {} + for model in summaries: + sub = per_cat[per_cat["model"] == model].set_index("category") + vals[model] = [_num(sub["f1"].get(c)) if c in sub.index else float("nan") for c in unc] + _grouped_bar(directory / "uncommon_categories.png", + "Uncommon categories - F1 (rare in typical datasets; not a claim about pretraining data)", + "F1", unc, vals) + outputs["uncommon_categories.png"] = str(directory / "uncommon_categories.png") + + lines = ["# Open-Vocabulary Detection - Benchmark Report", ""] + for model, s in summaries.items(): + lines.append(f"- **{model}**: device `{s['device']}`, {s['num_images_evaluated']} images, " + f"operating confidence {s['operating_conf']}, run {s['timestamp']}") + lines += ["", "## Comparison", "", table.to_markdown(index=False) if _has_tabulate() else table.to_string(index=False), "", + "Missing models are shown as 'Not evaluated'. Confidence is not accuracy. " + "Both models were evaluated in separate processes on the same hardware, images and annotations.", ""] + (directory / "benchmark_report.md").write_text("\n".join(lines), encoding="utf-8") + outputs["report"] = str(directory / "benchmark_report.md") + return outputs + + +def _has_tabulate() -> bool: + try: + import tabulate # noqa: F401 + return True + except ImportError: + return False diff --git a/config/config.yaml b/config/config.yaml new file mode 100644 index 0000000..10dee5f --- /dev/null +++ b/config/config.yaml @@ -0,0 +1,41 @@ +# Central application configuration. The UI can override most values at runtime. +app: + name: "Open-Vocabulary Object Detection" + +device: + default: auto # auto | cuda | cpu (auto = CUDA if available, else CPU) + +detection: + yolo_conf: 0.25 # YOLO-World confidence threshold + dino_box_threshold: 0.35 # Grounding DINO box threshold + dino_text_threshold: 0.25 # Grounding DINO text threshold + +image: + inference_max_side: 1280 # resize long side before inference (0 = keep original size) + yolo_imgsz: 640 # Ultralytics inference size + allowed_extensions: [".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"] + +video: + frame_skip: 1 # 1 = process every frame, N = process every Nth frame + resize_long_side: 0 # 0 = keep original resolution + warmup: true # one untimed warm-up inference before the timed loop + max_frames: 0 # 0 = process the full video + codecs: ["avc1", "mp4v"] # tried in order when creating the output video + allowed_extensions: [".mp4", ".avi", ".mov", ".mkv", ".webm"] + +paths: + images_in: dataset/images + videos_in: dataset/videos + annotations_dir: dataset/annotations + prompts_dir: dataset/prompts + images_out: outputs/images + videos_out: outputs/videos + reports_out: outputs/reports + +benchmark: + warmup_runs: 3 # untimed warm-up inferences before measuring + iou_threshold: 0.50 # primary matching threshold + map_conf_threshold: 0.05 # low threshold used so AP sees the full ranking + monitor_interval_s: 0.2 # background sampling period for RAM / CPU / GPU util + images_dir: dataset/images + annotations: dataset/annotations/annotations.json diff --git a/config/model_config.yaml b/config/model_config.yaml new file mode 100644 index 0000000..30c0017 --- /dev/null +++ b/config/model_config.yaml @@ -0,0 +1,9 @@ +models: + grounding_dino: + display_name: "Grounding DINO" + checkpoint: "IDEA-Research/grounding-dino-tiny" + cache_dir: weights/grounding_dino # Hugging Face download cache + yolo_world: + display_name: "YOLO-World" + checkpoint: "yolov8s-worldv2.pt" + weights_dir: weights/yolo_world diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..8282ccd --- /dev/null +++ b/conftest.py @@ -0,0 +1,5 @@ +"""Makes the project root importable when running `pytest` from any directory.""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) diff --git a/dataset/annotations/annotation_format_example.json b/dataset/annotations/annotation_format_example.json new file mode 100644 index 0000000..eb1f4ad --- /dev/null +++ b/dataset/annotations/annotation_format_example.json @@ -0,0 +1,14 @@ +{ + "_comment": "FORMAT TEMPLATE ONLY - not real ground truth. Copy to annotations.json and replace with your own labelled data. bbox = [x, y, width, height] in pixels.", + "images": [ + {"id": 1, "file_name": "example_image.jpg", "width": 1280, "height": 720} + ], + "categories": [ + {"id": 1, "name": "person"}, + {"id": 2, "name": "safety helmet"} + ], + "annotations": [ + {"id": 1, "image_id": 1, "category_id": 1, "bbox": [100, 80, 200, 370], "iscrowd": 0}, + {"id": 2, "image_id": 1, "category_id": 2, "bbox": [140, 80, 110, 90], "iscrowd": 0} + ] +} diff --git a/dataset/images/.gitkeep b/dataset/images/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/dataset/prompts/test_prompts.json b/dataset/prompts/test_prompts.json new file mode 100644 index 0000000..14b8d5d --- /dev/null +++ b/dataset/prompts/test_prompts.json @@ -0,0 +1,19 @@ +{ + "description": "Test categories for open-vocabulary detection. Edit freely or add categories in the UI.", + "categories": [ + "person", "safety helmet", "safety vest", "fire extinguisher", "mobile phone", + "laptop", "traffic cone", "toolbox", "welding machine", "industrial safety equipment", + "Vending Machine", "Ambulance", "Telescope", "Stretcher", "Suitcase" + ], + "common": [ + "person", "safety helmet", "safety vest", "fire extinguisher", "mobile phone", + "laptop", "traffic cone", "toolbox", "welding machine", "industrial safety equipment" + ], + "uncommon": ["Vending Machine", "Ambulance", "Telescope", "Stretcher", "Suitcase"], + "image_conditions": [ + "single objects", "multiple objects", "small objects", "large objects", + "partially occluded objects", "different distances", "different lighting conditions", + "cluttered industrial environments" + ], + "note": "'Uncommon' means rare in typical datasets. It is NOT a claim that these categories were unseen during pretraining." +} diff --git a/dataset/videos/.gitkeep b/dataset/videos/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/detection/__init__.py b/detection/__init__.py new file mode 100644 index 0000000..f54bbf8 --- /dev/null +++ b/detection/__init__.py @@ -0,0 +1 @@ +"""Detection pipelines: prompts, images, video and visualisation.""" diff --git a/detection/image_detection.py b/detection/image_detection.py new file mode 100644 index 0000000..2c2ae24 --- /dev/null +++ b/detection/image_detection.py @@ -0,0 +1,73 @@ +"""Image detection pipeline (also usable from the command line).""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import numpy as np + +from detection.prompt_manager import parse_prompts, require_prompts +from detection.visualization import draw_detections, save_annotated_image +from utils.config_loader import ensure_project_dirs, load_config +from utils.image_utils import load_image_rgb, resize_long_side, validate_extension +from utils.logger import get_logger + +logger = get_logger("image_detection") + + +def run_image_detection(manager, model_name: str, image_rgb: np.ndarray, prompts: list[str], + device: str = "auto", conf: float | None = None, + text_threshold: float | None = None, max_side: int | None = None, + imgsz: int | None = None) -> dict: + """Run one model on one image. Returned boxes are in ORIGINAL image coordinates. + + The image may be downscaled for inference (max_side); boxes are mapped back afterwards. + """ + prompts = require_prompts(prompts) + cfg = load_config()["image"] + max_side = cfg["inference_max_side"] if max_side is None else max_side + orig_h, orig_w = image_rgb.shape[:2] + + small, scale = resize_long_side(image_rgb, max_side) + result = manager.detect(model_name, small, prompts, device=device, conf=conf, + text_threshold=text_threshold, imgsz=imgsz) + if scale != 1.0: + result["boxes"] = [ + [round(min(max(v / scale, 0.0), lim), 2) for v, lim in zip(box, (orig_w, orig_h, orig_w, orig_h))] + for box in result["boxes"] + ] + result["image_width"], result["image_height"] = orig_w, orig_h + result["inference_scale"] = scale + result["prompts"] = prompts + return result + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Open-vocabulary detection on one image.") + parser.add_argument("--image", required=True, help="Path to the input image") + parser.add_argument("--model", default="Grounding DINO", help="'Grounding DINO' or 'YOLO-World'") + parser.add_argument("--prompts", required=True, help="Comma-separated categories, e.g. 'person, safety helmet'") + parser.add_argument("--device", default=load_config()["device"]["default"]) + parser.add_argument("--conf", type=float, default=None, help="Confidence / box threshold") + parser.add_argument("--text-threshold", type=float, default=None) + parser.add_argument("--max-side", type=int, default=None) + args = parser.parse_args(argv) + + from models.model_manager import ModelManager, normalize_model_name + + ensure_project_dirs() + validate_extension(args.image, load_config()["image"]["allowed_extensions"]) + image = load_image_rgb(args.image) + result = run_image_detection(ModelManager(), normalize_model_name(args.model), image, + parse_prompts(args.prompts), args.device, args.conf, + args.text_threshold, args.max_side) + out = save_annotated_image(draw_detections(image, result), stem=Path(args.image).stem) + print(json.dumps({k: v for k, v in result.items() if k != "prompts"}, indent=2)) + print(f"\nAnnotated image saved to: {out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/detection/prompt_manager.py b/detection/prompt_manager.py new file mode 100644 index 0000000..0fa20b1 --- /dev/null +++ b/detection/prompt_manager.py @@ -0,0 +1,118 @@ +"""Prompt (object category) parsing, per-model preparation and preset storage.""" +from __future__ import annotations + +import json +import re +from pathlib import Path + +from utils.config_loader import load_config, resolve_path + + +class PromptError(ValueError): + """Raised when no valid prompts remain after cleaning.""" + + +def normalize_prompt(text: str) -> str: + """Collapse whitespace and strip surrounding spaces/periods.""" + return re.sub(r"\s+", " ", str(text)).strip().strip(".").strip() + + +def parse_prompts(raw: str | list[str]) -> list[str]: + """Split comma/newline separated text (or a list) into a clean, de-duplicated list. + + Order is preserved; duplicates are detected case-insensitively; empties are removed. + """ + if isinstance(raw, str): + parts = re.split(r"[,\n\r;]+", raw) + else: + parts = [piece for item in raw for piece in re.split(r"[\n\r;]+", str(item))] + seen: set[str] = set() + cleaned: list[str] = [] + for part in parts: + norm = normalize_prompt(part) + if norm and norm.lower() not in seen: + seen.add(norm.lower()) + cleaned.append(norm) + return cleaned + + +def require_prompts(prompts: list[str]) -> list[str]: + cleaned = parse_prompts(prompts) + if not cleaned: + raise PromptError("Please enter at least one object category.") + return cleaned + + +def prepare_for_grounding_dino(prompts: list[str]) -> str: + """Grounding DINO expects ONE lower-case string with classes separated by periods.""" + cleaned = require_prompts(prompts) + return " . ".join(p.lower() for p in cleaned) + " ." + + +def prepare_for_yolo_world(prompts: list[str]) -> list[str]: + """YOLO-World's set_classes() expects a list of class names.""" + return require_prompts(prompts) + + +def match_label_to_prompt(label: str, prompts: list[str]) -> str: + """Map a (possibly partial/composite) Grounding DINO label back to one of the prompts.""" + norm = normalize_prompt(label).lower() + lookup = {p.lower(): p for p in prompts} + if norm in lookup: + return lookup[norm] + candidates = [orig for low, orig in lookup.items() if low in norm or norm in low] + if candidates: + return max(candidates, key=len) + return norm + + +# ----------------------------------------------------------------- presets +def _prompts_dir() -> Path: + path = resolve_path(load_config()["paths"]["prompts_dir"]) + path.mkdir(parents=True, exist_ok=True) + return path + + +def load_test_prompts() -> dict: + path = _prompts_dir() / "test_prompts.json" + if not path.exists(): + return {"categories": [], "common": [], "uncommon": []} + with path.open("r", encoding="utf-8") as fh: + return json.load(fh) + + +def load_saved_presets() -> dict[str, list[str]]: + path = _prompts_dir() / "saved_prompts.json" + if not path.exists(): + return {} + try: + with path.open("r", encoding="utf-8") as fh: + data = json.load(fh) + except (json.JSONDecodeError, OSError): + return {} + return {str(k): parse_prompts(v) for k, v in data.items() if isinstance(v, list)} + + +def save_prompt_preset(name: str, prompts: list[str]) -> None: + name = normalize_prompt(name) + if not name: + raise PromptError("Preset name cannot be empty.") + prompts = require_prompts(prompts) + presets = load_saved_presets() + presets[name] = prompts + with (_prompts_dir() / "saved_prompts.json").open("w", encoding="utf-8") as fh: + json.dump(presets, fh, indent=2, ensure_ascii=False) + + +def get_all_presets() -> dict[str, list[str]]: + """Built-in test sets followed by the user's saved presets.""" + test = load_test_prompts() + presets: dict[str, list[str]] = {} + if test.get("categories"): + presets[f"Test set - all {len(test['categories'])} categories"] = test["categories"] + if test.get("common"): + presets["Test set - common"] = test["common"] + if test.get("uncommon"): + presets["Test set - uncommon industrial"] = test["uncommon"] + presets.update(load_saved_presets()) + return presets diff --git a/detection/video_detection.py b/detection/video_detection.py new file mode 100644 index 0000000..1811fdb --- /dev/null +++ b/detection/video_detection.py @@ -0,0 +1,178 @@ +"""Video detection pipeline (also usable from the command line).""" +from __future__ import annotations + +import argparse +import json +import shutil +import sys +import time +from pathlib import Path +from typing import Callable + +import cv2 +import numpy as np + +from detection.prompt_manager import parse_prompts, require_prompts +from detection.visualization import draw_detections +from utils.config_loader import ensure_project_dirs, load_config, resolve_path +from utils.image_utils import resize_long_side +from utils.logger import get_logger +from utils.video_utils import VideoError, create_video_writer, get_video_info, reencode_h264 + +logger = get_logger("video_detection") + + +def process_video(manager, model_name: str, input_path: str | Path, output_path: str | Path, + prompts: list[str], device: str = "auto", conf: float | None = None, + text_threshold: float | None = None, frame_skip: int | None = None, + resize_side: int | None = None, imgsz: int | None = None, + max_frames: int | None = None, warmup: bool | None = None, + progress_callback: Callable | None = None) -> dict: + """Detect objects in every Nth frame, write an annotated video and return timing statistics. + + Timing definitions + inference FPS = processed frames / summed MODEL inference time (forward + post-processing) + end-to-end FPS = processed frames / wall time of the whole loop (decode, resize, model, + drawing, encoding) + The input video's FPS is reported separately and is never used as a model FPS. + + When frame_skip > 1 only every Nth frame is processed AND written; the output video is + written at input_fps / frame_skip so it still plays back at real-time speed. + """ + cfg = load_config()["video"] + frame_skip = max(1, int(cfg["frame_skip"] if frame_skip is None else frame_skip)) + resize_side = cfg["resize_long_side"] if resize_side is None else resize_side + max_frames = cfg["max_frames"] if max_frames is None else max_frames + warmup = cfg["warmup"] if warmup is None else warmup + prompts = require_prompts(prompts) + + input_path, output_path = Path(input_path), Path(output_path) + info = get_video_info(input_path) + cap = cv2.VideoCapture(str(input_path)) + if not cap.isOpened(): + raise VideoError(f"Cannot open video '{input_path.name}'.") + + writer = None + codec_used = None + tmp_path = output_path.with_suffix(".tmp.mp4") + records: list[dict] = [] + frame_idx = -1 + processed = 0 + try: + if warmup: # untimed warm-up on a blank frame of the working resolution + blank, _ = resize_long_side(np.full((info["height"] or 480, info["width"] or 640, 3), 127, np.uint8), + resize_side) + manager.detect(model_name, blank, prompts, device=device, conf=conf, + text_threshold=text_threshold, imgsz=imgsz) + + loop_start = time.perf_counter() + while True: + ok, bgr = cap.read() + if not ok: + break + frame_idx += 1 + if frame_idx % frame_skip != 0: + continue + if max_frames and processed >= max_frames: + break + + frame = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + frame, _ = resize_long_side(frame, resize_side) + result = manager.detect(model_name, frame, prompts, device=device, conf=conf, + text_threshold=text_threshold, imgsz=imgsz) + total = info["total_frames"] or "?" + header = (f"Frame {frame_idx + 1}/{total} | {result['model_name']} | " + f"{result['num_detections']} det | {result['inference_time'] * 1000:.1f} ms") + annotated = draw_detections(frame, result, header=header) + + if writer is None: + out_fps = info["fps"] / frame_skip + h, w = annotated.shape[:2] + writer, codec_used = create_video_writer(tmp_path, out_fps, (w, h), cfg["codecs"]) + writer.write(cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR)) + + processed += 1 + scores = result["scores"] + records.append({ + "frame": frame_idx + 1, + "inference_ms": result["inference_time"] * 1000, + "num_detections": result["num_detections"], + "avg_confidence": float(np.mean(scores)) if scores else None, + }) + if progress_callback: + progress_callback(frame_idx + 1, info["total_frames"], processed, annotated) + wall_time = time.perf_counter() - loop_start + finally: + cap.release() + if writer is not None: + writer.release() + + if processed == 0: + tmp_path.unlink(missing_ok=True) + raise VideoError("No frames were processed - the video may be empty or unreadable.") + + # Browser-playable H.264 when ffmpeg exists; otherwise keep the OpenCV file as written. + browser_playable = codec_used == "avc1" + if codec_used != "avc1" and reencode_h264(tmp_path, output_path): + tmp_path.unlink(missing_ok=True) + browser_playable = True + else: + shutil.move(str(tmp_path), str(output_path)) + + inference_total = sum(r["inference_ms"] for r in records) / 1000.0 + stats = { + "model_name": model_name, + "output_path": str(output_path), + "codec": codec_used, + "browser_playable": browser_playable, + "input_fps": info["fps"], + "input_total_frames": info["total_frames"], + "input_duration_s": info["duration_s"], + "input_resolution": f"{info['width']}x{info['height']}", + "processed_frames": processed, + "frame_skip": frame_skip, + "frame_skip_enabled": frame_skip > 1, + "resize_long_side": resize_side or None, + "avg_inference_ms": 1000.0 * inference_total / processed, + "inference_fps": processed / inference_total if inference_total > 0 else float("nan"), + "end_to_end_fps": processed / wall_time if wall_time > 0 else float("nan"), + "total_processing_time_s": wall_time, + "total_detections": int(sum(r["num_detections"] for r in records)), + "per_frame": records, + "note": (f"Frame skipping enabled: every {frame_skip}th frame was processed and written; " + f"output plays at {info['fps'] / frame_skip:.2f} FPS." if frame_skip > 1 + else "All frames were processed."), + } + logger.info("Video done: %d frames, inference %.1f FPS, end-to-end %.1f FPS", + processed, stats["inference_fps"], stats["end_to_end_fps"]) + return stats + + +def main(argv: list[str] | None = None) -> int: + cfg = load_config() + parser = argparse.ArgumentParser(description="Open-vocabulary detection on a video.") + parser.add_argument("--video", required=True) + parser.add_argument("--model", default="YOLO-World") + parser.add_argument("--prompts", required=True, help="Comma-separated categories") + parser.add_argument("--device", default=cfg["device"]["default"]) + parser.add_argument("--conf", type=float, default=None) + parser.add_argument("--text-threshold", type=float, default=None) + parser.add_argument("--frame-skip", type=int, default=None) + parser.add_argument("--resize-side", type=int, default=None) + parser.add_argument("--max-frames", type=int, default=None) + args = parser.parse_args(argv) + + from models.model_manager import ModelManager, normalize_model_name + + ensure_project_dirs() + out = resolve_path(cfg["paths"]["videos_out"]) / f"{Path(args.video).stem}_{int(time.time())}_annotated.mp4" + stats = process_video(ModelManager(), normalize_model_name(args.model), args.video, out, + parse_prompts(args.prompts), args.device, args.conf, args.text_threshold, + args.frame_skip, args.resize_side, max_frames=args.max_frames) + stats.pop("per_frame") + print(json.dumps(stats, indent=2, default=str)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/detection/visualization.py b/detection/visualization.py new file mode 100644 index 0000000..f15b3e4 --- /dev/null +++ b/detection/visualization.py @@ -0,0 +1,78 @@ +"""Drawing detections and turning results into tables.""" +from __future__ import annotations + +import colorsys +import hashlib +import time +from pathlib import Path + +import cv2 +import numpy as np +import pandas as pd + +from utils.config_loader import load_config, resolve_path + + +def color_for_label(label: str) -> tuple[int, int, int]: + """Stable RGB colour per category (same label -> same colour across runs).""" + digest = hashlib.md5(label.lower().encode("utf-8")).digest() + r, g, b = colorsys.hsv_to_rgb(digest[0] / 255.0, 0.75, 0.95) + return int(r * 255), int(g * 255), int(b * 255) + + +def draw_detections(image_rgb: np.ndarray, result: dict, header: str | None = None, + show_summary: bool = True) -> np.ndarray: + """Return a copy of the image with boxes, 'label NN%' tags and a summary bar.""" + canvas = image_rgb.copy() + h, w = canvas.shape[:2] + thickness = max(2, int(round(max(h, w) / 500))) + font_scale = max(0.5, min(h, w) / 900) + font = cv2.FONT_HERSHEY_SIMPLEX + text_thickness = max(1, thickness - 1) + + for box, label, score in zip(result["boxes"], result["labels"], result["scores"]): + x1, y1, x2, y2 = (int(round(v)) for v in box) + color = color_for_label(label) + cv2.rectangle(canvas, (x1, y1), (x2, y2), color, thickness) + tag = f"{label} {score * 100:.0f}%" + (tw, th), baseline = cv2.getTextSize(tag, font, font_scale, text_thickness) + top = y1 - th - baseline - 4 + if top < 0: + top = y1 + cv2.rectangle(canvas, (x1, top), (x1 + tw + 6, top + th + baseline + 4), color, -1) + cv2.putText(canvas, tag, (x1 + 3, top + th + 1), font, font_scale, (0, 0, 0), text_thickness, cv2.LINE_AA) + + if show_summary or header: + text = header or (f"{result['model_name']} | {result['num_detections']} detections | " + f"{result['inference_time'] * 1000:.1f} ms") + (tw, th), baseline = cv2.getTextSize(text, font, font_scale, text_thickness) + cv2.rectangle(canvas, (0, 0), (tw + 12, th + baseline + 10), (20, 24, 31), -1) + cv2.putText(canvas, text, (6, th + 5), font, font_scale, (255, 255, 255), text_thickness, cv2.LINE_AA) + return canvas + + +def result_to_dataframe(result: dict) -> pd.DataFrame: + """Detections as a table (xyxy pixels in the original image).""" + columns = ["#", "label", "confidence_%", "x1", "y1", "x2", "y2", "width", "height"] + rows = [] + for i, (box, label, score) in enumerate(zip(result["boxes"], result["labels"], result["scores"]), start=1): + x1, y1, x2, y2 = box + rows.append({"#": i, "label": label, "confidence_%": round(score * 100, 1), + "x1": round(x1, 1), "y1": round(y1, 1), "x2": round(x2, 1), "y2": round(y2, 1), + "width": round(x2 - x1, 1), "height": round(y2 - y1, 1)}) + return pd.DataFrame(rows, columns=columns) + + +def save_annotated_image(image_rgb: np.ndarray, directory: str | Path | None = None, + stem: str = "detection") -> Path: + """Save an RGB image as PNG under outputs/images (unicode-safe). Returns the file path.""" + directory = Path(directory) if directory else resolve_path(load_config()["paths"]["images_out"]) + directory.mkdir(parents=True, exist_ok=True) + stamp = time.strftime("%Y%m%d_%H%M%S") + f"_{int((time.time() % 1) * 1000):03d}" + safe_stem = "".join(c if c.isalnum() or c in "-_" else "_" for c in stem)[:60] or "detection" + path = directory / f"{safe_stem}_{stamp}.png" + ok, buf = cv2.imencode(".png", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)) + if not ok: + raise OSError("Could not encode the annotated image.") + path.write_bytes(buf.tobytes()) + return path diff --git a/models/__init__.py b/models/__init__.py new file mode 100644 index 0000000..e087259 --- /dev/null +++ b/models/__init__.py @@ -0,0 +1,34 @@ +"""Detector wrappers sharing one common output format.""" +from __future__ import annotations + + +class ModelLoadError(RuntimeError): + """Raised when a model or its weights cannot be loaded.""" + + +class DetectionError(RuntimeError): + """Raised when inference fails (e.g. GPU out of memory).""" + + +def build_result(model_name: str, boxes, labels, scores, inference_time: float, + image_shape: tuple, **extra) -> dict: + """Build the standard detection dict. Boxes are xyxy in the coordinates of image_shape.""" + height, width = int(image_shape[0]), int(image_shape[1]) + clipped = [] + for box in boxes: + x1, y1, x2, y2 = (float(v) for v in box) + x1, x2 = min(max(x1, 0.0), width), min(max(x2, 0.0), width) + y1, y2 = min(max(y1, 0.0), height), min(max(y2, 0.0), height) + clipped.append([round(x1, 2), round(y1, 2), round(x2, 2), round(y2, 2)]) + result = { + "model_name": model_name, + "boxes": clipped, + "labels": [str(label) for label in labels], + "scores": [round(float(s), 4) for s in scores], + "inference_time": float(inference_time), # seconds; model forward + post-processing + "image_width": width, + "image_height": height, + "num_detections": len(clipped), + } + result.update(extra) + return result diff --git a/models/grounding_dino.py b/models/grounding_dino.py new file mode 100644 index 0000000..9d24236 --- /dev/null +++ b/models/grounding_dino.py @@ -0,0 +1,127 @@ +"""Grounding DINO (Hugging Face Transformers) wrapper.""" +from __future__ import annotations + +import inspect +import time + +import numpy as np +from PIL import Image + +from detection.prompt_manager import match_label_to_prompt, prepare_for_grounding_dino +from models import DetectionError, ModelLoadError, build_result +from utils.config_loader import load_config, resolve_path +from utils.device import cuda_sync, is_cuda_oom, resolve_device +from utils.logger import get_logger + +logger = get_logger("grounding_dino") + + +class GroundingDINODetector: + """IDEA-Research/grounding-dino-tiny via AutoModelForZeroShotObjectDetection.""" + + name = "Grounding DINO" + + def __init__(self, checkpoint: str | None = None, cache_dir: str | None = None): + cfg = load_config()["models"]["grounding_dino"] + self.checkpoint = checkpoint or cfg["checkpoint"] + self.cache_dir = resolve_path(cache_dir or cfg["cache_dir"]) + self.processor = None + self.model = None + self.device: str | None = None + + @property + def is_loaded(self) -> bool: + return self.model is not None + + def load(self, device: str = "auto") -> None: + """Load (once) and place the model on the requested device.""" + device = resolve_device(device) + if self.is_loaded: + if device != self.device: + self.model.to(device) + self.device = device + return + try: + from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor + + self.cache_dir.mkdir(parents=True, exist_ok=True) + logger.info("Loading %s on %s (first run downloads the weights)...", self.checkpoint, device) + processor = AutoProcessor.from_pretrained(self.checkpoint, cache_dir=str(self.cache_dir)) + model = AutoModelForZeroShotObjectDetection.from_pretrained( + self.checkpoint, cache_dir=str(self.cache_dir)) + self.processor = processor + self.model = model.to(device).eval() + self.device = device + except Exception as exc: # noqa: BLE001 - convert every failure to a readable message + self.model = self.processor = None + hint = "Check your internet connection (needed for the first download) and that 'transformers' is installed." + if is_cuda_oom(exc): + hint = "GPU ran out of memory while loading; try the CPU device." + raise ModelLoadError(f"Could not load Grounding DINO '{self.checkpoint}': {exc}. {hint}") from exc + + def _post_process(self, outputs, input_ids, conf: float, text_threshold: float, size: tuple[int, int]): + """Call post_process_grounded_object_detection with whichever argument names this version has.""" + fn = self.processor.post_process_grounded_object_detection + params = inspect.signature(fn).parameters + kwargs: dict = {"target_sizes": [size]} + if "threshold" in params: + kwargs["threshold"] = conf + elif "box_threshold" in params: + kwargs["box_threshold"] = conf + else: + raise DetectionError("Unsupported transformers version: no box threshold argument found.") + if "text_threshold" in params: + kwargs["text_threshold"] = text_threshold + return fn(outputs, input_ids, **kwargs) + + def detect(self, image_rgb: np.ndarray, prompts: list[str], conf: float = 0.35, + text_threshold: float = 0.25, **_ignored) -> dict: + """Run open-vocabulary detection. conf = box threshold. Boxes are in image_rgb coordinates.""" + if not self.is_loaded: + self.load("auto") + if image_rgb.ndim != 3 or image_rgb.shape[2] != 3: + raise DetectionError("Expected an RGB image of shape (H, W, 3).") + import torch + + height, width = image_rgb.shape[:2] + text = prepare_for_grounding_dino(prompts) + try: + t_pre = time.perf_counter() + inputs = self.processor(images=Image.fromarray(image_rgb), text=text, return_tensors="pt") + inputs = inputs.to(self.device) + preprocess_time = time.perf_counter() - t_pre + + cuda_sync(self.device) + t0 = time.perf_counter() + with torch.inference_mode(): + outputs = self.model(**inputs) + results = self._post_process(outputs, inputs["input_ids"], conf, text_threshold, (height, width)) + cuda_sync(self.device) + inference_time = time.perf_counter() - t0 + except RuntimeError as exc: + if is_cuda_oom(exc): + torch.cuda.empty_cache() + raise DetectionError("GPU out of memory. Use a smaller image resolution or the CPU device.") from exc + raise DetectionError(f"Grounding DINO inference failed: {exc}") from exc + + res = results[0] + label_key = "text_labels" if "text_labels" in res else "labels" + boxes = res["boxes"].detach().cpu().numpy() + scores = res["scores"].detach().cpu().numpy() + + kept_boxes, kept_labels, kept_scores = [], [], [] + for box, score, raw in zip(boxes, scores, res[label_key]): + if not isinstance(raw, str) and hasattr(raw, "item") or isinstance(raw, (int, np.integer)): + idx = int(raw) + text_label = prompts[idx] if 0 <= idx < len(prompts) else "" + else: + text_label = str(raw) + text_label = text_label.strip() + if not text_label: + continue # no prompt tokens matched above the text threshold + kept_boxes.append(box) + kept_labels.append(match_label_to_prompt(text_label, prompts)) + kept_scores.append(score) + + return build_result(self.name, kept_boxes, kept_labels, kept_scores, inference_time, + (height, width), preprocess_time=preprocess_time, device=self.device) diff --git a/models/model_manager.py b/models/model_manager.py new file mode 100644 index 0000000..a3e8b03 --- /dev/null +++ b/models/model_manager.py @@ -0,0 +1,91 @@ +"""Common entry point that selects and runs a detector by name.""" +from __future__ import annotations + +import re +import threading + +import numpy as np + +from models.grounding_dino import GroundingDINODetector +from models.yolo_world import YOLOWorldDetector +from utils.config_loader import load_config +from utils.device import resolve_device +from utils.logger import get_logger + +logger = get_logger("model_manager") + +MODEL_REGISTRY = { + "Grounding DINO": GroundingDINODetector, + "YOLO-World": YOLOWorldDetector, +} +MODEL_NAMES = list(MODEL_REGISTRY) + + +def normalize_model_name(name: str) -> str: + """Accept 'grounding-dino', 'yolo_world', ... and return the canonical display name.""" + key = re.sub(r"[^a-z0-9]", "", name.lower()) + for canonical in MODEL_REGISTRY: + if re.sub(r"[^a-z0-9]", "", canonical.lower()) == key: + return canonical + raise ValueError(f"Unknown model '{name}'. Choose from: {', '.join(MODEL_NAMES)}") + + +def model_slug(name: str) -> str: + return re.sub(r"[^a-z0-9]+", "_", normalize_model_name(name).lower()).strip("_") + + +class ModelManager: + """Loads detectors lazily, keeps them in memory and exposes one detect() call.""" + + def __init__(self): + self._cfg = load_config() + self._detectors: dict = {} + self._lock = threading.RLock() + + @staticmethod + def available_models() -> list[str]: + return list(MODEL_NAMES) + + def default_conf(self, model_name: str) -> float: + det = self._cfg["detection"] + return det["dino_box_threshold"] if model_name == "Grounding DINO" else det["yolo_conf"] + + def get_detector(self, model_name: str, device: str = "auto"): + model_name = normalize_model_name(model_name) + device = resolve_device(device) + with self._lock: + detector = self._detectors.get(model_name) + fresh = detector is None + if fresh: + detector = MODEL_REGISTRY[model_name]() + detector.load(device) # raises ModelLoadError on failure + self._detectors[model_name] = detector + if fresh: + self._warmup(detector) + return detector + + @staticmethod + def _warmup(detector) -> None: + """One untimed pass so CUDA kernels / lazy init do not pollute the first real timing.""" + try: + detector.detect(np.full((480, 640, 3), 127, dtype=np.uint8), ["object"]) + except Exception as exc: # noqa: BLE001 + logger.warning("Warm-up pass failed (ignored): %s", exc) + + def detect(self, model_name: str, image_rgb: np.ndarray, prompts: list[str], device: str = "auto", + conf: float | None = None, text_threshold: float | None = None, + imgsz: int | None = None) -> dict: + """Run the selected model. Returns the common result dict (boxes in image_rgb coordinates).""" + model_name = normalize_model_name(model_name) + detector = self.get_detector(model_name, device) + conf = self.default_conf(model_name) if conf is None else conf + if text_threshold is None: + text_threshold = self._cfg["detection"]["dino_text_threshold"] + with self._lock: + return detector.detect(image_rgb, prompts, conf=conf, text_threshold=text_threshold, imgsz=imgsz) + + def warmup(self, model_name: str, image_rgb: np.ndarray, prompts: list[str], device: str = "auto", + runs: int = 3, **kwargs) -> None: + """Run untimed inferences on real data (used before benchmarking).""" + for _ in range(max(0, runs)): + self.detect(model_name, image_rgb, prompts, device=device, **kwargs) diff --git a/models/yolo_world.py b/models/yolo_world.py new file mode 100644 index 0000000..b1b1e58 --- /dev/null +++ b/models/yolo_world.py @@ -0,0 +1,135 @@ +"""YOLO-World (Ultralytics) wrapper.""" +from __future__ import annotations + +import time +from pathlib import Path + +import cv2 +import numpy as np + +from detection.prompt_manager import prepare_for_yolo_world +from models import DetectionError, ModelLoadError, build_result +from utils.config_loader import load_config, resolve_path +from utils.device import cuda_sync, is_cuda_oom, resolve_device +from utils.logger import get_logger + +logger = get_logger("yolo_world") + + +class YOLOWorldDetector: + """yolov8s-worldv2.pt through the Ultralytics YOLOWorld API.""" + + name = "YOLO-World" + + def __init__(self, checkpoint: str | None = None, weights_dir: str | None = None): + cfg = load_config()["models"]["yolo_world"] + self.checkpoint = checkpoint or cfg["checkpoint"] + self.weights_dir = resolve_path(weights_dir or cfg["weights_dir"]) + self.model = None + self.device: str | None = None + self.current_classes: tuple[str, ...] = () + + @property + def is_loaded(self) -> bool: + return self.model is not None + + def _ensure_weights(self) -> str: + """Return a path/name for the checkpoint, downloading into weights/yolo_world when possible.""" + target = self.weights_dir / self.checkpoint + self.weights_dir.mkdir(parents=True, exist_ok=True) + if target.exists(): + return str(target) + try: + from ultralytics.utils.downloads import attempt_download_asset + + attempt_download_asset(str(target)) + except Exception as exc: # noqa: BLE001 + logger.warning("Direct download into %s failed (%s); letting Ultralytics download it.", target, exc) + return str(target) if target.exists() else self.checkpoint + + def load(self, device: str = "auto") -> None: + device = resolve_device(device) + if self.is_loaded: + if device != self.device: + self.model.to(device) + self.device = device + return + try: + from ultralytics import YOLOWorld + + weights = self._ensure_weights() + logger.info("Loading YOLO-World weights '%s' on %s...", weights, device) + model = YOLOWorld(weights) + model.to(device) + self.model = model + self.device = device + self.current_classes = () + except Exception as exc: # noqa: BLE001 + self.model = None + hint = "Check your internet connection (needed to download the weights) and that 'ultralytics' is installed." + if is_cuda_oom(exc): + hint = "GPU ran out of memory while loading; try the CPU device." + raise ModelLoadError(f"Could not load YOLO-World '{self.checkpoint}': {exc}. {hint}") from exc + + def _apply_classes(self, classes: list[str]) -> None: + """Call set_classes() when the vocabulary changed, then verify it was applied.""" + wanted = tuple(classes) + if wanted == self.current_classes: + return + try: + self.model.set_classes(list(wanted)) + except Exception as exc: # noqa: BLE001 + raise DetectionError( + f"set_classes() failed: {exc}. If the error mentions 'clip', run: " + "pip install git+https://github.com/ultralytics/CLIP.git") from exc + names = getattr(self.model.model, "names", None) + applied = list(names.values()) if isinstance(names, dict) else list(names or []) + if applied != list(wanted): + raise DetectionError(f"Custom classes were not applied (model has {applied}, expected {list(wanted)}).") + self.current_classes = wanted + logger.info("YOLO-World vocabulary set: %s", list(wanted)) + + def detect(self, image_rgb: np.ndarray, prompts: list[str], conf: float = 0.25, + imgsz: int | None = None, **_ignored) -> dict: + """Run detection with the custom vocabulary. Boxes are in image_rgb coordinates.""" + if not self.is_loaded: + self.load("auto") + if image_rgb.ndim != 3 or image_rgb.shape[2] != 3: + raise DetectionError("Expected an RGB image of shape (H, W, 3).") + imgsz = imgsz or load_config()["image"]["yolo_imgsz"] + classes = prepare_for_yolo_world(prompts) + self._apply_classes(classes) + + height, width = image_rgb.shape[:2] + bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) # Ultralytics treats numpy input as BGR + try: + cuda_sync(self.device) + t0 = time.perf_counter() + results = self.model.predict(source=bgr, conf=float(conf), imgsz=int(imgsz), + device=0 if self.device == "cuda" else "cpu", verbose=False) + cuda_sync(self.device) + wall = time.perf_counter() - t0 + except RuntimeError as exc: + if is_cuda_oom(exc): + import torch + + torch.cuda.empty_cache() + raise DetectionError("GPU out of memory. Use a smaller image size or the CPU device.") from exc + raise DetectionError(f"YOLO-World inference failed: {exc}") from exc + + r = results[0] + speed = getattr(r, "speed", None) or {} + # Ultralytics times preprocess / inference / postprocess (ms); report model inference + NMS. + if "inference" in speed: + inference_time = (speed["inference"] + speed.get("postprocess", 0.0)) / 1000.0 + preprocess_time = speed.get("preprocess", 0.0) / 1000.0 + else: + inference_time, preprocess_time = wall, 0.0 + + boxes = r.boxes.xyxy.cpu().numpy() if len(r.boxes) else np.zeros((0, 4)) + scores = r.boxes.conf.cpu().numpy() if len(r.boxes) else np.zeros((0,)) + cls_ids = r.boxes.cls.cpu().numpy().astype(int) if len(r.boxes) else np.zeros((0,), dtype=int) + labels = [classes[i] if 0 <= i < len(classes) else str(i) for i in cls_ids] + + return build_result(self.name, boxes, labels, scores, inference_time, (height, width), + preprocess_time=preprocess_time, wall_time=wall, device=self.device) diff --git a/outputs/images/.gitkeep b/outputs/images/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/outputs/reports/.gitkeep b/outputs/reports/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/outputs/videos/.gitkeep b/outputs/videos/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d7b7c58 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,17 @@ +# Compatible-range pins (not blind "latest"). Install PyTorch FIRST for your CUDA version +# (see README step 4), then: pip install -r requirements.txt +# After a working install, lock exact versions with: pip freeze > requirements.lock.txt +torch>=2.1,<3 +torchvision>=0.16,<1 +transformers>=4.45,<6 # Grounding DINO; code adapts to threshold/box_threshold API naming +ultralytics>=8.3,<9 # YOLO-World (YOLOWorld, set_classes, yolov8s-worldv2) +opencv-python>=4.8,<6 +numpy>=1.24,<3 +Pillow>=10.0,<13 +pandas>=2.0,<4 +matplotlib>=3.7,<4 +psutil>=5.9,<8 +streamlit>=1.35,<2 +PyYAML>=6.0,<7 +nvidia-ml-py>=12.0 # GPU utilisation (optional on CPU-only machines) +pytest>=7.4,<10 diff --git a/run_app.bat b/run_app.bat new file mode 100644 index 0000000..cab6f77 --- /dev/null +++ b/run_app.bat @@ -0,0 +1,12 @@ +@echo off +setlocal +cd /d "%~dp0" + +if not exist ".venv\Scripts\python.exe" ( + echo Project virtual environment not found: .venv + echo Create it with: python -m venv .venv + exit /b 1 +) + +".venv\Scripts\python.exe" -m streamlit run app.py %* +exit /b %errorlevel% diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..85ade72 --- /dev/null +++ b/tests/helpers.py @@ -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() diff --git a/tests/test_grounding_dino.py b/tests/test_grounding_dino.py new file mode 100644 index 0000000..f3c4e75 --- /dev/null +++ b/tests/test_grounding_dino.py @@ -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") diff --git a/tests/test_image_detection.py b/tests/test_image_detection.py new file mode 100644 index 0000000..cc866c3 --- /dev/null +++ b/tests/test_image_detection.py @@ -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() diff --git a/tests/test_metrics.py b/tests/test_metrics.py new file mode 100644 index 0000000..39bd24c --- /dev/null +++ b/tests/test_metrics.py @@ -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] diff --git a/tests/test_pdf_report.py b/tests/test_pdf_report.py new file mode 100644 index 0000000..79bdf66 --- /dev/null +++ b/tests/test_pdf_report.py @@ -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", + } diff --git a/tests/test_pipeline_logic.py b/tests/test_pipeline_logic.py new file mode 100644 index 0000000..f1a214d --- /dev/null +++ b/tests/test_pipeline_logic.py @@ -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"] diff --git a/tests/test_prompt_manager.py b/tests/test_prompt_manager.py new file mode 100644 index 0000000..b1c5797 --- /dev/null +++ b/tests/test_prompt_manager.py @@ -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" diff --git a/tests/test_video_detection.py b/tests/test_video_detection.py new file mode 100644 index 0000000..4f71c4b --- /dev/null +++ b/tests/test_video_detection.py @@ -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 diff --git a/tests/test_yolo_world.py b/tests/test_yolo_world.py new file mode 100644 index 0000000..88e9657 --- /dev/null +++ b/tests/test_yolo_world.py @@ -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") diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..3396fa9 --- /dev/null +++ b/utils/__init__.py @@ -0,0 +1 @@ +"""Shared utilities (config, device, logging, image/video helpers).""" diff --git a/utils/config_loader.py b/utils/config_loader.py new file mode 100644 index 0000000..0ab093d --- /dev/null +++ b/utils/config_loader.py @@ -0,0 +1,51 @@ +"""Centralised YAML configuration loading and project paths.""" +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path +from typing import Any + +import yaml + +PROJECT_ROOT = Path(__file__).resolve().parent.parent +CONFIG_DIR = PROJECT_ROOT / "config" +_CONFIG_FILES = ("config.yaml", "model_config.yaml") + + +def _deep_update(base: dict, new: dict) -> dict: + for key, value in new.items(): + if isinstance(value, dict) and isinstance(base.get(key), dict): + _deep_update(base[key], value) + else: + base[key] = value + return base + + +@lru_cache(maxsize=1) +def load_config() -> dict[str, Any]: + """Load and merge all YAML config files. The result is cached; do not mutate it.""" + cfg: dict[str, Any] = {} + for name in _CONFIG_FILES: + path = CONFIG_DIR / name + if not path.exists(): + raise FileNotFoundError(f"Missing configuration file: {path}") + with path.open("r", encoding="utf-8") as fh: + _deep_update(cfg, yaml.safe_load(fh) or {}) + return cfg + + +def resolve_path(path: str | Path) -> Path: + """Resolve a config path relative to the project root (absolute paths pass through).""" + p = Path(path) + return p if p.is_absolute() else PROJECT_ROOT / p + + +def ensure_project_dirs() -> None: + """Create every directory the application writes to.""" + cfg = load_config() + for rel in cfg["paths"].values(): + resolve_path(rel).mkdir(parents=True, exist_ok=True) + for model_cfg in cfg["models"].values(): + for key in ("cache_dir", "weights_dir"): + if key in model_cfg: + resolve_path(model_cfg[key]).mkdir(parents=True, exist_ok=True) diff --git a/utils/device.py b/utils/device.py new file mode 100644 index 0000000..cf9861a --- /dev/null +++ b/utils/device.py @@ -0,0 +1,50 @@ +"""Device selection and CUDA helpers.""" +from __future__ import annotations + +from utils.logger import get_logger + +logger = get_logger("device") + + +def resolve_device(requested: str | None = "auto") -> str: + """Map a user choice (auto/cuda/gpu/cpu) to 'cuda' or 'cpu', falling back to CPU.""" + import torch + + requested = (requested or "auto").strip().lower() + if requested in ("auto", "cuda", "gpu") or requested.startswith("cuda"): + if torch.cuda.is_available(): + return "cuda" + if requested != "auto": + logger.warning("CUDA requested but not available - falling back to CPU.") + return "cpu" + if requested != "cpu": + logger.warning("Unknown device '%s' - using CPU.", requested) + return "cpu" + + +def cuda_sync(device: str) -> None: + """Synchronise CUDA so wall-clock timings include queued GPU work.""" + import torch + + if device.startswith("cuda") and torch.cuda.is_available(): + torch.cuda.synchronize() + + +def is_cuda_oom(exc: BaseException) -> bool: + """True if an exception looks like a CUDA out-of-memory error.""" + return "out of memory" in str(exc).lower() + + +def device_info() -> dict: + """Return basic information about the available compute device.""" + import torch + + info = {"cuda_available": torch.cuda.is_available(), "torch": torch.__version__} + if torch.cuda.is_available(): + props = torch.cuda.get_device_properties(0) + info.update( + gpu_name=props.name, + gpu_total_mb=round(props.total_memory / 1024**2, 1), + cuda_version=torch.version.cuda, + ) + return info diff --git a/utils/image_utils.py b/utils/image_utils.py new file mode 100644 index 0000000..f9bdb4e --- /dev/null +++ b/utils/image_utils.py @@ -0,0 +1,53 @@ +"""Image loading and resizing helpers.""" +from __future__ import annotations + +from pathlib import Path + +import cv2 +import numpy as np + + +class ImageLoadError(ValueError): + """Raised when an image cannot be read or decoded.""" + + +def validate_extension(filename: str, allowed: list[str] | tuple[str, ...]) -> None: + ext = Path(filename).suffix.lower() + if ext not in allowed: + raise ImageLoadError(f"Unsupported file type '{ext}'. Allowed: {', '.join(allowed)}") + + +def load_image_rgb(source) -> np.ndarray: + """Load an image from a path, bytes, or file-like object as an RGB uint8 array.""" + try: + if isinstance(source, (str, Path)): + data = np.fromfile(str(source), dtype=np.uint8) # unicode-safe on Windows + elif isinstance(source, (bytes, bytearray)): + data = np.frombuffer(source, dtype=np.uint8) + elif hasattr(source, "getvalue"): + data = np.frombuffer(source.getvalue(), dtype=np.uint8) + elif hasattr(source, "read"): + data = np.frombuffer(source.read(), dtype=np.uint8) + else: + raise ImageLoadError(f"Unsupported image source type: {type(source).__name__}") + except OSError as exc: + raise ImageLoadError(f"Could not read image file: {exc}") from exc + if data.size == 0: + raise ImageLoadError("The image file is empty.") + bgr = cv2.imdecode(data, cv2.IMREAD_COLOR) + if bgr is None: + raise ImageLoadError("Could not decode the image - the file is corrupt or not a supported image.") + return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + + +def resize_long_side(image: np.ndarray, max_side: int | None) -> tuple[np.ndarray, float]: + """Downscale so the long side is at most max_side. Returns (image, scale). 0/None disables.""" + if not max_side or max_side <= 0: + return image, 1.0 + h, w = image.shape[:2] + longest = max(h, w) + if longest <= max_side: + return image, 1.0 + scale = max_side / float(longest) + new_size = (max(1, int(round(w * scale))), max(1, int(round(h * scale)))) + return cv2.resize(image, new_size, interpolation=cv2.INTER_AREA), scale diff --git a/utils/logger.py b/utils/logger.py new file mode 100644 index 0000000..877c2bf --- /dev/null +++ b/utils/logger.py @@ -0,0 +1,32 @@ +"""Logging setup: console + logs/app.log.""" +from __future__ import annotations + +import logging +import sys + +_CONFIGURED = False + + +def get_logger(name: str = "ovd") -> logging.Logger: + """Return a child of the shared 'ovd' logger, configuring handlers once.""" + global _CONFIGURED + if not _CONFIGURED: + root = logging.getLogger("ovd") + root.setLevel(logging.INFO) + root.propagate = False + fmt = logging.Formatter("%(asctime)s | %(levelname)s | %(name)s | %(message)s") + console = logging.StreamHandler(sys.stdout) + console.setFormatter(fmt) + root.addHandler(console) + try: + from utils.config_loader import PROJECT_ROOT + + log_dir = PROJECT_ROOT / "logs" + log_dir.mkdir(exist_ok=True) + file_handler = logging.FileHandler(log_dir / "app.log", encoding="utf-8") + file_handler.setFormatter(fmt) + root.addHandler(file_handler) + except OSError: + pass # read-only filesystem: console logging only + _CONFIGURED = True + return logging.getLogger(name if name.startswith("ovd") else f"ovd.{name}") diff --git a/utils/video_utils.py b/utils/video_utils.py new file mode 100644 index 0000000..65129ab --- /dev/null +++ b/utils/video_utils.py @@ -0,0 +1,66 @@ +"""Video I/O helpers built on OpenCV.""" +from __future__ import annotations + +import math +import shutil +import subprocess +from pathlib import Path + +import cv2 + +from utils.logger import get_logger + +logger = get_logger("video_utils") + + +class VideoError(RuntimeError): + """Raised for unreadable videos or writer/codec failures.""" + + +def get_video_info(path: str | Path) -> dict: + """Return fps, frame count, size and duration of a video file.""" + cap = cv2.VideoCapture(str(path)) + try: + if not cap.isOpened(): + raise VideoError(f"Cannot open video '{Path(path).name}'. The format or codec may be unsupported.") + fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) + frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0) + finally: + cap.release() + if not math.isfinite(fps) or fps <= 0: + fps = 25.0 + logger.warning("Video reports no FPS; assuming 25.") + duration = frames / fps if frames > 0 else 0.0 + return {"fps": fps, "total_frames": frames, "width": width, "height": height, "duration_s": duration} + + +def create_video_writer(path: str | Path, fps: float, size: tuple[int, int], codecs: list[str]): + """Open a VideoWriter trying each codec in order. Returns (writer, codec_used).""" + Path(path).parent.mkdir(parents=True, exist_ok=True) + for codec in codecs: + writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*codec), fps, size) + if writer.isOpened(): + return writer, codec + writer.release() + logger.warning("Video codec '%s' unavailable; trying next.", codec) + raise VideoError(f"Could not create a video writer with any of the codecs {codecs}.") + + +def reencode_h264(src: str | Path, dst: str | Path) -> bool: + """Re-encode to browser-playable H.264 with ffmpeg, if installed. Returns success.""" + ffmpeg = shutil.which("ffmpeg") + if not ffmpeg: + return False + cmd = [ffmpeg, "-y", "-loglevel", "error", "-i", str(src), "-c:v", "libx264", + "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(dst)] + try: + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=1800) + except (OSError, subprocess.TimeoutExpired) as exc: + logger.warning("ffmpeg re-encode failed: %s", exc) + return False + if proc.returncode != 0: + logger.warning("ffmpeg re-encode failed: %s", proc.stderr.strip()[:300]) + return False + return Path(dst).exists() and Path(dst).stat().st_size > 0 diff --git a/weights/grounding_dino/.gitkeep b/weights/grounding_dino/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/weights/yolo_world/.gitkeep b/weights/yolo_world/.gitkeep new file mode 100644 index 0000000..e69de29