coolroman commited on
Commit
fff6e44
·
verified ·
1 Parent(s): 20f5447

scorevision: push artifact

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