alfred8995 commited on
Commit
f0c79b7
·
verified ·
1 Parent(s): 6215877

Upload folder using huggingface_hub

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