coolroman commited on
Commit
43b0865
·
verified ·
1 Parent(s): b0d4f7c

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +701 -0
miner.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ keep = scores >= self.conf_thres
428
+ boxes = boxes[keep]
429
+ scores = scores[keep]
430
+ cls_ids = cls_ids[keep]
431
+
432
+ if len(boxes) == 0:
433
+ return []
434
+
435
+ pad_w, pad_h = pad
436
+ orig_w, orig_h = orig_size
437
+
438
+ # reverse letterbox
439
+ boxes[:, [0, 2]] -= pad_w
440
+ boxes[:, [1, 3]] -= pad_h
441
+ boxes /= ratio
442
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
443
+
444
+ # Box sanity filter (reduces FP)
445
+ boxes, scores, cls_ids = self._filter_sane_boxes(
446
+ boxes, scores, cls_ids, orig_size
447
+ )
448
+ if len(boxes) == 0:
449
+ return []
450
+
451
+ # Per-class NMS to remove duplicates without suppressing across classes
452
+ if len(boxes) > 1:
453
+ if apply_optional_dedup:
454
+ keep_idx, scores = self._per_class_soft_nms(boxes, scores, cls_ids)
455
+ boxes = boxes[keep_idx]
456
+ cls_ids = cls_ids[keep_idx]
457
+ else:
458
+ keep_idx = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
459
+ keep_idx = keep_idx[: self.max_det]
460
+ boxes = boxes[keep_idx]
461
+ scores = scores[keep_idx]
462
+ cls_ids = cls_ids[keep_idx]
463
+
464
+ results: list[BoundingBox] = []
465
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
466
+ x1, y1, x2, y2 = box.tolist()
467
+
468
+ if x2 <= x1 or y2 <= y1:
469
+ continue
470
+
471
+ results.append(
472
+ BoundingBox(
473
+ x1=int(math.floor(x1)),
474
+ y1=int(math.floor(y1)),
475
+ x2=int(math.ceil(x2)),
476
+ y2=int(math.ceil(y2)),
477
+ cls_id=int(cls_id),
478
+ conf=float(conf),
479
+ )
480
+ )
481
+
482
+ return results
483
+
484
+ def _decode_raw_yolo(
485
+ self,
486
+ preds: np.ndarray,
487
+ ratio: float,
488
+ pad: tuple[float, float],
489
+ orig_size: tuple[int, int],
490
+ ) -> list[BoundingBox]:
491
+ """
492
+ Fallback path for raw YOLO predictions.
493
+ Supports common layouts:
494
+ - [1, C, N]
495
+ - [1, N, C]
496
+ """
497
+ if preds.ndim != 3:
498
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
499
+
500
+ if preds.shape[0] != 1:
501
+ raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
502
+
503
+ preds = preds[0]
504
+
505
+ # Normalize to [N, C]
506
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
507
+ preds = preds.T
508
+
509
+ if preds.ndim != 2 or preds.shape[1] < 5:
510
+ raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
511
+
512
+ boxes_xywh = preds[:, :4].astype(np.float32)
513
+ cls_part = preds[:, 4:].astype(np.float32)
514
+
515
+ if cls_part.shape[1] == 1:
516
+ scores = cls_part[:, 0]
517
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
518
+ else:
519
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
520
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
521
+ cls_ids = self.cls_remap[cls_ids]
522
+
523
+ keep = scores >= self.conf_thres
524
+ boxes_xywh = boxes_xywh[keep]
525
+ scores = scores[keep]
526
+ cls_ids = cls_ids[keep]
527
+
528
+ if len(boxes_xywh) == 0:
529
+ return []
530
+
531
+ boxes = self._xywh_to_xyxy(boxes_xywh)
532
+
533
+ keep_idx = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
534
+ keep_idx = keep_idx[: self.max_det]
535
+ boxes = boxes[keep_idx]
536
+ scores = scores[keep_idx]
537
+ cls_ids = cls_ids[keep_idx]
538
+
539
+ pad_w, pad_h = pad
540
+ orig_w, orig_h = orig_size
541
+
542
+ boxes[:, [0, 2]] -= pad_w
543
+ boxes[:, [1, 3]] -= pad_h
544
+ boxes /= ratio
545
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
546
+
547
+ boxes, scores, cls_ids = self._filter_sane_boxes(
548
+ boxes, scores, cls_ids, (orig_w, orig_h)
549
+ )
550
+ if len(boxes) == 0:
551
+ return []
552
+
553
+ results: list[BoundingBox] = []
554
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
555
+ x1, y1, x2, y2 = box.tolist()
556
+
557
+ if x2 <= x1 or y2 <= y1:
558
+ continue
559
+
560
+ results.append(
561
+ BoundingBox(
562
+ x1=int(math.floor(x1)),
563
+ y1=int(math.floor(y1)),
564
+ x2=int(math.ceil(x2)),
565
+ y2=int(math.ceil(y2)),
566
+ cls_id=int(cls_id),
567
+ conf=float(conf),
568
+ )
569
+ )
570
+
571
+ return results
572
+
573
+ def _postprocess(
574
+ self,
575
+ output: np.ndarray,
576
+ ratio: float,
577
+ pad: tuple[float, float],
578
+ orig_size: tuple[int, int],
579
+ ) -> list[BoundingBox]:
580
+ """
581
+ Prefer final detections first.
582
+ Fallback to raw decode only if needed.
583
+ """
584
+ # final detections: [N,6]
585
+ if output.ndim == 2 and output.shape[1] >= 6:
586
+ return self._decode_final_dets(output, ratio, pad, orig_size)
587
+
588
+ # final detections: [1,N,6]
589
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
590
+ return self._decode_final_dets(output, ratio, pad, orig_size)
591
+
592
+ # fallback raw decode
593
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
594
+
595
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
596
+ if image is None:
597
+ raise ValueError("Input image is None")
598
+ if not isinstance(image, np.ndarray):
599
+ raise TypeError(f"Input is not numpy array: {type(image)}")
600
+ if image.ndim != 3:
601
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
602
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
603
+ raise ValueError(f"Invalid image shape={image.shape}")
604
+ if image.shape[2] != 3:
605
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
606
+
607
+ if image.dtype != np.uint8:
608
+ image = image.astype(np.uint8)
609
+
610
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
611
+
612
+ expected_shape = (1, 3, self.input_height, self.input_width)
613
+ if input_tensor.shape != expected_shape:
614
+ raise ValueError(
615
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}"
616
+ )
617
+
618
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
619
+ det_output = outputs[0]
620
+ return self._postprocess(det_output, ratio, pad, orig_size)
621
+
622
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
623
+ """
624
+ Horizontal-flip TTA: merge original + flipped via hard NMS.
625
+ Boost confidence for consensus detections (both views agree) to improve
626
+ mAP: validator sorts by confidence, so higher conf for TP helps PR curve.
627
+ """
628
+ boxes_orig = self._predict_single(image)
629
+
630
+ flipped = cv2.flip(image, 1)
631
+ boxes_flip = self._predict_single(flipped)
632
+
633
+ w = image.shape[1]
634
+ boxes_flip = [
635
+ BoundingBox(
636
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
637
+ cls_id=b.cls_id, conf=b.conf,
638
+ )
639
+ for b in boxes_flip
640
+ ]
641
+
642
+ all_boxes = boxes_orig + boxes_flip
643
+ if len(all_boxes) == 0:
644
+ return []
645
+
646
+ coords = np.array(
647
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
648
+ )
649
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
650
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
651
+
652
+ hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
653
+ if len(hard_keep) == 0:
654
+ return []
655
+
656
+ hard_keep = hard_keep[: self.max_det]
657
+
658
+ # Boost confidence when both views agree (overlapping detections)
659
+ boosted = self._max_score_per_cluster(
660
+ coords, scores, hard_keep, self.iou_thres
661
+ )
662
+
663
+ return [
664
+ BoundingBox(
665
+ x1=all_boxes[i].x1,
666
+ y1=all_boxes[i].y1,
667
+ x2=all_boxes[i].x2,
668
+ y2=all_boxes[i].y2,
669
+ cls_id=all_boxes[i].cls_id,
670
+ conf=float(boosted[j]),
671
+ )
672
+ for j, i in enumerate(hard_keep)
673
+ ]
674
+
675
+ def predict_batch(
676
+ self,
677
+ batch_images: list[ndarray],
678
+ offset: int,
679
+ n_keypoints: int,
680
+ ) -> list[TVFrameResult]:
681
+ results: list[TVFrameResult] = []
682
+
683
+ for frame_number_in_batch, image in enumerate(batch_images):
684
+ try:
685
+ if self.use_tta:
686
+ boxes = self._predict_tta(image)
687
+ else:
688
+ boxes = self._predict_single(image)
689
+ except Exception as e:
690
+ print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")
691
+ boxes = []
692
+
693
+ results.append(
694
+ TVFrameResult(
695
+ frame_id=offset + frame_number_in_batch,
696
+ boxes=boxes,
697
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
698
+ )
699
+ )
700
+
701
+ return results