coolroman commited on
Commit
17bc6c3
·
verified ·
1 Parent(s): ce4d26c

firenet v3: yolo26s trained on ensemble GT (SAM3 + leaked) - backtest +0.024

Browse files
Files changed (4) hide show
  1. __pycache__/miner.cpython-310.pyc +0 -0
  2. chute_config.yml +20 -0
  3. miner.py +732 -0
  4. weights.onnx +3 -0
__pycache__/miner.cpython-310.pyc ADDED
Binary file (21.4 kB). View file
 
chute_config.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Image:
2
+ from_base: parachutes/python:3.12
3
+ run_command:
4
+ - pip install --upgrade setuptools wheel
5
+ - pip install 'numpy>=1.23' 'onnxruntime-gpu[cuda,cudnn]>=1.16' 'opencv-python>=4.7' 'pillow>=9.5' 'huggingface_hub>=0.19.4' 'pydantic>=2.0' 'pyyaml>=6.0' 'aiohttp>=3.9'
6
+ - pip install torch torchvision
7
+
8
+ NodeSelector:
9
+ gpu_count: 1
10
+ min_vram_gb_per_gpu: 16
11
+ include:
12
+ - pro_6000
13
+
14
+ Chute:
15
+ timeout_seconds: 900
16
+ concurrency: 4
17
+ max_instances: 5
18
+ scaling_threshold: 0.5
19
+ shutdown_after_seconds: 288000
20
+ tee: true
miner.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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."""
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
+ return boxes, scores, cls_ids
473
+
474
+ @staticmethod
475
+ def _build_results(
476
+ boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray
477
+ ) -> list[BoundingBox]:
478
+ results: list[BoundingBox] = []
479
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
480
+ x1, y1, x2, y2 = box.tolist()
481
+ if x2 <= x1 or y2 <= y1:
482
+ continue
483
+ results.append(
484
+ BoundingBox(
485
+ x1=int(math.floor(x1)),
486
+ y1=int(math.floor(y1)),
487
+ x2=int(math.ceil(x2)),
488
+ y2=int(math.ceil(y2)),
489
+ cls_id=int(cls_id),
490
+ conf=float(conf),
491
+ )
492
+ )
493
+ return results
494
+
495
+ def _decode_final_dets(
496
+ self,
497
+ preds: np.ndarray,
498
+ ratio: float,
499
+ pad: tuple[float, float],
500
+ orig_size: tuple[int, int],
501
+ ) -> list[BoundingBox]:
502
+ """Final-detection output path: rows shaped [x1, y1, x2, y2, conf, cls_id]."""
503
+ if preds.ndim == 3 and preds.shape[0] == 1:
504
+ preds = preds[0]
505
+ if preds.ndim != 2 or preds.shape[1] < 6:
506
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
507
+
508
+ boxes = preds[:, :4].astype(np.float32)
509
+ scores = preds[:, 4].astype(np.float32)
510
+ cls_ids = preds[:, 5].astype(np.int32)
511
+ cls_ids = self.cls_remap[cls_ids]
512
+
513
+ keep = self._loose_conf_mask(scores, cls_ids)
514
+ boxes = boxes[keep]
515
+ scores = scores[keep]
516
+ cls_ids = cls_ids[keep]
517
+ if len(boxes) == 0:
518
+ return []
519
+
520
+ pad_w, pad_h = pad
521
+ boxes[:, [0, 2]] -= pad_w
522
+ boxes[:, [1, 3]] -= pad_h
523
+ boxes /= ratio
524
+ boxes = self._clip_boxes(boxes, orig_size)
525
+
526
+ boxes, scores, cls_ids = self._filter_sane_boxes(
527
+ boxes, scores, cls_ids, orig_size
528
+ )
529
+ if len(boxes) == 0:
530
+ return []
531
+
532
+ keep = self._conf_filter_mask(scores, cls_ids)
533
+ boxes = boxes[keep]
534
+ scores = scores[keep]
535
+ cls_ids = cls_ids[keep]
536
+ if len(boxes) == 0:
537
+ return []
538
+
539
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
540
+ return self._build_results(boxes, scores, cls_ids)
541
+
542
+ def _decode_raw_yolo(
543
+ self,
544
+ preds: np.ndarray,
545
+ ratio: float,
546
+ pad: tuple[float, float],
547
+ orig_size: tuple[int, int],
548
+ ) -> list[BoundingBox]:
549
+ """Fallback raw-YOLO output path: per-anchor class logits."""
550
+ if preds.ndim != 3 or preds.shape[0] != 1:
551
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
552
+ preds = preds[0]
553
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
554
+ preds = preds.T
555
+ if preds.ndim != 2 or preds.shape[1] < 5:
556
+ raise ValueError(f"Unexpected raw output shape: {preds.shape}")
557
+
558
+ boxes_xywh = preds[:, :4].astype(np.float32)
559
+ cls_part = preds[:, 4:].astype(np.float32)
560
+ if cls_part.shape[1] == 1:
561
+ scores = cls_part[:, 0]
562
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
563
+ else:
564
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
565
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
566
+ cls_ids = self.cls_remap[cls_ids]
567
+
568
+ keep = self._loose_conf_mask(scores, cls_ids)
569
+ boxes_xywh = boxes_xywh[keep]
570
+ scores = scores[keep]
571
+ cls_ids = cls_ids[keep]
572
+ if len(boxes_xywh) == 0:
573
+ return []
574
+ boxes = self._xywh_to_xyxy(boxes_xywh)
575
+
576
+ pad_w, pad_h = pad
577
+ boxes[:, [0, 2]] -= pad_w
578
+ boxes[:, [1, 3]] -= pad_h
579
+ boxes /= ratio
580
+ boxes = self._clip_boxes(boxes, orig_size)
581
+
582
+ boxes, scores, cls_ids = self._filter_sane_boxes(
583
+ boxes, scores, cls_ids, orig_size
584
+ )
585
+ if len(boxes) == 0:
586
+ return []
587
+
588
+ keep = self._conf_filter_mask(scores, cls_ids)
589
+ boxes = boxes[keep]
590
+ scores = scores[keep]
591
+ cls_ids = cls_ids[keep]
592
+ if len(boxes) == 0:
593
+ return []
594
+
595
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
596
+ return self._build_results(boxes, scores, cls_ids)
597
+
598
+ def _postprocess(
599
+ self,
600
+ output: np.ndarray,
601
+ ratio: float,
602
+ pad: tuple[float, float],
603
+ orig_size: tuple[int, int],
604
+ ) -> list[BoundingBox]:
605
+ if output.ndim == 2 and output.shape[1] >= 6:
606
+ return self._decode_final_dets(output, ratio, pad, orig_size)
607
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
608
+ return self._decode_final_dets(output, ratio, pad, orig_size)
609
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
610
+
611
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
612
+ if image is None:
613
+ raise ValueError("Input image is None")
614
+ if not isinstance(image, np.ndarray):
615
+ raise TypeError(f"Input is not numpy array: {type(image)}")
616
+ if image.ndim != 3:
617
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
618
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
619
+ raise ValueError(f"Invalid image shape={image.shape}")
620
+ if image.shape[2] != 3:
621
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
622
+ if image.dtype != np.uint8:
623
+ image = image.astype(np.uint8)
624
+
625
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
626
+ expected = (1, 3, self.input_height, self.input_width)
627
+ if input_tensor.shape != expected:
628
+ raise ValueError(
629
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected}"
630
+ )
631
+
632
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
633
+ return self._postprocess(outputs[0], ratio, pad, orig_size)
634
+
635
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
636
+ """Horizontal-flip TTA.
637
+
638
+ Strategy:
639
+ 1. Predict on original and on flipped image.
640
+ 2. Map flipped boxes back to original coordinates.
641
+ 3. Per-class hard NMS on the union.
642
+ 4. For each kept box, compute the max same-class score across the
643
+ FULL union (not just the post-NMS subset) -- this lets a high-
644
+ confidence flipped detection raise a borderline original one.
645
+ 5. Cross-class dedup to suppress same-physical-object multi-class.
646
+ """
647
+ boxes_orig = self._predict_single(image)
648
+ flipped = cv2.flip(image, 1)
649
+ boxes_flip = self._predict_single(flipped)
650
+ w = image.shape[1]
651
+ boxes_flip = [
652
+ BoundingBox(
653
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
654
+ cls_id=b.cls_id, conf=b.conf,
655
+ )
656
+ for b in boxes_flip
657
+ ]
658
+ all_boxes = boxes_orig + boxes_flip
659
+ if not all_boxes:
660
+ return []
661
+
662
+ coords = np.array(
663
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
664
+ )
665
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
666
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
667
+
668
+ hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
669
+ if len(hard_keep) == 0:
670
+ return []
671
+ kept_coords = coords[hard_keep]
672
+ kept_scores = scores[hard_keep]
673
+ kept_cls = cls_ids[hard_keep]
674
+ kept_coords, kept_scores, kept_cls = self._nested_zone_filter(
675
+ kept_coords, kept_scores, kept_cls
676
+ )
677
+ if len(kept_coords) == 0:
678
+ return []
679
+ if len(kept_scores) > self.max_det:
680
+ top = np.argsort(-kept_scores)[: self.max_det]
681
+ kept_coords = kept_coords[top]
682
+ kept_scores = kept_scores[top]
683
+ kept_cls = kept_cls[top]
684
+
685
+ boosted = self._max_score_per_cluster(
686
+ kept_coords, kept_cls,
687
+ coords, scores, cls_ids, self.iou_thres,
688
+ )
689
+ if len(kept_coords) > 1:
690
+ kept_coords, boosted, kept_cls = self._cross_class_dedup_op(
691
+ kept_coords, boosted, kept_cls, self.cross_iou_thresh
692
+ )
693
+
694
+ return [
695
+ BoundingBox(
696
+ x1=int(math.floor(kept_coords[j, 0])),
697
+ y1=int(math.floor(kept_coords[j, 1])),
698
+ x2=int(math.ceil(kept_coords[j, 2])),
699
+ y2=int(math.ceil(kept_coords[j, 3])),
700
+ cls_id=int(kept_cls[j]),
701
+ conf=float(boosted[j]),
702
+ )
703
+ for j in range(len(kept_coords))
704
+ ]
705
+
706
+ def predict_batch(
707
+ self,
708
+ batch_images: list[ndarray],
709
+ offset: int,
710
+ n_keypoints: int,
711
+ ) -> list[TVFrameResult]:
712
+ results: list[TVFrameResult] = []
713
+ for frame_number_in_batch, image in enumerate(batch_images):
714
+ try:
715
+ if self.use_tta:
716
+ boxes = self._predict_tta(image)
717
+ else:
718
+ boxes = self._predict_single(image)
719
+ except Exception as e:
720
+ print(
721
+ f"⚠️ Inference failed for frame "
722
+ f"{offset + frame_number_in_batch}: {e}"
723
+ )
724
+ boxes = []
725
+ results.append(
726
+ TVFrameResult(
727
+ frame_id=offset + frame_number_in_batch,
728
+ boxes=boxes,
729
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
730
+ )
731
+ )
732
+ return results
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0de4cb192841274c319b250b7ab16e015905f76a3643ac22e9a61cac9f650d75
3
+ size 19300240