alfred8995 commited on
Commit
becc354
·
verified ·
1 Parent(s): fc6287e

Upload folder using huggingface_hub

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