initial commit
This commit is contained in:
@@ -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
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user