happydev93 commited on
Commit
afce8c6
·
verified ·
1 Parent(s): 49fc621

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +752 -0
miner.py ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ONNX Runtime miner for fire / smoke / fire_extinguisher detection.
28
+
29
+ Strategy (ported from offense miner):
30
+ - per-class confidence threshold with per-class rescue bonus
31
+ - per-class hard NMS, then cross-class dedup
32
+ - horizontal-flip TTA with full-set cluster score boost
33
+ Plus fire001 specifics: class remap, sanity-box filter, TTA toggle.
34
+ """
35
+
36
+ class_names = ["fire", "smoke", "fire extinguisher"]
37
+ _cls_fire = 0 # index in class_names
38
+ _cls_smoke = 1 # index in class_names
39
+ _cls_fire_extinguisher = 2 # index in class_names
40
+ _nested_zone_classes = (_cls_fire, _cls_smoke)
41
+ # Order the model emits classes in -- remapped to `class_names` index.
42
+ _model_class_order = ["fire", "fire extinguisher", "smoke"]
43
+
44
+ iou_thres = 0.55
45
+ cross_iou_thresh = 0.8
46
+ max_det = 150
47
+ nested_contain_ratio = 0.8
48
+ nested_close_score_thresh = 0.5
49
+ nested_close_score_margin = 0.4
50
+ #"fire", "smoke", "fire extinguisher"
51
+ _conf_thres_array = np.array([0.65, 0.66, 0.42], dtype=np.float32)
52
+ _bonus_array = np.array([0.3, 0.31, 0.395], dtype=np.float32)
53
+ # Box sanity filter (fire001-specific FP reduction): drop tiny / degenerate
54
+ # / image-spanning / extreme aspect ratio boxes.
55
+ min_box_area = 14 * 14
56
+ min_side = 8
57
+ max_aspect_ratio = 8.0
58
+
59
+ def __init__(self, path_hf_repo: Path) -> None:
60
+ model_path = path_hf_repo / "weights.onnx"
61
+ self.cls_remap = np.array(
62
+ [self.class_names.index(n) for n in self._model_class_order],
63
+ dtype=np.int32,
64
+ )
65
+ print("ORT version:", ort.__version__)
66
+
67
+ try:
68
+ ort.preload_dlls()
69
+ print("✅ onnxruntime.preload_dlls() success")
70
+ except Exception as e:
71
+ print(f"⚠️ preload_dlls failed: {e}")
72
+
73
+ print("ORT available providers BEFORE session:", ort.get_available_providers())
74
+
75
+ sess_options = ort.SessionOptions()
76
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
77
+
78
+ try:
79
+ self.session = ort.InferenceSession(
80
+ str(model_path),
81
+ sess_options=sess_options,
82
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
83
+ )
84
+ print("✅ Created ORT session with preferred CUDA provider list")
85
+ except Exception as e:
86
+ print(f"⚠️ CUDA session creation failed, falling back to CPU: {e}")
87
+ self.session = ort.InferenceSession(
88
+ str(model_path),
89
+ sess_options=sess_options,
90
+ providers=["CPUExecutionProvider"],
91
+ )
92
+
93
+ print("ORT session providers:", self.session.get_providers())
94
+
95
+ for inp in self.session.get_inputs():
96
+ print("INPUT:", inp.name, inp.shape, inp.type)
97
+ for out in self.session.get_outputs():
98
+ print("OUTPUT:", out.name, out.shape, out.type)
99
+
100
+ self.input_name = self.session.get_inputs()[0].name
101
+ self.output_names = [output.name for output in self.session.get_outputs()]
102
+ self.input_shape = self.session.get_inputs()[0].shape
103
+
104
+ self.input_height = self._safe_dim(self.input_shape[2], default=1280)
105
+ self.input_width = self._safe_dim(self.input_shape[3], default=1280)
106
+
107
+ self.use_tta = True
108
+
109
+ print(f"✅ ONNX model loaded from: {model_path}")
110
+ print(f"✅ ONNX providers: {self.session.get_providers()}")
111
+ print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
112
+ print("per-class conf: " + ", ".join(
113
+ f"{n}={t:.3f}" for n, t in zip(
114
+ self.class_names, self._conf_thres_array.tolist()
115
+ )
116
+ ))
117
+
118
+ def __repr__(self) -> str:
119
+ return (
120
+ f"ONNXRuntime(session={type(self.session).__name__}, "
121
+ f"providers={self.session.get_providers()})"
122
+ )
123
+
124
+ @staticmethod
125
+ def _safe_dim(value, default: int) -> int:
126
+ return value if isinstance(value, int) and value > 0 else default
127
+
128
+ def _letterbox(
129
+ self,
130
+ image: ndarray,
131
+ new_shape: tuple[int, int],
132
+ color=(114, 114, 114),
133
+ ) -> tuple[ndarray, float, tuple[float, float]]:
134
+ h, w = image.shape[:2]
135
+ new_w, new_h = new_shape
136
+
137
+ ratio = min(new_w / w, new_h / h)
138
+ resized_w = int(round(w * ratio))
139
+ resized_h = int(round(h * ratio))
140
+
141
+ if (resized_w, resized_h) != (w, h):
142
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
143
+ image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
144
+
145
+ dw = (new_w - resized_w) / 2.0
146
+ dh = (new_h - resized_h) / 2.0
147
+
148
+ left = int(round(dw - 0.1))
149
+ right = int(round(dw + 0.1))
150
+ top = int(round(dh - 0.1))
151
+ bottom = int(round(dh + 0.1))
152
+
153
+ padded = cv2.copyMakeBorder(
154
+ image, top, bottom, left, right,
155
+ borderType=cv2.BORDER_CONSTANT, value=color,
156
+ )
157
+ return padded, ratio, (dw, dh)
158
+
159
+ def _preprocess(
160
+ self, image: ndarray
161
+ ) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
162
+ orig_h, orig_w = image.shape[:2]
163
+ img, ratio, pad = self._letterbox(
164
+ image, (self.input_width, self.input_height)
165
+ )
166
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
167
+ img = img.astype(np.float32) / 255.0
168
+ img = np.transpose(img, (2, 0, 1))[None, ...]
169
+ img = np.ascontiguousarray(img, dtype=np.float32)
170
+ return img, ratio, pad, (orig_w, orig_h)
171
+
172
+ @staticmethod
173
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
174
+ w, h = image_size
175
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
176
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
177
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
178
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
179
+ return boxes
180
+
181
+ @staticmethod
182
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
183
+ out = np.empty_like(boxes)
184
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
185
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
186
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
187
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
188
+ return out
189
+
190
+ @staticmethod
191
+ def _hard_nms(
192
+ boxes: np.ndarray, scores: np.ndarray, iou_thresh: float
193
+ ) -> np.ndarray:
194
+ n = len(boxes)
195
+ if n == 0:
196
+ return np.array([], dtype=np.intp)
197
+ order = np.argsort(-scores)
198
+ keep: list[int] = []
199
+ while len(order) > 0:
200
+ i = int(order[0])
201
+ keep.append(i)
202
+ if len(order) == 1:
203
+ break
204
+ rest = order[1:]
205
+ xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
206
+ yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
207
+ xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
208
+ yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
209
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
210
+ a_i = (max(0.0, boxes[i, 2] - boxes[i, 0]) *
211
+ max(0.0, boxes[i, 3] - boxes[i, 1]))
212
+ a_r = (np.maximum(0.0, boxes[rest, 2] - boxes[rest, 0]) *
213
+ np.maximum(0.0, boxes[rest, 3] - boxes[rest, 1]))
214
+ iou = inter / (a_i + a_r - inter + 1e-7)
215
+ order = rest[iou <= iou_thresh]
216
+ return np.array(keep, dtype=np.intp)
217
+
218
+ def _per_class_hard_nms(
219
+ self,
220
+ boxes: np.ndarray,
221
+ scores: np.ndarray,
222
+ cls_ids: np.ndarray,
223
+ iou_thresh: float,
224
+ ) -> np.ndarray:
225
+ if len(boxes) == 0:
226
+ return np.array([], dtype=np.intp)
227
+ all_keep: list[int] = []
228
+ for c in np.unique(cls_ids):
229
+ mask = cls_ids == c
230
+ indices = np.where(mask)[0]
231
+ keep = self._hard_nms(boxes[mask], scores[mask], iou_thresh)
232
+ all_keep.extend(indices[keep].tolist())
233
+ all_keep.sort()
234
+ return np.array(all_keep, dtype=np.intp)
235
+
236
+ @staticmethod
237
+ def _box_mostly_contained(
238
+ outer: np.ndarray, inner: np.ndarray, ratio: float
239
+ ) -> bool:
240
+ """True when at least `ratio` of inner's area lies inside outer."""
241
+ xx1 = max(float(outer[0]), float(inner[0]))
242
+ yy1 = max(float(outer[1]), float(inner[1]))
243
+ xx2 = min(float(outer[2]), float(inner[2]))
244
+ yy2 = min(float(outer[3]), float(inner[3]))
245
+ inter = max(0.0, xx2 - xx1) * max(0.0, yy2 - yy1)
246
+ inner_area = max(
247
+ 1e-7,
248
+ (float(inner[2]) - float(inner[0])) * (float(inner[3]) - float(inner[1])),
249
+ )
250
+ return inter / inner_area >= ratio
251
+
252
+ def _nested_zone_filter(
253
+ self,
254
+ boxes: np.ndarray,
255
+ scores: np.ndarray,
256
+ cls_ids: np.ndarray,
257
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
258
+ """Among nested fire/smoke pairs (>=80% containment).
259
+
260
+ If both scores are >0.5 and |score_i - score_j| < 0.4, keep the
261
+ larger box; otherwise keep the higher score.
262
+ """
263
+ n = len(boxes)
264
+ if n <= 1:
265
+ return boxes, scores, cls_ids
266
+
267
+ ratio = self.nested_contain_ratio
268
+ boxes = np.asarray(boxes, dtype=np.float32)
269
+ scores = np.asarray(scores, dtype=np.float32)
270
+ cls_ids = np.asarray(cls_ids, dtype=np.int32)
271
+ suppress = np.zeros(n, dtype=bool)
272
+ for cls_id in self._nested_zone_classes:
273
+ class_idx = np.where(cls_ids == cls_id)[0]
274
+ if len(class_idx) <= 1:
275
+ continue
276
+ for a in range(len(class_idx)):
277
+ i = int(class_idx[a])
278
+ if suppress[i]:
279
+ continue
280
+ bi = boxes[i]
281
+ for b in range(a + 1, len(class_idx)):
282
+ j = int(class_idx[b])
283
+ if suppress[j]:
284
+ continue
285
+ bj = boxes[j]
286
+ nested = (
287
+ self._box_mostly_contained(bi, bj, ratio)
288
+ or self._box_mostly_contained(bj, bi, ratio)
289
+ )
290
+ if not nested:
291
+ continue
292
+ si = float(scores[i])
293
+ sj = float(scores[j])
294
+ if (
295
+ si > self.nested_close_score_thresh
296
+ and sj > self.nested_close_score_thresh
297
+ and abs(si - sj) < self.nested_close_score_margin
298
+ ):
299
+ area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])
300
+ area_j = (bj[2] - bj[0]) * (bj[3] - bj[1])
301
+ if area_i >= area_j:
302
+ suppress[j] = True
303
+ else:
304
+ suppress[i] = True
305
+ break
306
+ elif si >= sj:
307
+ suppress[j] = True
308
+ else:
309
+ suppress[i] = True
310
+ break
311
+
312
+ keep = ~suppress
313
+ return boxes[keep], scores[keep], cls_ids[keep]
314
+
315
+ def _cross_class_dedup_op(
316
+ self,
317
+ boxes: np.ndarray,
318
+ scores: np.ndarray,
319
+ cls_ids: np.ndarray,
320
+ iou_thresh: float,
321
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
322
+ """Remove near-duplicate boxes across classes.
323
+
324
+ Order candidates by (score - per_class_threshold) margin, then by area;
325
+ keep the highest, suppress every other box with IoU > iou_thresh.
326
+ This suppresses the case where the same physical object is detected
327
+ as multiple classes (e.g. fire vs smoke on the same flames).
328
+
329
+ Fire extinguisher is exempt: it is a distinct object and may overlap
330
+ fire/smoke boxes in scene without being a duplicate detection.
331
+ """
332
+ n = len(boxes)
333
+ if n <= 1:
334
+ return boxes, scores, cls_ids
335
+ boxes = np.asarray(boxes, dtype=np.float32)
336
+ scores = np.asarray(scores, dtype=np.float32)
337
+ cls_ids = np.asarray(cls_ids, dtype=np.int32)
338
+ ext_cls = self._cls_fire_extinguisher
339
+ areas = (np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) *
340
+ np.maximum(0.0, boxes[:, 3] - boxes[:, 1]))
341
+ margins = scores - self._conf_thres_array[cls_ids]
342
+ order = np.lexsort((-areas, -margins))
343
+ suppressed = np.zeros(n, dtype=bool)
344
+ keep: list[int] = []
345
+ for i in order:
346
+ if suppressed[i]:
347
+ continue
348
+ keep.append(int(i))
349
+ bi = boxes[i]
350
+ xx1 = np.maximum(bi[0], boxes[:, 0])
351
+ yy1 = np.maximum(bi[1], boxes[:, 1])
352
+ xx2 = np.minimum(bi[2], boxes[:, 2])
353
+ yy2 = np.minimum(bi[3], boxes[:, 3])
354
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
355
+ a_i = max(1e-7, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
356
+ iou = inter / (a_i + areas - inter + 1e-7)
357
+ dup = iou > iou_thresh
358
+ dup[i] = False
359
+ # Never cross-suppress fire extinguisher vs fire/smoke.
360
+ dup &= ~((cls_ids == ext_cls) | (cls_ids[i] == ext_cls))
361
+ suppressed |= dup
362
+ keep_idx = np.array(keep, dtype=np.intp)
363
+ return boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx]
364
+
365
+ @staticmethod
366
+ def _max_score_per_cluster(
367
+ post_boxes: np.ndarray,
368
+ post_cls: np.ndarray,
369
+ full_boxes: np.ndarray,
370
+ full_scores: np.ndarray,
371
+ full_cls: np.ndarray,
372
+ iou_thresh: float,
373
+ ) -> np.ndarray:
374
+ """For each kept (post-NMS) box, return the max score over the FULL
375
+ candidate set among same-class boxes with IoU >= iou_thresh.
376
+
377
+ Used after horizontal-flip TTA: a high-confidence flipped detection
378
+ can raise the score of the corresponding original detection.
379
+ """
380
+ n = len(post_boxes)
381
+ if n == 0:
382
+ return np.empty(0, dtype=np.float32)
383
+ full_areas = (np.maximum(0.0, full_boxes[:, 2] - full_boxes[:, 0]) *
384
+ np.maximum(0.0, full_boxes[:, 3] - full_boxes[:, 1]))
385
+ out = np.empty(n, dtype=np.float32)
386
+ for i in range(n):
387
+ bi = post_boxes[i]
388
+ xx1 = np.maximum(bi[0], full_boxes[:, 0])
389
+ yy1 = np.maximum(bi[1], full_boxes[:, 1])
390
+ xx2 = np.minimum(bi[2], full_boxes[:, 2])
391
+ yy2 = np.minimum(bi[3], full_boxes[:, 3])
392
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
393
+ a_i = max(0.0, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
394
+ iou = inter / (a_i + full_areas - inter + 1e-7)
395
+ cluster = (iou >= iou_thresh) & (full_cls == post_cls[i])
396
+ out[i] = float(np.max(full_scores[cluster])) if np.any(cluster) else 0.0
397
+ return out
398
+
399
+ def _loose_conf_mask(
400
+ self, scores: np.ndarray, cls_ids: np.ndarray
401
+ ) -> np.ndarray:
402
+ """Pre-filter: keep candidates that could pass threshold or bonus rescue."""
403
+ floor = self._conf_thres_array[cls_ids] - self._bonus_array[cls_ids]
404
+ return scores >= floor
405
+
406
+ def _conf_filter_mask(
407
+ self, scores: np.ndarray, cls_ids: np.ndarray
408
+ ) -> np.ndarray:
409
+ """Boolean keep-mask: score >= per-class threshold, with a per-class
410
+ rescue -- admit top-1 when score >= (threshold - bonus). Runs after
411
+ sane-box filtering so tiny FPs cannot block bonus rescue."""
412
+ if len(scores) == 0:
413
+ return np.zeros(0, dtype=bool)
414
+ thr = self._conf_thres_array[cls_ids]
415
+ keep = scores >= thr
416
+ ext_cls = self._cls_fire_extinguisher
417
+ for c in np.unique(cls_ids):
418
+ b = float(self._bonus_array[c])
419
+ if b <= 0.0:
420
+ continue
421
+ cm = cls_ids == c
422
+ idx = np.where(cm)[0]
423
+ top = int(idx[int(np.argmax(scores[idx]))])
424
+ floor = float(self._conf_thres_array[c] - b)
425
+ if scores[top] < floor:
426
+ continue
427
+ if c == ext_cls:
428
+ keep[top] = True
429
+ elif not keep[cm].any():
430
+ keep[top] = True
431
+ return keep
432
+
433
+ def _filter_sane_boxes(
434
+ self,
435
+ boxes: np.ndarray,
436
+ scores: np.ndarray,
437
+ cls_ids: np.ndarray,
438
+ orig_size: tuple[int, int],
439
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
440
+ """Drop tiny / degenerate / image-spanning / extreme-AR boxes (FP)."""
441
+ if len(boxes) == 0:
442
+ return boxes, scores, cls_ids
443
+ orig_w, orig_h = orig_size
444
+ image_area = float(orig_w * orig_h)
445
+ keep = []
446
+ for i, box in enumerate(boxes):
447
+ x1, y1, x2, y2 = box.tolist()
448
+ bw = x2 - x1
449
+ bh = y2 - y1
450
+ if bw <= 0 or bh <= 0:
451
+ continue
452
+ if bw < self.min_side or bh < self.min_side:
453
+ continue
454
+ area = bw * bh
455
+ if area < self.min_box_area:
456
+ continue
457
+ if area > 0.95 * image_area:
458
+ continue
459
+ ar = max(bw / max(bh, 1e-6), bh / max(bw, 1e-6))
460
+ if ar > self.max_aspect_ratio:
461
+ continue
462
+ keep.append(i)
463
+ if not keep:
464
+ return (
465
+ np.empty((0, 4), dtype=np.float32),
466
+ np.empty((0,), dtype=np.float32),
467
+ np.empty((0,), dtype=np.int32),
468
+ )
469
+ k = np.array(keep, dtype=np.intp)
470
+ return boxes[k], scores[k], cls_ids[k]
471
+
472
+ def _per_view_pipeline(
473
+ self,
474
+ boxes: np.ndarray,
475
+ scores: np.ndarray,
476
+ cls_ids: np.ndarray,
477
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
478
+ """Per-view post-processing pipeline: per-class NMS -> nested filter -> cap -> cross-class dedup."""
479
+ if len(boxes) > 1:
480
+ keep = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
481
+ boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
482
+ boxes, scores, cls_ids = self._nested_zone_filter(
483
+ boxes, scores, cls_ids
484
+ )
485
+ if len(scores) > self.max_det:
486
+ top = np.argsort(-scores)[: self.max_det]
487
+ boxes, scores, cls_ids = boxes[top], scores[top], cls_ids[top]
488
+ if len(boxes) > 1:
489
+ boxes, scores, cls_ids = self._cross_class_dedup_op(
490
+ boxes, scores, cls_ids, self.cross_iou_thresh
491
+ )
492
+ return boxes, scores, cls_ids
493
+
494
+ @staticmethod
495
+ def _build_results(
496
+ boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray
497
+ ) -> list[BoundingBox]:
498
+ results: list[BoundingBox] = []
499
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
500
+ x1, y1, x2, y2 = box.tolist()
501
+ if x2 <= x1 or y2 <= y1:
502
+ continue
503
+ results.append(
504
+ BoundingBox(
505
+ x1=int(math.floor(x1)),
506
+ y1=int(math.floor(y1)),
507
+ x2=int(math.ceil(x2)),
508
+ y2=int(math.ceil(y2)),
509
+ cls_id=int(cls_id),
510
+ conf=float(conf),
511
+ )
512
+ )
513
+ return results
514
+
515
+ def _decode_final_dets(
516
+ self,
517
+ preds: np.ndarray,
518
+ ratio: float,
519
+ pad: tuple[float, float],
520
+ orig_size: tuple[int, int],
521
+ ) -> list[BoundingBox]:
522
+ """Final-detection output path: rows shaped [x1, y1, x2, y2, conf, cls_id]."""
523
+ if preds.ndim == 3 and preds.shape[0] == 1:
524
+ preds = preds[0]
525
+ if preds.ndim != 2 or preds.shape[1] < 6:
526
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
527
+
528
+ boxes = preds[:, :4].astype(np.float32)
529
+ scores = preds[:, 4].astype(np.float32)
530
+ cls_ids = preds[:, 5].astype(np.int32)
531
+ cls_ids = self.cls_remap[cls_ids]
532
+
533
+ keep = self._loose_conf_mask(scores, cls_ids)
534
+ boxes = boxes[keep]
535
+ scores = scores[keep]
536
+ cls_ids = cls_ids[keep]
537
+ if len(boxes) == 0:
538
+ return []
539
+
540
+ pad_w, pad_h = pad
541
+ boxes[:, [0, 2]] -= pad_w
542
+ boxes[:, [1, 3]] -= pad_h
543
+ boxes /= ratio
544
+ boxes = self._clip_boxes(boxes, orig_size)
545
+
546
+ boxes, scores, cls_ids = self._filter_sane_boxes(
547
+ boxes, scores, cls_ids, orig_size
548
+ )
549
+ if len(boxes) == 0:
550
+ return []
551
+
552
+ keep = self._conf_filter_mask(scores, cls_ids)
553
+ boxes = boxes[keep]
554
+ scores = scores[keep]
555
+ cls_ids = cls_ids[keep]
556
+ if len(boxes) == 0:
557
+ return []
558
+
559
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
560
+ return self._build_results(boxes, scores, cls_ids)
561
+
562
+ def _decode_raw_yolo(
563
+ self,
564
+ preds: np.ndarray,
565
+ ratio: float,
566
+ pad: tuple[float, float],
567
+ orig_size: tuple[int, int],
568
+ ) -> list[BoundingBox]:
569
+ """Fallback raw-YOLO output path: per-anchor class logits."""
570
+ if preds.ndim != 3 or preds.shape[0] != 1:
571
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
572
+ preds = preds[0]
573
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
574
+ preds = preds.T
575
+ if preds.ndim != 2 or preds.shape[1] < 5:
576
+ raise ValueError(f"Unexpected raw output shape: {preds.shape}")
577
+
578
+ boxes_xywh = preds[:, :4].astype(np.float32)
579
+ cls_part = preds[:, 4:].astype(np.float32)
580
+ if cls_part.shape[1] == 1:
581
+ scores = cls_part[:, 0]
582
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
583
+ else:
584
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
585
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
586
+ cls_ids = self.cls_remap[cls_ids]
587
+
588
+ keep = self._loose_conf_mask(scores, cls_ids)
589
+ boxes_xywh = boxes_xywh[keep]
590
+ scores = scores[keep]
591
+ cls_ids = cls_ids[keep]
592
+ if len(boxes_xywh) == 0:
593
+ return []
594
+ boxes = self._xywh_to_xyxy(boxes_xywh)
595
+
596
+ pad_w, pad_h = pad
597
+ boxes[:, [0, 2]] -= pad_w
598
+ boxes[:, [1, 3]] -= pad_h
599
+ boxes /= ratio
600
+ boxes = self._clip_boxes(boxes, orig_size)
601
+
602
+ boxes, scores, cls_ids = self._filter_sane_boxes(
603
+ boxes, scores, cls_ids, orig_size
604
+ )
605
+ if len(boxes) == 0:
606
+ return []
607
+
608
+ keep = self._conf_filter_mask(scores, cls_ids)
609
+ boxes = boxes[keep]
610
+ scores = scores[keep]
611
+ cls_ids = cls_ids[keep]
612
+ if len(boxes) == 0:
613
+ return []
614
+
615
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
616
+ return self._build_results(boxes, scores, cls_ids)
617
+
618
+ def _postprocess(
619
+ self,
620
+ output: np.ndarray,
621
+ ratio: float,
622
+ pad: tuple[float, float],
623
+ orig_size: tuple[int, int],
624
+ ) -> list[BoundingBox]:
625
+ if output.ndim == 2 and output.shape[1] >= 6:
626
+ return self._decode_final_dets(output, ratio, pad, orig_size)
627
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
628
+ return self._decode_final_dets(output, ratio, pad, orig_size)
629
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
630
+
631
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
632
+ if image is None:
633
+ raise ValueError("Input image is None")
634
+ if not isinstance(image, np.ndarray):
635
+ raise TypeError(f"Input is not numpy array: {type(image)}")
636
+ if image.ndim != 3:
637
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
638
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
639
+ raise ValueError(f"Invalid image shape={image.shape}")
640
+ if image.shape[2] != 3:
641
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
642
+ if image.dtype != np.uint8:
643
+ image = image.astype(np.uint8)
644
+
645
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
646
+ expected = (1, 3, self.input_height, self.input_width)
647
+ if input_tensor.shape != expected:
648
+ raise ValueError(
649
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected}"
650
+ )
651
+
652
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
653
+ return self._postprocess(outputs[0], ratio, pad, orig_size)
654
+
655
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
656
+ """Horizontal-flip TTA.
657
+
658
+ Strategy:
659
+ 1. Predict on original and on flipped image.
660
+ 2. Map flipped boxes back to original coordinates.
661
+ 3. Per-class hard NMS on the union.
662
+ 4. For each kept box, compute the max same-class score across the
663
+ FULL union (not just the post-NMS subset) -- this lets a high-
664
+ confidence flipped detection raise a borderline original one.
665
+ 5. Cross-class dedup to suppress same-physical-object multi-class.
666
+ """
667
+ boxes_orig = self._predict_single(image)
668
+ flipped = cv2.flip(image, 1)
669
+ boxes_flip = self._predict_single(flipped)
670
+ w = image.shape[1]
671
+ boxes_flip = [
672
+ BoundingBox(
673
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
674
+ cls_id=b.cls_id, conf=b.conf,
675
+ )
676
+ for b in boxes_flip
677
+ ]
678
+ all_boxes = boxes_orig + boxes_flip
679
+ if not all_boxes:
680
+ return []
681
+
682
+ coords = np.array(
683
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
684
+ )
685
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
686
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
687
+
688
+ hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
689
+ if len(hard_keep) == 0:
690
+ return []
691
+ kept_coords = coords[hard_keep]
692
+ kept_scores = scores[hard_keep]
693
+ kept_cls = cls_ids[hard_keep]
694
+ kept_coords, kept_scores, kept_cls = self._nested_zone_filter(
695
+ kept_coords, kept_scores, kept_cls
696
+ )
697
+ if len(kept_coords) == 0:
698
+ return []
699
+ if len(kept_scores) > self.max_det:
700
+ top = np.argsort(-kept_scores)[: self.max_det]
701
+ kept_coords = kept_coords[top]
702
+ kept_scores = kept_scores[top]
703
+ kept_cls = kept_cls[top]
704
+
705
+ boosted = self._max_score_per_cluster(
706
+ kept_coords, kept_cls,
707
+ coords, scores, cls_ids, self.iou_thres,
708
+ )
709
+ if len(kept_coords) > 1:
710
+ kept_coords, boosted, kept_cls = self._cross_class_dedup_op(
711
+ kept_coords, boosted, kept_cls, self.cross_iou_thresh
712
+ )
713
+
714
+ return [
715
+ BoundingBox(
716
+ x1=int(math.floor(kept_coords[j, 0])),
717
+ y1=int(math.floor(kept_coords[j, 1])),
718
+ x2=int(math.ceil(kept_coords[j, 2])),
719
+ y2=int(math.ceil(kept_coords[j, 3])),
720
+ cls_id=int(kept_cls[j]),
721
+ conf=float(boosted[j]),
722
+ )
723
+ for j in range(len(kept_coords))
724
+ ]
725
+
726
+ def predict_batch(
727
+ self,
728
+ batch_images: list[ndarray],
729
+ offset: int,
730
+ n_keypoints: int,
731
+ ) -> list[TVFrameResult]:
732
+ results: list[TVFrameResult] = []
733
+ for frame_number_in_batch, image in enumerate(batch_images):
734
+ try:
735
+ if self.use_tta:
736
+ boxes = self._predict_tta(image)
737
+ else:
738
+ boxes = self._predict_single(image)
739
+ except Exception as e:
740
+ print(
741
+ f"⚠️ Inference failed for frame "
742
+ f"{offset + frame_number_in_batch}: {e}"
743
+ )
744
+ boxes = []
745
+ results.append(
746
+ TVFrameResult(
747
+ frame_id=offset + frame_number_in_batch,
748
+ boxes=boxes,
749
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
750
+ )
751
+ )
752
+ return results