trackflow-python-tensorrt 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trackflow/detector.py ADDED
@@ -0,0 +1,850 @@
1
+ """Detector adapters for ONNX Runtime and optional Hugging Face Transformers models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import ctypes
7
+ import functools
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import platform
12
+ import shutil
13
+ import site
14
+ import subprocess
15
+ import sys
16
+ from collections.abc import Sequence
17
+ from pathlib import Path
18
+ from typing import Any, Protocol
19
+
20
+ import cv2
21
+ import numpy as np
22
+ import onnxruntime as ort
23
+
24
+ from trackflow.models import MODEL_REGISTRY, Precision, resolve_detector_artifacts
25
+ from trackflow.types import Detection
26
+
27
+ DEFAULT_COCO_LABELS: dict[int, str] = {
28
+ 0: "person",
29
+ 1: "bicycle",
30
+ 2: "car",
31
+ 3: "motorbike",
32
+ 4: "aeroplane",
33
+ 5: "bus",
34
+ 6: "train",
35
+ 7: "truck",
36
+ 8: "boat",
37
+ 9: "traffic light",
38
+ 10: "fire hydrant",
39
+ 11: "stop sign",
40
+ 12: "parking meter",
41
+ 13: "bench",
42
+ 14: "bird",
43
+ 15: "cat",
44
+ 16: "dog",
45
+ 17: "horse",
46
+ 18: "sheep",
47
+ 19: "cow",
48
+ 20: "elephant",
49
+ 21: "bear",
50
+ 22: "zebra",
51
+ 23: "giraffe",
52
+ 24: "backpack",
53
+ 25: "umbrella",
54
+ 26: "handbag",
55
+ 27: "tie",
56
+ 28: "suitcase",
57
+ 29: "frisbee",
58
+ 30: "skis",
59
+ 31: "snowboard",
60
+ 32: "sports ball",
61
+ 33: "kite",
62
+ 34: "baseball bat",
63
+ 35: "baseball glove",
64
+ 36: "skateboard",
65
+ 37: "surfboard",
66
+ 38: "tennis racket",
67
+ 39: "bottle",
68
+ 40: "wine glass",
69
+ 41: "cup",
70
+ 42: "fork",
71
+ 43: "knife",
72
+ 44: "spoon",
73
+ 45: "bowl",
74
+ 46: "banana",
75
+ 47: "apple",
76
+ 48: "sandwich",
77
+ 49: "orange",
78
+ 50: "broccoli",
79
+ 51: "carrot",
80
+ 52: "hot dog",
81
+ 53: "pizza",
82
+ 54: "donut",
83
+ 55: "cake",
84
+ 56: "chair",
85
+ 57: "sofa",
86
+ 58: "pottedplant",
87
+ 59: "bed",
88
+ 60: "diningtable",
89
+ 61: "toilet",
90
+ 62: "tvmonitor",
91
+ 63: "laptop",
92
+ 64: "mouse",
93
+ 65: "remote",
94
+ 66: "keyboard",
95
+ 67: "cell phone",
96
+ 68: "microwave",
97
+ 69: "oven",
98
+ 70: "toaster",
99
+ 71: "sink",
100
+ 72: "refrigerator",
101
+ 73: "book",
102
+ 74: "clock",
103
+ 75: "vase",
104
+ 76: "scissors",
105
+ 77: "teddy bear",
106
+ 78: "hair drier",
107
+ 79: "toothbrush",
108
+ }
109
+
110
+
111
+ class Detector(Protocol):
112
+ """A detector accepts one BGR uint8 frame and returns pixel-space xyxy boxes."""
113
+
114
+ def detect(self, frame_bgr: np.ndarray) -> list[Detection]: ...
115
+
116
+
117
+ _COCO_ALIASES = {
118
+ "motorbike": "motorcycle",
119
+ "aeroplane": "airplane",
120
+ "sofa": "couch",
121
+ "pottedplant": "potted plant",
122
+ "diningtable": "dining table",
123
+ "tvmonitor": "tv",
124
+ }
125
+
126
+
127
+ def _class_key(name: str) -> str:
128
+ name = name.strip().lower()
129
+ return _COCO_ALIASES.get(name, name)
130
+
131
+
132
+ def _allowed_classes(classes: Sequence[str] | None) -> set[str] | None:
133
+ if isinstance(classes, str):
134
+ classes = classes.split(",")
135
+ names = {_class_key(c) for c in classes or () if c.strip()}
136
+ if not names or names.intersection({"*", "all"}):
137
+ return None
138
+ return names
139
+
140
+
141
+ _CUDA_INSTALL_HINT = (
142
+ "Run with NVIDIA CUDA support: `uvx trackflow-python-cuda run <video>` "
143
+ "(or `pip install trackflow-python-cuda` in a clean environment without CPU `onnxruntime`)."
144
+ )
145
+ _TRT_INSTALL_HINT = (
146
+ "Run with NVIDIA TensorRT support (Python 3.11+): `uvx trackflow-python-tensorrt run <video>` "
147
+ "(or `pip install trackflow-python-tensorrt` in a clean environment without CPU `onnxruntime`)."
148
+ )
149
+
150
+
151
+ def detect_nvidia_gpu() -> str | None:
152
+ """Return ``'<name>, <driver>'`` from ``nvidia-smi`` when an NVIDIA GPU is present."""
153
+ if shutil.which("nvidia-smi") is None:
154
+ return None
155
+ try:
156
+ res = subprocess.run(
157
+ ["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"],
158
+ capture_output=True,
159
+ text=True,
160
+ timeout=1.5,
161
+ check=False,
162
+ )
163
+ except Exception:
164
+ return None
165
+ if res.returncode != 0:
166
+ return None
167
+ first = next((line.strip() for line in res.stdout.splitlines() if line.strip()), None)
168
+ return first or None
169
+
170
+
171
+ @functools.lru_cache(maxsize=1)
172
+ def preload_gpu_libraries() -> tuple[str, ...]:
173
+ """Preload pip-bundled CUDA, cuDNN, and TensorRT libraries so LD_LIBRARY_PATH is unneeded."""
174
+ available = ort.get_available_providers()
175
+ if (
176
+ "CUDAExecutionProvider" not in available
177
+ and "TensorrtExecutionProvider" not in available
178
+ ):
179
+ return ()
180
+ if hasattr(ort, "preload_dlls"):
181
+ with contextlib.suppress(Exception):
182
+ ort.preload_dlls(cuda=True, cudnn=True, msvc=(os.name == "nt"))
183
+
184
+ loaded: list[str] = []
185
+ seen_dirs: set[Path] = set()
186
+ search_roots: list[str] = []
187
+ with contextlib.suppress(Exception):
188
+ search_roots.extend(site.getsitepackages())
189
+ with contextlib.suppress(Exception):
190
+ user_site = site.getusersitepackages()
191
+ if user_site:
192
+ search_roots.append(user_site)
193
+
194
+ for root in search_roots:
195
+ root_path = Path(root)
196
+ if not root_path.is_dir():
197
+ continue
198
+ for lib_dir in sorted(root_path.glob("tensorrt*libs")):
199
+ if not lib_dir.is_dir() or lib_dir in seen_dirs:
200
+ continue
201
+ seen_dirs.add(lib_dir)
202
+ if os.name == "nt":
203
+ if hasattr(os, "add_dll_directory"):
204
+ with contextlib.suppress(OSError):
205
+ os.add_dll_directory(str(lib_dir))
206
+ for dll in sorted(lib_dir.glob("nvinfer*.dll")):
207
+ loaded.append(dll.name)
208
+ continue
209
+ # Load core nvinfer before plugin and onnxparser so shared symbols resolve in order.
210
+ for pat in ("libnvinfer.so.*", "libnvinfer_plugin.so.*", "libnvonnxparser.so.*"):
211
+ for so in sorted(lib_dir.glob(pat)):
212
+ if so.is_symlink():
213
+ continue
214
+ with contextlib.suppress(OSError):
215
+ ctypes.CDLL(str(so), mode=ctypes.RTLD_GLOBAL)
216
+ loaded.append(so.name)
217
+ return tuple(loaded)
218
+
219
+
220
+ def _trt_cache_paths(
221
+ onnx_path: Path, *, trt_fp16: bool, cache_dir: str | Path | None = None
222
+ ) -> tuple[Path, Path]:
223
+ """Return ``(engine_dir, timing_cache_dir)`` for persistent TensorRT engine caching."""
224
+ if cache_dir is not None:
225
+ root = Path(cache_dir) / "trt_cache"
226
+ else:
227
+ env_dir = os.environ.get("TRACKFLOW_TRT_CACHE_DIR", "").strip()
228
+ root = Path(env_dir) if env_dir else Path.home() / ".cache" / "trackflow" / "trt_cache"
229
+ resolved = onnx_path.resolve()
230
+ key_parts = [str(resolved), "fp16" if trt_fp16 else "fp32"]
231
+ with contextlib.suppress(OSError):
232
+ st = resolved.stat()
233
+ key_parts.extend([str(st.st_size), str(st.st_mtime_ns)])
234
+ digest = hashlib.sha256("|".join(key_parts).encode("utf-8")).hexdigest()[:12]
235
+ engine_dir = root / f"{onnx_path.stem}_{digest}_{'fp16' if trt_fp16 else 'fp32'}"
236
+ return engine_dir, root
237
+
238
+
239
+ def select_providers(device: str = "auto") -> list[str]:
240
+ """Choose ONNX Runtime execution providers based on requested device."""
241
+ available = ort.get_available_providers()
242
+ req = device.lower().strip()
243
+
244
+ options = {
245
+ "cpu": ["CPUExecutionProvider"],
246
+ "cuda": ["CUDAExecutionProvider", "CPUExecutionProvider"],
247
+ "coreml": ["CoreMLExecutionProvider", "CPUExecutionProvider"],
248
+ "tensorrt": ["TensorrtExecutionProvider", "CUDAExecutionProvider", "CPUExecutionProvider"],
249
+ }
250
+ if req != "auto":
251
+ if req not in options:
252
+ raise ValueError(
253
+ f"Unknown ONNX device {device!r}. Choose auto, cpu, coreml, cuda, or tensorrt."
254
+ )
255
+ if options[req][0] not in available:
256
+ hint = ""
257
+ if req == "cuda":
258
+ hint = f" {_CUDA_INSTALL_HINT}"
259
+ elif req == "tensorrt":
260
+ hint = f" {_TRT_INSTALL_HINT}"
261
+ raise ValueError(
262
+ f"{device} requires {options[req][0]}. Available providers: {available}.{hint}"
263
+ )
264
+ return [p for p in options[req] if p in available]
265
+
266
+ # Auto-selection: prefer NVIDIA CUDA if present, else multi-threaded CPU. On Apple Silicon,
267
+ # CoreML runs part of each DETR graph on the CPU: it frees most CPU cores but is slower for
268
+ # RF-DETR, so it stays opt-in with --device coreml.
269
+ preferred = [
270
+ "CUDAExecutionProvider",
271
+ "CPUExecutionProvider",
272
+ ]
273
+ selected = [p for p in preferred if p in available]
274
+ return selected or ["CPUExecutionProvider"]
275
+
276
+
277
+ def _apple_p_cores() -> int | None:
278
+ """Return Apple Silicon's performance-core count via sysctlbyname, or None elsewhere."""
279
+ if platform.system() != "Darwin":
280
+ return None
281
+ try:
282
+ libc = ctypes.CDLL(None)
283
+ val = ctypes.c_int(0)
284
+ size = ctypes.c_size_t(ctypes.sizeof(val))
285
+ rc = libc.sysctlbyname(
286
+ b"hw.perflevel0.physicalcpu", ctypes.byref(val), ctypes.byref(size), None, 0
287
+ )
288
+ return val.value if rc == 0 and val.value > 0 else None
289
+ except Exception:
290
+ return None
291
+
292
+
293
+ def _default_onnx_threads() -> int:
294
+ """Pick ORT intra-op threads: honor OMP_NUM_THREADS, else pin Apple Silicon to P-cores."""
295
+ env = os.environ.get("OMP_NUM_THREADS", "").strip()
296
+ if env:
297
+ with contextlib.suppress(ValueError):
298
+ if (n := int(env)) > 0:
299
+ return n
300
+ # On Apple Silicon, ORT defaults to hw.physicalcpu (P + E cores), so slow E-cores stall
301
+ # thread barriers. Pinning to P-cores speeds up CPU DETR models by ~17-27%.
302
+ return _apple_p_cores() or 0
303
+
304
+
305
+ def create_onnx_session(
306
+ onnx_path: Path,
307
+ device: str = "auto",
308
+ *,
309
+ optimization: ort.GraphOptimizationLevel = ort.GraphOptimizationLevel.ORT_ENABLE_ALL,
310
+ coreml_format: str | None = "MLProgram",
311
+ trt_fp16: bool = True,
312
+ cache_dir: str | Path | None = None,
313
+ ) -> tuple[ort.InferenceSession, str]:
314
+ """Create an ONNX Runtime session with safe fallback to CPU if an EP fails."""
315
+ providers = select_providers(device)
316
+ if (
317
+ "CUDAExecutionProvider" in providers
318
+ or "TensorrtExecutionProvider" in providers
319
+ ):
320
+ preload_gpu_libraries()
321
+
322
+ provider_options: list[dict[str, Any]] = []
323
+ for p in providers:
324
+ if p == "CoreMLExecutionProvider" and coreml_format is not None:
325
+ # CoreML runs on the GPU, not the Neural Engine, so results match the CPU's fp32.
326
+ # ``coreml_format=None`` keeps ONNX Runtime's default CoreML setup.
327
+ provider_options.append({"ModelFormat": coreml_format, "MLComputeUnits": "CPUAndGPU"})
328
+ elif p == "CUDAExecutionProvider":
329
+ # HEURISTIC cuts cuDNN startup search ~4-5x with identical steady-state throughput.
330
+ provider_options.append({"cudnn_conv_algo_search": "HEURISTIC"})
331
+ elif p == "TensorrtExecutionProvider":
332
+ engine_dir, timing_root = _trt_cache_paths(
333
+ onnx_path, trt_fp16=trt_fp16, cache_dir=cache_dir
334
+ )
335
+ engine_dir.mkdir(parents=True, exist_ok=True)
336
+ if not any(engine_dir.glob("*.engine")):
337
+ precision_label = "FP16" if trt_fp16 else "FP32"
338
+ print(
339
+ f"Building TensorRT {precision_label} engine for {onnx_path.name} "
340
+ f"(first run only; cached in {engine_dir})...",
341
+ file=sys.stderr,
342
+ flush=True,
343
+ )
344
+ provider_options.append(
345
+ {
346
+ "trt_engine_cache_enable": True,
347
+ "trt_engine_cache_path": str(engine_dir),
348
+ "trt_timing_cache_enable": True,
349
+ "trt_timing_cache_path": str(timing_root),
350
+ "trt_fp16_enable": bool(trt_fp16),
351
+ }
352
+ )
353
+ else:
354
+ provider_options.append({})
355
+
356
+ sess_opts = ort.SessionOptions()
357
+ sess_opts.graph_optimization_level = optimization
358
+ sess_opts.intra_op_num_threads = _default_onnx_threads()
359
+ sess_opts.inter_op_num_threads = 1
360
+
361
+ try:
362
+ session = ort.InferenceSession(
363
+ str(onnx_path),
364
+ sess_options=sess_opts,
365
+ providers=providers,
366
+ provider_options=provider_options,
367
+ )
368
+ except Exception:
369
+ if device.strip().lower() != "auto" or providers == ["CPUExecutionProvider"]:
370
+ raise
371
+ session = ort.InferenceSession(
372
+ str(onnx_path),
373
+ sess_options=sess_opts,
374
+ providers=["CPUExecutionProvider"],
375
+ )
376
+
377
+ active = session.get_providers()
378
+ active_name = active[0] if active else "CPUExecutionProvider"
379
+ req = device.strip().lower()
380
+ if req != "auto" and active_name != providers[0]:
381
+ hint = ""
382
+ if providers[0] == "TensorrtExecutionProvider":
383
+ hint = f" {_TRT_INSTALL_HINT}"
384
+ elif providers[0] == "CUDAExecutionProvider":
385
+ hint = f" {_CUDA_INSTALL_HINT}"
386
+ raise RuntimeError(
387
+ f"Could not start {providers[0]}. ONNX Runtime selected {active_name}.{hint}"
388
+ )
389
+ return session, active_name
390
+
391
+
392
+ def sigmoid(x: np.ndarray) -> np.ndarray:
393
+ """Numerically stable sigmoid."""
394
+ x_clip = np.clip(x, -60.0, 60.0)
395
+ return 1.0 / (1.0 + np.exp(-x_clip))
396
+
397
+
398
+ def _nms_class_aware(detections: list[Detection], iou_threshold: float) -> list[Detection]:
399
+ """Deduplicate overlapping same-class DETR queries so duplicate boxes don't spawn ghost tracks."""
400
+ if len(detections) <= 1 or iou_threshold <= 0.0 or iou_threshold >= 1.0:
401
+ return detections
402
+
403
+ kept: list[Detection] = []
404
+ for det in detections:
405
+ x1, y1, x2, y2 = det.bbox
406
+ area_a = max(0.0, x2 - x1) * max(0.0, y2 - y1)
407
+ duplicate = False
408
+ for prev in kept:
409
+ if prev.class_id != det.class_id:
410
+ continue
411
+ px1, py1, px2, py2 = prev.bbox
412
+ iw = max(0.0, min(x2, px2) - max(x1, px1))
413
+ ih = max(0.0, min(y2, py2) - max(y1, py1))
414
+ inter = iw * ih
415
+ if inter <= 0.0:
416
+ continue
417
+ area_b = max(0.0, px2 - px1) * max(0.0, py2 - py1)
418
+ iou = inter / max(area_a + area_b - inter, 1e-6)
419
+ if iou >= iou_threshold:
420
+ duplicate = True
421
+ break
422
+ if not duplicate:
423
+ kept.append(det)
424
+ return kept
425
+
426
+
427
+ def _letterbox(
428
+ frame_bgr: np.ndarray, input_hw: tuple[int, int], pad: int
429
+ ) -> tuple[np.ndarray, tuple[int, int, float, float]]:
430
+ """Resize keeping the aspect ratio, centered on a ``pad``-filled canvas of ``input_hw``.
431
+
432
+ Returns the canvas and ``(left, top, scale_x, scale_y)`` for ``_unletterbox``.
433
+ """
434
+ h, w = input_hw
435
+ orig_h, orig_w = frame_bgr.shape[:2]
436
+ scale = min(w / orig_w, h / orig_h)
437
+ rw, rh = max(1, int(orig_w * scale)), max(1, int(orig_h * scale))
438
+ left, top = (w - rw) // 2, (h - rh) // 2
439
+ canvas = np.full((h, w, 3), pad, dtype=np.uint8)
440
+ canvas[top : top + rh, left : left + rw] = cv2.resize(frame_bgr, (rw, rh))
441
+ return canvas, (left, top, rw / orig_w, rh / orig_h)
442
+
443
+
444
+ def _unletterbox(xyxy: np.ndarray, placement: tuple[int, int, float, float]) -> np.ndarray:
445
+ """Map xyxy boxes on a ``_letterbox`` canvas back to the original frame's pixels."""
446
+ left, top, sx, sy = placement
447
+ return (np.asarray(xyxy, dtype=np.float64) - [left, top, left, top]) / [sx, sy, sx, sy]
448
+
449
+
450
+ def postprocess_detr_outputs(
451
+ logits: np.ndarray,
452
+ pred_boxes: np.ndarray,
453
+ orig_hw: tuple[int, int],
454
+ id2label: dict[int, str],
455
+ threshold: float = 0.45,
456
+ allowed_classes: set[str] | None = None,
457
+ max_detections: int = 300,
458
+ nms_iou: float = 0.65,
459
+ softmax: bool = False,
460
+ ) -> list[Detection]:
461
+ """Convert DETR/RT-DETR/D-FINE/RF-DETR raw logits + normalized cxcywh boxes into Detections."""
462
+ # Squeeze batch dimension [1, N, C] -> [N, C]
463
+ if logits.ndim == 3:
464
+ logits = logits[0]
465
+ if pred_boxes.ndim == 3:
466
+ pred_boxes = pred_boxes[0]
467
+
468
+ if softmax:
469
+ exp = np.exp(logits - logits.max(axis=-1, keepdims=True))
470
+ probs = (exp / exp.sum(axis=-1, keepdims=True))[:, :-1] # trailing no-object class
471
+ else:
472
+ probs = sigmoid(logits)
473
+ class_ids = np.argmax(probs, axis=-1)
474
+ scores = probs[np.arange(probs.shape[0]), class_ids]
475
+
476
+ keep = (scores >= threshold) & np.isfinite(pred_boxes).all(axis=-1)
477
+ if not np.any(keep):
478
+ return []
479
+
480
+ kept_scores = scores[keep]
481
+ kept_classes = class_ids[keep]
482
+ kept_boxes = pred_boxes[keep]
483
+
484
+ # Stable sort so ties keep query order (web/detector.js mirrors this for parity).
485
+ order = np.argsort(-kept_scores, kind="stable")
486
+ orig_h, orig_w = orig_hw
487
+
488
+ detections: list[Detection] = []
489
+ for idx in order:
490
+ cid = int(kept_classes[idx])
491
+ cname = id2label.get(cid, str(cid))
492
+ if (
493
+ allowed_classes is not None
494
+ and cname.lower() not in allowed_classes
495
+ and _class_key(cname) not in allowed_classes
496
+ ):
497
+ continue
498
+
499
+ cx, cy, w, h = kept_boxes[idx].tolist()
500
+ # Handle both normalized [0, 1] and already-pixel coordinates safely.
501
+ if max(cx, cy, w, h) <= 2.0:
502
+ x1 = (cx - 0.5 * w) * orig_w
503
+ y1 = (cy - 0.5 * h) * orig_h
504
+ x2 = (cx + 0.5 * w) * orig_w
505
+ y2 = (cy + 0.5 * h) * orig_h
506
+ else:
507
+ x1, y1, x2, y2 = cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 * h
508
+
509
+ x1 = float(np.clip(x1, 0.0, orig_w))
510
+ y1 = float(np.clip(y1, 0.0, orig_h))
511
+ x2 = float(np.clip(x2, 0.0, orig_w))
512
+ y2 = float(np.clip(y2, 0.0, orig_h))
513
+
514
+ if x2 - x1 < 2.0 or y2 - y1 < 2.0:
515
+ continue
516
+
517
+ detections.append(
518
+ Detection(
519
+ bbox=(x1, y1, x2, y2),
520
+ confidence=float(kept_scores[idx]),
521
+ class_id=cid,
522
+ class_name=cname,
523
+ )
524
+ )
525
+
526
+ return _nms_class_aware(detections, iou_threshold=nms_iou)[:max_detections]
527
+
528
+
529
+ class OnnxDetrDetector:
530
+ """End-to-end transformer object detector powered by ONNX Runtime."""
531
+
532
+ def __init__(
533
+ self,
534
+ model: str = "rtdetr-v2-r18",
535
+ *,
536
+ precision: Precision = "fp32",
537
+ device: str = "auto",
538
+ threshold: float = 0.45,
539
+ classes: Sequence[str] | None = ("person",),
540
+ cache_dir: str | Path | None = None,
541
+ ) -> None:
542
+ self.model_name = model
543
+ self.precision = precision
544
+ spec = MODEL_REGISTRY.get(model)
545
+ self.revision = spec.revision if spec else None
546
+ self.threshold = float(threshold)
547
+ self.allowed_classes = _allowed_classes(classes)
548
+
549
+ onnx_path, config_path, prep_path = resolve_detector_artifacts(
550
+ model=model,
551
+ precision=precision,
552
+ cache_dir=cache_dir,
553
+ )
554
+ self.onnx_path = onnx_path
555
+ self.id2label = self._load_labels(config_path)
556
+ self.input_hw, self.do_rescale, self.do_normalize, self.mean, self.std = (
557
+ self._load_preprocess_config(prep_path)
558
+ )
559
+ if spec and spec.normalize:
560
+ self.do_normalize = True
561
+
562
+ # CoreML EP on int8 quantized DETR graphs can occasionally fail or degrade; prefer CPU for int8.
563
+ effective_device = "cpu" if (device == "auto" and precision == "int8") else device
564
+ cfg = json.loads(config_path.read_text(encoding="utf-8")) if config_path else {}
565
+ optimization = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
566
+ # ORT's extended CPU fusions for this signed INT8 graph abort the process on arm64 macOS.
567
+ if (
568
+ cfg.get("model_type") == "d_fine"
569
+ and (precision == "int8" or "int8" in onnx_path.name)
570
+ and platform.system() == "Darwin"
571
+ and platform.machine() == "arm64"
572
+ ):
573
+ optimization = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
574
+ self.session, self.active_provider = create_onnx_session(
575
+ onnx_path,
576
+ device=effective_device,
577
+ optimization=optimization,
578
+ coreml_format=spec.coreml_format if spec else "MLProgram",
579
+ trt_fp16=spec.trt_fp16 if spec else True,
580
+ cache_dir=cache_dir,
581
+ )
582
+
583
+ self.input_name = self.session.get_inputs()[0].name
584
+ self.output_names = [o.name for o in self.session.get_outputs()]
585
+ inputs = {i.name for i in self.session.get_inputs()}
586
+ self.letterbox = bool(spec and spec.letterbox)
587
+ self.deployed = inputs == {"images", "orig_target_sizes"} and set(self.output_names) == {
588
+ "labels",
589
+ "boxes",
590
+ "scores",
591
+ }
592
+ if self.deployed:
593
+ self.input_name = "images"
594
+ elif len(inputs) == 1 and {"logits", "pred_boxes"}.issubset(self.output_names):
595
+ self.raw_outputs = ["logits", "pred_boxes"]
596
+ elif len(inputs) == 1 and len(self.output_names) == 2:
597
+ # Legacy two-output exports can use other names or reverse the output order.
598
+ first, second = self.session.get_outputs()
599
+ if (
600
+ len(first.shape) != 3
601
+ or len(second.shape) != 3
602
+ or 4 not in (first.shape[-1], second.shape[-1])
603
+ ):
604
+ raise ValueError(
605
+ "Expected class logits and cxcywh boxes with shape (1, queries, 4)."
606
+ )
607
+ self.raw_outputs = (
608
+ [first.name, second.name] if second.shape[-1] == 4 else [second.name, first.name]
609
+ )
610
+ else:
611
+ raise ValueError(
612
+ "Expected an ONNX detector with logits/pred_boxes or images + orig_target_sizes and labels/boxes/scores. For other formats supply detector= to TrackflowPipeline."
613
+ )
614
+ image_input = next(i for i in self.session.get_inputs() if i.name == self.input_name)
615
+ if len(image_input.shape) != 4 or image_input.type not in (
616
+ "tensor(float)",
617
+ "tensor(float16)",
618
+ ):
619
+ raise ValueError("Expected a float32 or float16 NCHW image input.")
620
+ self.input_dtype = np.float16 if image_input.type == "tensor(float16)" else np.float32
621
+ h, w = image_input.shape[-2:]
622
+ if isinstance(h, int) and isinstance(w, int):
623
+ self.input_hw = (h, w)
624
+ # The converted YOLO26 graphs use the YOLOS config type but have no background logit.
625
+ logits_out = next((o for o in self.session.get_outputs() if o.name == "logits"), None)
626
+ self.softmax = cfg.get("model_type") in ("detr", "yolos", "table-transformer") and (
627
+ logits_out is not None and logits_out.shape[-1] == max(self.id2label, default=-1) + 2
628
+ )
629
+
630
+ @staticmethod
631
+ def _load_labels(config_path: Path | None) -> dict[int, str]:
632
+ if config_path is None or not config_path.is_file():
633
+ return dict(DEFAULT_COCO_LABELS)
634
+ raw: dict[str, Any] = json.loads(config_path.read_text(encoding="utf-8"))
635
+ id2label_raw = raw.get("id2label")
636
+ if not isinstance(id2label_raw, dict):
637
+ return dict(DEFAULT_COCO_LABELS)
638
+ return {int(k): str(v) for k, v in id2label_raw.items()}
639
+
640
+ @staticmethod
641
+ def _load_preprocess_config(
642
+ prep_path: Path | None,
643
+ ) -> tuple[tuple[int, int], bool, bool, np.ndarray, np.ndarray]:
644
+ default_mean = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(3, 1, 1)
645
+ default_std = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(3, 1, 1)
646
+ if prep_path is None or not prep_path.is_file():
647
+ return (640, 640), True, False, default_mean, default_std
648
+
649
+ cfg: dict[str, Any] = json.loads(prep_path.read_text(encoding="utf-8"))
650
+ size = cfg.get("size", {})
651
+ if isinstance(size, int):
652
+ size = {"height": size, "width": size}
653
+ h = int(size.get("height", size.get("shortest_edge", 640)))
654
+ w = int(size.get("width", size.get("shortest_edge", 640)))
655
+ do_rescale = bool(cfg.get("do_rescale", True))
656
+ do_normalize = bool(cfg.get("do_normalize", False))
657
+ mean = np.array(cfg.get("image_mean", [0.485, 0.456, 0.406]), dtype=np.float32).reshape(
658
+ 3, 1, 1
659
+ )
660
+ std = np.array(cfg.get("image_std", [0.229, 0.224, 0.225]), dtype=np.float32).reshape(
661
+ 3, 1, 1
662
+ )
663
+ return (h, w), do_rescale, do_normalize, mean, std
664
+
665
+ def preprocess(self, frame_bgr: np.ndarray) -> np.ndarray:
666
+ """Convert OpenCV BGR uint8 frame to NCHW float tensor."""
667
+ target_h, target_w = self.input_hw
668
+ # Resize before BGR->RGB so 1080p/4K frames color-convert 5-20x fewer pixels.
669
+ resized = cv2.resize(frame_bgr, (target_w, target_h), interpolation=cv2.INTER_LINEAR)
670
+ rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
671
+ arr = rgb.astype(np.float32)
672
+ if self.do_rescale:
673
+ arr *= 1.0 / 255.0
674
+ if self.do_normalize:
675
+ arr -= self.mean.reshape(1, 1, 3)
676
+ arr /= self.std.reshape(1, 1, 3)
677
+ chw = np.transpose(arr, (2, 0, 1))
678
+ return np.ascontiguousarray(np.expand_dims(chw, axis=0), dtype=self.input_dtype)
679
+
680
+ def detect(self, frame_bgr: np.ndarray, threshold: float | None = None) -> list[Detection]:
681
+ """Run object detection on a single BGR frame."""
682
+ orig_h, orig_w = frame_bgr.shape[:2]
683
+ cutoff = self.threshold if threshold is None else threshold
684
+ if self.deployed:
685
+ # Upstream DEIMv2 / RT-DETRv4 deployment graphs take a black-letterboxed RGB
686
+ # image and emit xyxy in the coordinate system supplied via orig_target_sizes.
687
+ h, w = self.input_hw
688
+ padded, placement = _letterbox(frame_bgr, self.input_hw, 0)
689
+ labels, boxes, scores = self.session.run(
690
+ ["labels", "boxes", "scores"],
691
+ {
692
+ "images": self.preprocess(padded),
693
+ "orig_target_sizes": np.array([[w, h]], dtype=np.int64),
694
+ },
695
+ )
696
+ return _pixel_detections(
697
+ labels[0],
698
+ _unletterbox(boxes[0], placement),
699
+ scores[0],
700
+ (orig_h, orig_w),
701
+ self.id2label,
702
+ self.allowed_classes,
703
+ cutoff,
704
+ )
705
+ image, placement = frame_bgr, None
706
+ if self.letterbox:
707
+ image, placement = _letterbox(frame_bgr, self.input_hw, 114)
708
+ tensor = self.preprocess(image)
709
+ logits, pred_boxes = self.session.run(self.raw_outputs, {self.input_name: tensor})
710
+
711
+ detections = postprocess_detr_outputs(
712
+ logits=np.asarray(logits, dtype=np.float32),
713
+ pred_boxes=np.asarray(pred_boxes, dtype=np.float32),
714
+ orig_hw=image.shape[:2],
715
+ id2label=self.id2label,
716
+ threshold=cutoff,
717
+ allowed_classes=self.allowed_classes,
718
+ softmax=self.softmax,
719
+ )
720
+ if placement is None:
721
+ return detections
722
+ restored = []
723
+ for det in detections:
724
+ x1, y1, x2, y2 = _unletterbox(det.bbox, placement)
725
+ x1, x2 = np.clip([x1, x2], 0.0, orig_w)
726
+ y1, y2 = np.clip([y1, y2], 0.0, orig_h)
727
+ if x2 - x1 >= 2.0 and y2 - y1 >= 2.0:
728
+ det.bbox = (float(x1), float(y1), float(x2), float(y2))
729
+ restored.append(det)
730
+ return restored
731
+
732
+
733
+ def _pixel_detections(
734
+ labels: np.ndarray,
735
+ boxes: np.ndarray,
736
+ scores: np.ndarray,
737
+ orig_hw: tuple[int, int],
738
+ id2label: dict[int, str],
739
+ allowed: set[str] | None,
740
+ threshold: float,
741
+ ) -> list[Detection]:
742
+ h, w = orig_hw
743
+ detections = []
744
+ for i in np.flatnonzero(scores >= threshold):
745
+ cid = int(labels[i])
746
+ name = id2label.get(cid, str(cid))
747
+ if allowed is not None and _class_key(name) not in allowed:
748
+ continue
749
+ x1, y1, x2, y2 = np.clip(boxes[i], 0, [w, h, w, h]).tolist()
750
+ if x2 - x1 >= 2 and y2 - y1 >= 2:
751
+ detections.append(Detection((x1, y1, x2, y2), float(scores[i]), cid, name))
752
+ detections.sort(key=lambda d: d.confidence, reverse=True)
753
+ return _nms_class_aware(detections, 0.65)
754
+
755
+
756
+ class TransformersDetector:
757
+ """Use a native Transformers object-detection checkpoint and its own image processor."""
758
+
759
+ def __init__(
760
+ self,
761
+ repo_id: str,
762
+ *,
763
+ revision: str | None,
764
+ device: str,
765
+ precision: Precision,
766
+ threshold: float,
767
+ classes: Sequence[str] | None,
768
+ cache_dir: str | Path | None,
769
+ ) -> None:
770
+ try:
771
+ import torch
772
+ from transformers import AutoImageProcessor, AutoModelForObjectDetection
773
+ except ImportError as exc:
774
+ raise ImportError(
775
+ "Install 'trackflow-python[transformers]' to load native Transformers checkpoints."
776
+ ) from exc
777
+ if device == "auto":
778
+ device = "cuda" if torch.cuda.is_available() else "cpu"
779
+ if device not in ("cpu", "cuda", "mps"):
780
+ raise ValueError("Transformers supports --device auto, cpu, cuda, or mps.")
781
+ if precision not in ("fp32", "fp16"):
782
+ raise ValueError("Transformers detectors support fp32 or fp16.")
783
+ self.model_name = repo_id
784
+ self.device = device
785
+ self.precision = precision
786
+ self.dtype = torch.float32 if precision == "fp32" else torch.float16
787
+ kwargs = {"revision": revision, "cache_dir": cache_dir, "trust_remote_code": False}
788
+ self.processor = AutoImageProcessor.from_pretrained(repo_id, **kwargs)
789
+ self.model = (
790
+ AutoModelForObjectDetection.from_pretrained(repo_id, use_safetensors=True, **kwargs)
791
+ .to(device=device, dtype=self.dtype)
792
+ .eval()
793
+ )
794
+ self.revision = revision or getattr(self.model.config, "_commit_hash", None)
795
+ self.active_provider = f"torch:{device}"
796
+ self.threshold = threshold
797
+ self.allowed_classes = _allowed_classes(classes)
798
+
799
+ def detect(self, frame_bgr: np.ndarray) -> list[Detection]:
800
+ import torch
801
+
802
+ hw = frame_bgr.shape[:2]
803
+ rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
804
+ with torch.inference_mode():
805
+ inputs = self.processor(images=rgb, return_tensors="pt").to(self.device, self.dtype)
806
+ output = self.model(**inputs)
807
+ result = self.processor.post_process_object_detection(
808
+ output, threshold=self.threshold, target_sizes=[hw]
809
+ )[0]
810
+ return _pixel_detections(
811
+ result["labels"].cpu().numpy(),
812
+ result["boxes"].float().cpu().numpy(),
813
+ result["scores"].float().cpu().numpy(),
814
+ hw,
815
+ self.model.config.id2label,
816
+ self.allowed_classes,
817
+ self.threshold,
818
+ )
819
+
820
+
821
+ def create_detector(
822
+ model: str | Path = "rtdetr-v2-r18",
823
+ *,
824
+ precision: Precision = "fp32",
825
+ device: str = "auto",
826
+ threshold: float = 0.45,
827
+ classes: Sequence[str] | None = ("person",),
828
+ cache_dir: str | Path | None = None,
829
+ ) -> Detector:
830
+ """Load a preset, compatible ONNX graph/repository, or hf:owner/repo Transformers checkpoint."""
831
+ model = str(model)
832
+ spec = MODEL_REGISTRY.get(model)
833
+ if model.startswith("hf:") or (spec and spec.backend == "transformers"):
834
+ return TransformersDetector(
835
+ spec.repo_id if spec else model.removeprefix("hf:"),
836
+ revision=spec.revision if spec else None,
837
+ device=device,
838
+ precision=precision,
839
+ threshold=threshold,
840
+ classes=classes,
841
+ cache_dir=cache_dir,
842
+ )
843
+ return OnnxDetrDetector(
844
+ model,
845
+ precision=precision,
846
+ device=device,
847
+ threshold=threshold,
848
+ classes=classes,
849
+ cache_dir=cache_dir,
850
+ )