alfred8995 commited on
Commit
e57d748
·
verified ·
1 Parent(s): b54ee81

Upload folder using huggingface_hub

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