coolroman commited on
Commit
d39991e
·
verified ·
1 Parent(s): c08a697

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +727 -0
miner.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import math
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import onnxruntime as ort
7
+ from numpy import ndarray
8
+ from pydantic import BaseModel
9
+
10
+
11
+ class BoundingBox(BaseModel):
12
+ x1: int
13
+ y1: int
14
+ x2: int
15
+ y2: int
16
+ cls_id: int
17
+ conf: float
18
+
19
+
20
+ class TVFrameResult(BaseModel):
21
+ frame_id: int
22
+ boxes: list[BoundingBox]
23
+ keypoints: list[tuple[int, int]]
24
+
25
+
26
+ class Miner:
27
+ def __init__(self,
28
+ path_hf_repo: Path
29
+ ) -> None:
30
+ model_path = path_hf_repo / "weights.onnx"
31
+ # car-wash element classes — cls_id order MUST match element `objects`
32
+ # (0=broom, 1=drainage gate, 2=nozzle, 3=track) and the YOLO training order.
33
+ self.class_names = ["broom", "drainage gate", "nozzle", "track"]
34
+ model_class_order = ["broom", "drainage gate", "nozzle", "track"]
35
+ self.cls_remap = np.array(
36
+ [self.class_names.index(n) for n in model_class_order], dtype=np.int32
37
+ )
38
+ print("ORT version:", ort.__version__)
39
+
40
+ try:
41
+ ort.preload_dlls()
42
+ print("✅ onnxruntime.preload_dlls() success")
43
+ except Exception as e:
44
+ print(f"⚠️ preload_dlls failed: {e}")
45
+
46
+ print("ORT available providers BEFORE session:", ort.get_available_providers())
47
+
48
+ sess_options = ort.SessionOptions()
49
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
50
+
51
+ try:
52
+ self.session = ort.InferenceSession(
53
+ str(model_path),
54
+ sess_options=sess_options,
55
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
56
+ )
57
+ print("✅ Created ORT session with preferred CUDA provider list")
58
+ except Exception as e:
59
+ print(f"⚠️ CUDA session creation failed, falling back to CPU: {e}")
60
+ self.session = ort.InferenceSession(
61
+ str(model_path),
62
+ sess_options=sess_options,
63
+ providers=["CPUExecutionProvider"],
64
+ )
65
+
66
+ print("ORT session providers:", self.session.get_providers())
67
+
68
+ for inp in self.session.get_inputs():
69
+ print("INPUT:", inp.name, inp.shape, inp.type)
70
+
71
+ for out in self.session.get_outputs():
72
+ print("OUTPUT:", out.name, out.shape, out.type)
73
+
74
+ self.input_name = self.session.get_inputs()[0].name
75
+ self.output_names = [output.name for output in self.session.get_outputs()]
76
+ self.input_shape = self.session.get_inputs()[0].shape
77
+
78
+ # Match the ONNX input dtype (this export is FP16 -> needs float16 input).
79
+ input_type = self.session.get_inputs()[0].type
80
+ self.np_dtype = np.float16 if "float16" in input_type else np.float32
81
+ print(f"✅ ONNX input dtype: {input_type} -> numpy {self.np_dtype}")
82
+
83
+ # ONNX is fixed-size 1408x1408 (v1 export); read actual shape to be safe.
84
+ self.input_height = self._safe_dim(self.input_shape[2], default=1408)
85
+ self.input_width = self._safe_dim(self.input_shape[3], default=1408)
86
+
87
+ # Tuned for validator scoring (pillars: 0.6*map50 + 0.4*false_positive).
88
+ # conf 0.40 was the best element-score point in the v1 eval sweep.
89
+ self.conf_thres = 0.40 # Higher = fewer FP, slightly lower recall
90
+ self.iou_thres = 0.43 # Lower = suppress duplicate detections (FP)
91
+ self.max_det = 200 # Cap detections per image
92
+ self.use_tta = True
93
+
94
+ # Box sanity filter — kept loose: car-wash `nozzle` boxes are tiny
95
+ # (GT median ~290 px², smallest ~32 px²). Fire's 14x14/min_side 8
96
+ # would delete valid nozzles, so thresholds are dropped here.
97
+ self.min_box_area = 4 * 4 # 16 px²
98
+ self.min_side = 3
99
+ self.max_aspect_ratio = 12.0
100
+
101
+ print(f"✅ ONNX model loaded from: {model_path}")
102
+ print(f"✅ ONNX providers: {self.session.get_providers()}")
103
+ print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
104
+
105
+ def __repr__(self) -> str:
106
+ return (
107
+ f"ONNXRuntime(session={type(self.session).__name__}, "
108
+ f"providers={self.session.get_providers()})"
109
+ )
110
+
111
+ @staticmethod
112
+ def _safe_dim(value, default: int) -> int:
113
+ return value if isinstance(value, int) and value > 0 else default
114
+
115
+ def _letterbox(
116
+ self,
117
+ image: ndarray,
118
+ new_shape: tuple[int, int],
119
+ color=(114, 114, 114),
120
+ ) -> tuple[ndarray, float, tuple[float, float]]:
121
+ """
122
+ Resize with unchanged aspect ratio and pad to target shape.
123
+ Returns:
124
+ padded_image,
125
+ ratio,
126
+ (pad_w, pad_h) # half-padding
127
+ """
128
+ h, w = image.shape[:2]
129
+ new_w, new_h = new_shape
130
+
131
+ ratio = min(new_w / w, new_h / h)
132
+ resized_w = int(round(w * ratio))
133
+ resized_h = int(round(h * ratio))
134
+
135
+ if (resized_w, resized_h) != (w, h):
136
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
137
+ image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
138
+
139
+ dw = new_w - resized_w
140
+ dh = new_h - resized_h
141
+ dw /= 2.0
142
+ dh /= 2.0
143
+
144
+ left = int(round(dw - 0.1))
145
+ right = int(round(dw + 0.1))
146
+ top = int(round(dh - 0.1))
147
+ bottom = int(round(dh + 0.1))
148
+
149
+ padded = cv2.copyMakeBorder(
150
+ image,
151
+ top,
152
+ bottom,
153
+ left,
154
+ right,
155
+ borderType=cv2.BORDER_CONSTANT,
156
+ value=color,
157
+ )
158
+ return padded, ratio, (dw, dh)
159
+
160
+ def _preprocess(
161
+ self, image: ndarray
162
+ ) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
163
+ """
164
+ Preprocess for fixed-size ONNX export:
165
+ - enhance image quality (CLAHE, denoise, sharpen)
166
+ - letterbox to model input size
167
+ - BGR -> RGB
168
+ - normalize to [0,1]
169
+ - HWC -> NCHW float32
170
+ """
171
+ orig_h, orig_w = image.shape[:2]
172
+
173
+ img, ratio, pad = self._letterbox(
174
+ image, (self.input_width, self.input_height)
175
+ )
176
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
177
+ img = (img.astype(np.float32) / 255.0)
178
+ img = np.transpose(img, (2, 0, 1))[None, ...]
179
+ img = np.ascontiguousarray(img, dtype=self.np_dtype)
180
+
181
+ return img, ratio, pad, (orig_w, orig_h)
182
+
183
+ @staticmethod
184
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
185
+ w, h = image_size
186
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
187
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
188
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
189
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
190
+ return boxes
191
+
192
+ @staticmethod
193
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
194
+ out = np.empty_like(boxes)
195
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
196
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
197
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
198
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
199
+ return out
200
+
201
+ def _soft_nms(
202
+ self,
203
+ boxes: np.ndarray,
204
+ scores: np.ndarray,
205
+ sigma: float = 0.5,
206
+ score_thresh: float = 0.01,
207
+ ) -> tuple[np.ndarray, np.ndarray]:
208
+ """
209
+ Soft-NMS: Gaussian decay of overlapping scores instead of hard removal.
210
+ Returns (kept_original_indices, updated_scores).
211
+ """
212
+ N = len(boxes)
213
+ if N == 0:
214
+ return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
215
+
216
+ boxes = boxes.astype(np.float32, copy=True)
217
+ scores = scores.astype(np.float32, copy=True)
218
+ order = np.arange(N)
219
+
220
+ for i in range(N):
221
+ max_pos = i + int(np.argmax(scores[i:]))
222
+ boxes[[i, max_pos]] = boxes[[max_pos, i]]
223
+ scores[[i, max_pos]] = scores[[max_pos, i]]
224
+ order[[i, max_pos]] = order[[max_pos, i]]
225
+
226
+ if i + 1 >= N:
227
+ break
228
+
229
+ xx1 = np.maximum(boxes[i, 0], boxes[i + 1:, 0])
230
+ yy1 = np.maximum(boxes[i, 1], boxes[i + 1:, 1])
231
+ xx2 = np.minimum(boxes[i, 2], boxes[i + 1:, 2])
232
+ yy2 = np.minimum(boxes[i, 3], boxes[i + 1:, 3])
233
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
234
+
235
+ area_i = max(0.0, float(
236
+ (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
237
+ ))
238
+ areas_j = (
239
+ np.maximum(0.0, boxes[i + 1:, 2] - boxes[i + 1:, 0])
240
+ * np.maximum(0.0, boxes[i + 1:, 3] - boxes[i + 1:, 1])
241
+ )
242
+ iou = inter / (area_i + areas_j - inter + 1e-7)
243
+ scores[i + 1:] *= np.exp(-(iou ** 2) / sigma)
244
+
245
+ mask = scores > score_thresh
246
+ return order[mask], scores[mask]
247
+
248
+ @staticmethod
249
+ def _hard_nms(
250
+ boxes: np.ndarray,
251
+ scores: np.ndarray,
252
+ iou_thresh: float,
253
+ ) -> np.ndarray:
254
+ """
255
+ Standard NMS: keep one box per overlapping cluster (the one with highest score).
256
+ Returns indices of kept boxes (into the boxes/scores arrays).
257
+ """
258
+ N = len(boxes)
259
+ if N == 0:
260
+ return np.array([], dtype=np.intp)
261
+ boxes = np.asarray(boxes, dtype=np.float32)
262
+ scores = np.asarray(scores, dtype=np.float32)
263
+ order = np.argsort(scores)[::-1]
264
+ keep: list[int] = []
265
+ suppressed = np.zeros(N, dtype=bool)
266
+ for i in range(N):
267
+ idx = order[i]
268
+ if suppressed[idx]:
269
+ continue
270
+ keep.append(idx)
271
+ bi = boxes[idx]
272
+ for k in range(i + 1, N):
273
+ jdx = order[k]
274
+ if suppressed[jdx]:
275
+ continue
276
+ bj = boxes[jdx]
277
+ xx1 = max(bi[0], bj[0])
278
+ yy1 = max(bi[1], bj[1])
279
+ xx2 = min(bi[2], bj[2])
280
+ yy2 = min(bi[3], bj[3])
281
+ inter = max(0.0, xx2 - xx1) * max(0.0, yy2 - yy1)
282
+ area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])
283
+ area_j = (bj[2] - bj[0]) * (bj[3] - bj[1])
284
+ iou = inter / (area_i + area_j - inter + 1e-7)
285
+ if iou > iou_thresh:
286
+ suppressed[jdx] = True
287
+ return np.array(keep)
288
+
289
+ def _per_class_hard_nms(
290
+ self,
291
+ boxes: np.ndarray,
292
+ scores: np.ndarray,
293
+ cls_ids: np.ndarray,
294
+ iou_thresh: float,
295
+ ) -> np.ndarray:
296
+ """Hard NMS applied independently per class."""
297
+ if len(boxes) == 0:
298
+ return np.array([], dtype=np.intp)
299
+ all_keep: list[int] = []
300
+ for c in np.unique(cls_ids):
301
+ mask = cls_ids == c
302
+ indices = np.where(mask)[0]
303
+ keep = self._hard_nms(boxes[mask], scores[mask], iou_thresh)
304
+ all_keep.extend(indices[keep].tolist())
305
+ all_keep.sort()
306
+ return np.array(all_keep, dtype=np.intp)
307
+
308
+ def _per_class_soft_nms(
309
+ self,
310
+ boxes: np.ndarray,
311
+ scores: np.ndarray,
312
+ cls_ids: np.ndarray,
313
+ sigma: float = 0.5,
314
+ score_thresh: float = 0.01,
315
+ ) -> tuple[np.ndarray, np.ndarray]:
316
+ """Soft NMS applied independently per class."""
317
+ if len(boxes) == 0:
318
+ return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
319
+ all_keep: list[int] = []
320
+ all_scores: list[float] = []
321
+ for c in np.unique(cls_ids):
322
+ mask = cls_ids == c
323
+ indices = np.where(mask)[0]
324
+ keep, updated = self._soft_nms(boxes[mask], scores[mask], sigma, score_thresh)
325
+ for k, s in zip(keep, updated):
326
+ all_keep.append(int(indices[k]))
327
+ all_scores.append(float(s))
328
+ if not all_keep:
329
+ return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
330
+ return np.array(all_keep, dtype=np.intp), np.array(all_scores, dtype=np.float32)
331
+
332
+ def _filter_sane_boxes(
333
+ self,
334
+ boxes: np.ndarray,
335
+ scores: np.ndarray,
336
+ cls_ids: np.ndarray,
337
+ orig_size: tuple[int, int],
338
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
339
+ """Filter out tiny, degenerate, or implausible boxes (common FP)."""
340
+ if len(boxes) == 0:
341
+ return boxes, scores, cls_ids
342
+ orig_w, orig_h = orig_size
343
+ image_area = float(orig_w * orig_h)
344
+ keep = []
345
+ for i, box in enumerate(boxes):
346
+ x1, y1, x2, y2 = box.tolist()
347
+ bw = x2 - x1
348
+ bh = y2 - y1
349
+ if bw <= 0 or bh <= 0:
350
+ continue
351
+ if bw < self.min_side or bh < self.min_side:
352
+ continue
353
+ area = bw * bh
354
+ if area < self.min_box_area:
355
+ continue
356
+ if area > 0.95 * image_area:
357
+ continue
358
+ ar = max(bw / max(bh, 1e-6), bh / max(bw, 1e-6))
359
+ if ar > self.max_aspect_ratio:
360
+ continue
361
+ keep.append(i)
362
+ if not keep:
363
+ return (
364
+ np.empty((0, 4), dtype=np.float32),
365
+ np.empty((0,), dtype=np.float32),
366
+ np.empty((0,), dtype=np.int32),
367
+ )
368
+ k = np.array(keep, dtype=np.intp)
369
+ return boxes[k], scores[k], cls_ids[k]
370
+
371
+ @staticmethod
372
+ def _max_score_per_cluster(
373
+ coords: np.ndarray,
374
+ scores: np.ndarray,
375
+ keep_indices: np.ndarray,
376
+ iou_thresh: float,
377
+ ) -> np.ndarray:
378
+ """
379
+ For each kept box, return the max original score among itself and any
380
+ box that overlaps it with IOU >= iou_thresh (so TTA cluster keeps best conf).
381
+ """
382
+ n_keep = len(keep_indices)
383
+ if n_keep == 0:
384
+ return np.array([], dtype=np.float32)
385
+ out = np.empty(n_keep, dtype=np.float32)
386
+ coords = np.asarray(coords, dtype=np.float32)
387
+ scores = np.asarray(scores, dtype=np.float32)
388
+ for i in range(n_keep):
389
+ idx = keep_indices[i]
390
+ bi = coords[idx]
391
+ xx1 = np.maximum(bi[0], coords[:, 0])
392
+ yy1 = np.maximum(bi[1], coords[:, 1])
393
+ xx2 = np.minimum(bi[2], coords[:, 2])
394
+ yy2 = np.minimum(bi[3], coords[:, 3])
395
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
396
+ area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])
397
+ areas_j = (coords[:, 2] - coords[:, 0]) * (coords[:, 3] - coords[:, 1])
398
+ iou = inter / (area_i + areas_j - inter + 1e-7)
399
+ in_cluster = iou >= iou_thresh
400
+ out[i] = float(np.max(scores[in_cluster]))
401
+ return out
402
+
403
+ def _decode_final_dets(
404
+ self,
405
+ preds: np.ndarray,
406
+ ratio: float,
407
+ pad: tuple[float, float],
408
+ orig_size: tuple[int, int],
409
+ apply_optional_dedup: bool = False,
410
+ ) -> list[BoundingBox]:
411
+ """
412
+ Primary path:
413
+ expected output rows like [x1, y1, x2, y2, conf, cls_id]
414
+ in letterboxed input coordinates.
415
+ """
416
+ if preds.ndim == 3 and preds.shape[0] == 1:
417
+ preds = preds[0]
418
+
419
+ if preds.ndim != 2 or preds.shape[1] < 6:
420
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
421
+
422
+ boxes = preds[:, :4].astype(np.float32)
423
+ scores = preds[:, 4].astype(np.float32)
424
+ cls_ids = preds[:, 5].astype(np.int32)
425
+ cls_ids = self.cls_remap[cls_ids]
426
+
427
+ # Save raw before primary conf filter for rescue path
428
+ raw_boxes = boxes.copy()
429
+ raw_scores = scores.copy()
430
+ raw_cls_ids = cls_ids.copy()
431
+
432
+ keep = scores >= self.conf_thres
433
+ boxes = boxes[keep]
434
+ scores = scores[keep]
435
+ cls_ids = cls_ids[keep]
436
+
437
+ # Rescue: for each of 4 classes, if 0 boxes passed primary threshold,
438
+ # take the top-1 raw candidate if its score >= rescue_thres.
439
+ # Avoids zero-prediction frames where validator scores us composite ~0.05.
440
+ rescue_margin = 0.10
441
+ rescue_thres = max(0.0, self.conf_thres - rescue_margin)
442
+ present_cls = set(cls_ids.tolist()) if len(cls_ids) > 0 else set()
443
+ for tgt_cid in range(4):
444
+ if tgt_cid in present_cls:
445
+ continue
446
+ cls_mask = raw_cls_ids == tgt_cid
447
+ if not cls_mask.any():
448
+ continue
449
+ cls_scores = raw_scores[cls_mask]
450
+ top_pos = int(np.argmax(cls_scores))
451
+ if float(cls_scores[top_pos]) >= rescue_thres:
452
+ cls_indices = np.where(cls_mask)[0]
453
+ chosen = cls_indices[top_pos]
454
+ boxes = np.vstack([boxes, raw_boxes[chosen:chosen + 1]]) if len(boxes) > 0 else raw_boxes[chosen:chosen + 1]
455
+ scores = np.append(scores, raw_scores[chosen])
456
+ cls_ids = np.append(cls_ids, tgt_cid)
457
+
458
+ if len(boxes) == 0:
459
+ return []
460
+
461
+ pad_w, pad_h = pad
462
+ orig_w, orig_h = orig_size
463
+
464
+ # reverse letterbox
465
+ boxes[:, [0, 2]] -= pad_w
466
+ boxes[:, [1, 3]] -= pad_h
467
+ boxes /= ratio
468
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
469
+
470
+ # Box sanity filter (reduces FP)
471
+ boxes, scores, cls_ids = self._filter_sane_boxes(
472
+ boxes, scores, cls_ids, orig_size
473
+ )
474
+ if len(boxes) == 0:
475
+ return []
476
+
477
+ # Per-class NMS to remove duplicates without suppressing across classes
478
+ if len(boxes) > 1:
479
+ if apply_optional_dedup:
480
+ keep_idx, scores = self._per_class_soft_nms(boxes, scores, cls_ids)
481
+ boxes = boxes[keep_idx]
482
+ cls_ids = cls_ids[keep_idx]
483
+ else:
484
+ keep_idx = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
485
+ keep_idx = keep_idx[: self.max_det]
486
+ boxes = boxes[keep_idx]
487
+ scores = scores[keep_idx]
488
+ cls_ids = cls_ids[keep_idx]
489
+
490
+ results: list[BoundingBox] = []
491
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
492
+ x1, y1, x2, y2 = box.tolist()
493
+
494
+ if x2 <= x1 or y2 <= y1:
495
+ continue
496
+
497
+ results.append(
498
+ BoundingBox(
499
+ x1=int(math.floor(x1)),
500
+ y1=int(math.floor(y1)),
501
+ x2=int(math.ceil(x2)),
502
+ y2=int(math.ceil(y2)),
503
+ cls_id=int(cls_id),
504
+ conf=float(conf),
505
+ )
506
+ )
507
+
508
+ return results
509
+
510
+ def _decode_raw_yolo(
511
+ self,
512
+ preds: np.ndarray,
513
+ ratio: float,
514
+ pad: tuple[float, float],
515
+ orig_size: tuple[int, int],
516
+ ) -> list[BoundingBox]:
517
+ """
518
+ Fallback path for raw YOLO predictions.
519
+ Supports common layouts:
520
+ - [1, C, N]
521
+ - [1, N, C]
522
+ """
523
+ if preds.ndim != 3:
524
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
525
+
526
+ if preds.shape[0] != 1:
527
+ raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
528
+
529
+ preds = preds[0]
530
+
531
+ # Normalize to [N, C]
532
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
533
+ preds = preds.T
534
+
535
+ if preds.ndim != 2 or preds.shape[1] < 5:
536
+ raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
537
+
538
+ boxes_xywh = preds[:, :4].astype(np.float32)
539
+ cls_part = preds[:, 4:].astype(np.float32)
540
+
541
+ if cls_part.shape[1] == 1:
542
+ scores = cls_part[:, 0]
543
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
544
+ else:
545
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
546
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
547
+ cls_ids = self.cls_remap[cls_ids]
548
+
549
+ keep = scores >= self.conf_thres
550
+ boxes_xywh = boxes_xywh[keep]
551
+ scores = scores[keep]
552
+ cls_ids = cls_ids[keep]
553
+
554
+ if len(boxes_xywh) == 0:
555
+ return []
556
+
557
+ boxes = self._xywh_to_xyxy(boxes_xywh)
558
+
559
+ keep_idx = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
560
+ keep_idx = keep_idx[: self.max_det]
561
+ boxes = boxes[keep_idx]
562
+ scores = scores[keep_idx]
563
+ cls_ids = cls_ids[keep_idx]
564
+
565
+ pad_w, pad_h = pad
566
+ orig_w, orig_h = orig_size
567
+
568
+ boxes[:, [0, 2]] -= pad_w
569
+ boxes[:, [1, 3]] -= pad_h
570
+ boxes /= ratio
571
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
572
+
573
+ boxes, scores, cls_ids = self._filter_sane_boxes(
574
+ boxes, scores, cls_ids, (orig_w, orig_h)
575
+ )
576
+ if len(boxes) == 0:
577
+ return []
578
+
579
+ results: list[BoundingBox] = []
580
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
581
+ x1, y1, x2, y2 = box.tolist()
582
+
583
+ if x2 <= x1 or y2 <= y1:
584
+ continue
585
+
586
+ results.append(
587
+ BoundingBox(
588
+ x1=int(math.floor(x1)),
589
+ y1=int(math.floor(y1)),
590
+ x2=int(math.ceil(x2)),
591
+ y2=int(math.ceil(y2)),
592
+ cls_id=int(cls_id),
593
+ conf=float(conf),
594
+ )
595
+ )
596
+
597
+ return results
598
+
599
+ def _postprocess(
600
+ self,
601
+ output: np.ndarray,
602
+ ratio: float,
603
+ pad: tuple[float, float],
604
+ orig_size: tuple[int, int],
605
+ ) -> list[BoundingBox]:
606
+ """
607
+ Prefer final detections first.
608
+ Fallback to raw decode only if needed.
609
+ """
610
+ # final detections: [N,6]
611
+ if output.ndim == 2 and output.shape[1] >= 6:
612
+ return self._decode_final_dets(output, ratio, pad, orig_size)
613
+
614
+ # final detections: [1,N,6]
615
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
616
+ return self._decode_final_dets(output, ratio, pad, orig_size)
617
+
618
+ # fallback raw decode
619
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
620
+
621
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
622
+ if image is None:
623
+ raise ValueError("Input image is None")
624
+ if not isinstance(image, np.ndarray):
625
+ raise TypeError(f"Input is not numpy array: {type(image)}")
626
+ if image.ndim != 3:
627
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
628
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
629
+ raise ValueError(f"Invalid image shape={image.shape}")
630
+ if image.shape[2] != 3:
631
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
632
+
633
+ if image.dtype != np.uint8:
634
+ image = image.astype(np.uint8)
635
+
636
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
637
+
638
+ expected_shape = (1, 3, self.input_height, self.input_width)
639
+ if input_tensor.shape != expected_shape:
640
+ raise ValueError(
641
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}"
642
+ )
643
+
644
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
645
+ det_output = outputs[0]
646
+ return self._postprocess(det_output, ratio, pad, orig_size)
647
+
648
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
649
+ """
650
+ Horizontal-flip TTA: merge original + flipped via hard NMS.
651
+ Boost confidence for consensus detections (both views agree) to improve
652
+ mAP: validator sorts by confidence, so higher conf for TP helps PR curve.
653
+ """
654
+ boxes_orig = self._predict_single(image)
655
+
656
+ flipped = cv2.flip(image, 1)
657
+ boxes_flip = self._predict_single(flipped)
658
+
659
+ w = image.shape[1]
660
+ boxes_flip = [
661
+ BoundingBox(
662
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
663
+ cls_id=b.cls_id, conf=b.conf,
664
+ )
665
+ for b in boxes_flip
666
+ ]
667
+
668
+ all_boxes = boxes_orig + boxes_flip
669
+ if len(all_boxes) == 0:
670
+ return []
671
+
672
+ coords = np.array(
673
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
674
+ )
675
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
676
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
677
+
678
+ hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
679
+ if len(hard_keep) == 0:
680
+ return []
681
+
682
+ hard_keep = hard_keep[: self.max_det]
683
+
684
+ # Boost confidence when both views agree (overlapping detections)
685
+ boosted = self._max_score_per_cluster(
686
+ coords, scores, hard_keep, self.iou_thres
687
+ )
688
+
689
+ return [
690
+ BoundingBox(
691
+ x1=all_boxes[i].x1,
692
+ y1=all_boxes[i].y1,
693
+ x2=all_boxes[i].x2,
694
+ y2=all_boxes[i].y2,
695
+ cls_id=all_boxes[i].cls_id,
696
+ conf=float(boosted[j]),
697
+ )
698
+ for j, i in enumerate(hard_keep)
699
+ ]
700
+
701
+ def predict_batch(
702
+ self,
703
+ batch_images: list[ndarray],
704
+ offset: int,
705
+ n_keypoints: int,
706
+ ) -> list[TVFrameResult]:
707
+ results: list[TVFrameResult] = []
708
+
709
+ for frame_number_in_batch, image in enumerate(batch_images):
710
+ try:
711
+ if self.use_tta:
712
+ boxes = self._predict_tta(image)
713
+ else:
714
+ boxes = self._predict_single(image)
715
+ except Exception as e:
716
+ print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")
717
+ boxes = []
718
+
719
+ results.append(
720
+ TVFrameResult(
721
+ frame_id=offset + frame_number_in_batch,
722
+ boxes=boxes,
723
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
724
+ )
725
+ )
726
+
727
+ return results