alfred8995 commited on
Commit
cca83ef
·
verified ·
1 Parent(s): bd4b22c

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