fitleech commited on
Commit
8d18d47
·
verified ·
1 Parent(s): 7ebe2c6

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. chute_config.yml +20 -0
  2. miner.py +854 -0
  3. weights.onnx +3 -0
chute_config.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Image:
2
+ from_base: parachutes/python:3.12
3
+ run_command:
4
+ - pip install --upgrade setuptools wheel
5
+ - pip install 'numpy>=1.23' 'onnxruntime-gpu[cuda,cudnn]>=1.16' 'opencv-python>=4.7' 'pillow>=9.5' 'huggingface_hub>=0.19.4' 'pydantic>=2.0' 'pyyaml>=6.0' 'aiohttp>=3.9'
6
+ - pip install torch torchvision
7
+
8
+ NodeSelector:
9
+ gpu_count: 1
10
+ max_hourly_price_per_gpu: 2
11
+ include:
12
+ - pro_6000
13
+
14
+ Chute:
15
+ tee: true
16
+ timeout_seconds: 900
17
+ concurrency: 4
18
+ max_instances: 5
19
+ scaling_threshold: 0.5
20
+ shutdown_after_seconds: 288000
miner.py ADDED
@@ -0,0 +1,854 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import math
3
+ from typing import Any
4
+
5
+ import cv2
6
+ import numpy as np
7
+ import onnxruntime as ort
8
+ from numpy import ndarray
9
+ from pydantic import BaseModel
10
+
11
+ # Profile 002-001: aligned with miner_script/002/miner.py for identical no-sweep
12
+ # outputs (beverage cup/bottle/can). Fork __init__ thresholds only when freezing
13
+ # a sweep-best snapshot.
14
+
15
+
16
+ class BoundingBox(BaseModel):
17
+ x1: int
18
+ y1: int
19
+ x2: int
20
+ y2: int
21
+ cls_id: int
22
+ conf: float
23
+
24
+
25
+ class TVFrameResult(BaseModel):
26
+ frame_id: int
27
+ boxes: list[BoundingBox]
28
+ keypoints: list[tuple[int, int]]
29
+
30
+
31
+ class Miner:
32
+ def __init__(self, path_hf_repo: Path) -> None:
33
+ model_path = path_hf_repo / "weights.onnx"
34
+
35
+ # Canonical class indices (validator / PGT / manifest); match dataset.yaml names order.
36
+ # Beverage element: cup=0, bottle=1, can=2 (see evaluations_6 dataset.yaml).
37
+ self.class_names = ['cup', 'bottle', 'can']
38
+ # ONNX class index order from training export (Ultralytics names 0..2 in dataset.yaml).
39
+ model_class_order = ['cup', 'bottle', 'can']
40
+ self._train_cls_to_canonical = np.array(
41
+ [self.class_names.index(n) for n in model_class_order],
42
+ dtype=np.int32
43
+ )
44
+ print("ORT version:", ort.__version__)
45
+
46
+ try:
47
+ ort.preload_dlls()
48
+ print("✅ onnxruntime.preload_dlls() success")
49
+ except Exception as e:
50
+ print(f"⚠️ preload_dlls failed: {e}")
51
+
52
+ print("ORT available providers BEFORE session:", ort.get_available_providers())
53
+
54
+ sess_options = ort.SessionOptions()
55
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
56
+
57
+ try:
58
+ self.session = ort.InferenceSession(
59
+ str(model_path),
60
+ sess_options=sess_options,
61
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
62
+ )
63
+ print("✅ Created ORT session with preferred CUDA provider list")
64
+ except Exception as e:
65
+ print(f"⚠️ CUDA session creation failed, falling back to CPU: {e}")
66
+ self.session = ort.InferenceSession(
67
+ str(model_path),
68
+ sess_options=sess_options,
69
+ providers=["CPUExecutionProvider"],
70
+ )
71
+
72
+ print("ORT session providers:", self.session.get_providers())
73
+
74
+ for inp in self.session.get_inputs():
75
+ print("INPUT:", inp.name, inp.shape, inp.type)
76
+
77
+ for out in self.session.get_outputs():
78
+ print("OUTPUT:", out.name, out.shape, out.type)
79
+
80
+ self.input_name = self.session.get_inputs()[0].name
81
+ self.output_names = [output.name for output in self.session.get_outputs()]
82
+ self.input_shape = self.session.get_inputs()[0].shape
83
+
84
+ self.input_height = self._safe_dim(self.input_shape[2], default=1280)
85
+ self.input_width = self._safe_dim(self.input_shape[3], default=1280)
86
+
87
+ # ---------- Scoring-oriented thresholds (beverage: cup / bottle / can) ----------
88
+ # Beverage objects are typically rigid containers with moderate confidence
89
+ # peaks. Start a touch higher than vehicle/petrol to suppress soft junk.
90
+ self.conf_thres = 0.35
91
+
92
+ # Above this on orig view, accept directly. Below it, require TTA agreement.
93
+ self.conf_high = 0.80
94
+
95
+ # Standard NMS IoU; beverage instances rarely heavily overlap so 0.50 is fine.
96
+ self.iou_thres = 0.19
97
+
98
+ # Beverage objects barely shift between original and h-flipped view, but the
99
+ # detector confidence can ping-pong; a moderate IoU gate is right.
100
+ self.tta_match_iou = 0.00
101
+
102
+ self.max_det = 150
103
+ self.use_tta = True
104
+
105
+ # Box sanity filters tuned for beverage:
106
+ # - cups / bottles / cans are usually >=12 px on the short side in real shots
107
+ # - aspect ratio: bottles are tall (h/w up to ~4); cans/cups closer to square
108
+ self.min_box_area = 12 * 12
109
+ self.min_w = 6
110
+ self.min_h = 6
111
+ self.max_aspect_ratio = 5.0
112
+ self.max_box_area_ratio = 0.85
113
+
114
+ print(f"✅ ONNX model loaded from: {model_path}")
115
+ print(f"✅ ONNX providers: {self.session.get_providers()}")
116
+ print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
117
+
118
+ def __repr__(self) -> str:
119
+ return (
120
+ f"ONNXRuntime(session={type(self.session).__name__}, "
121
+ f"providers={self.session.get_providers()})"
122
+ )
123
+
124
+ @staticmethod
125
+ def _safe_dim(value, default: int) -> int:
126
+ return value if isinstance(value, int) and value > 0 else default
127
+
128
+ def _remap_train_cls_ids(self, cls_ids: np.ndarray) -> np.ndarray:
129
+ idx = np.clip(cls_ids.astype(np.int64, copy=False), 0, len(self._train_cls_to_canonical) - 1)
130
+ return self._train_cls_to_canonical[idx]
131
+
132
+ def _letterbox(
133
+ self,
134
+ image: ndarray,
135
+ new_shape: tuple[int, int],
136
+ color=(114, 114, 114),
137
+ ) -> tuple[ndarray, float, tuple[float, float]]:
138
+ h, w = image.shape[:2]
139
+ new_w, new_h = new_shape
140
+
141
+ ratio = min(new_w / w, new_h / h)
142
+ resized_w = int(round(w * ratio))
143
+ resized_h = int(round(h * ratio))
144
+
145
+ if (resized_w, resized_h) != (w, h):
146
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
147
+ image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
148
+
149
+ dw = new_w - resized_w
150
+ dh = new_h - resized_h
151
+ dw /= 2.0
152
+ dh /= 2.0
153
+
154
+ left = int(round(dw - 0.1))
155
+ right = int(round(dw + 0.1))
156
+ top = int(round(dh - 0.1))
157
+ bottom = int(round(dh + 0.1))
158
+
159
+ padded = cv2.copyMakeBorder(
160
+ image,
161
+ top,
162
+ bottom,
163
+ left,
164
+ right,
165
+ borderType=cv2.BORDER_CONSTANT,
166
+ value=color,
167
+ )
168
+ return padded, ratio, (dw, dh)
169
+
170
+ def _preprocess(
171
+ self, image: ndarray
172
+ ) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
173
+ orig_h, orig_w = image.shape[:2]
174
+
175
+ img, ratio, pad = self._letterbox(
176
+ image, (self.input_width, self.input_height)
177
+ )
178
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
179
+ img = img.astype(np.float32) / 255.0
180
+ img = np.transpose(img, (2, 0, 1))[None, ...]
181
+ img = np.ascontiguousarray(img, dtype=np.float32)
182
+
183
+ return img, ratio, pad, (orig_w, orig_h)
184
+
185
+ @staticmethod
186
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
187
+ w, h = image_size
188
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
189
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
190
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
191
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
192
+ return boxes
193
+
194
+ @staticmethod
195
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
196
+ out = np.empty_like(boxes)
197
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
198
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
199
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
200
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
201
+ return out
202
+
203
+ @staticmethod
204
+ def _hard_nms(
205
+ boxes: np.ndarray,
206
+ scores: np.ndarray,
207
+ iou_thresh: float,
208
+ ) -> np.ndarray:
209
+ if len(boxes) == 0:
210
+ return np.array([], dtype=np.intp)
211
+
212
+ boxes = np.asarray(boxes, dtype=np.float32)
213
+ scores = np.asarray(scores, dtype=np.float32)
214
+ order = np.argsort(scores)[::-1]
215
+ keep = []
216
+
217
+ while len(order) > 0:
218
+ i = order[0]
219
+ keep.append(i)
220
+ if len(order) == 1:
221
+ break
222
+
223
+ rest = order[1:]
224
+
225
+ xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
226
+ yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
227
+ xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
228
+ yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
229
+
230
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
231
+
232
+ area_i = np.maximum(0.0, (boxes[i, 2] - boxes[i, 0])) * np.maximum(0.0, (boxes[i, 3] - boxes[i, 1]))
233
+ area_r = np.maximum(0.0, (boxes[rest, 2] - boxes[rest, 0])) * np.maximum(0.0, (boxes[rest, 3] - boxes[rest, 1]))
234
+
235
+ iou = inter / (area_i + area_r - inter + 1e-7)
236
+ order = rest[iou <= iou_thresh]
237
+
238
+ return np.array(keep, dtype=np.intp)
239
+
240
+ @classmethod
241
+ def _nms_per_class(
242
+ cls,
243
+ boxes: np.ndarray,
244
+ scores: np.ndarray,
245
+ cls_ids: np.ndarray,
246
+ iou_thresh: float,
247
+ max_det: int,
248
+ ) -> np.ndarray:
249
+ """NMS within each class so overlapping predictions of different classes are not merged away."""
250
+ if len(boxes) == 0:
251
+ return np.array([], dtype=np.intp)
252
+ keep_all: list[int] = []
253
+ for c in np.unique(cls_ids):
254
+ idxs = np.nonzero(cls_ids == c)[0]
255
+ if len(idxs) == 0:
256
+ continue
257
+ local_keep = cls._hard_nms(boxes[idxs], scores[idxs], iou_thresh)
258
+ keep_all.extend(idxs[local_keep].tolist())
259
+ keep_all = np.array(keep_all, dtype=np.intp)
260
+ order = np.argsort(scores[keep_all])[::-1]
261
+ return keep_all[order[:max_det]]
262
+
263
+ @staticmethod
264
+ def _box_iou_one_to_many(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:
265
+ xx1 = np.maximum(box[0], boxes[:, 0])
266
+ yy1 = np.maximum(box[1], boxes[:, 1])
267
+ xx2 = np.minimum(box[2], boxes[:, 2])
268
+ yy2 = np.minimum(box[3], boxes[:, 3])
269
+
270
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
271
+
272
+ area_a = max(0.0, (box[2] - box[0]) * (box[3] - box[1]))
273
+ area_b = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
274
+
275
+ return inter / (area_a + area_b - inter + 1e-7)
276
+
277
+ def _filter_sane_boxes(
278
+ self,
279
+ boxes: np.ndarray,
280
+ scores: np.ndarray,
281
+ cls_ids: np.ndarray,
282
+ orig_size: tuple[int, int],
283
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
284
+ if len(boxes) == 0:
285
+ return boxes, scores, cls_ids
286
+
287
+ orig_w, orig_h = orig_size
288
+ image_area = float(orig_w * orig_h)
289
+
290
+ keep = []
291
+ for i, box in enumerate(boxes):
292
+ x1, y1, x2, y2 = box.tolist()
293
+ bw = x2 - x1
294
+ bh = y2 - y1
295
+
296
+ if bw <= 0 or bh <= 0:
297
+ continue
298
+ if bw < self.min_w or bh < self.min_h:
299
+ continue
300
+
301
+ area = bw * bh
302
+ if area < self.min_box_area:
303
+ continue
304
+ if area > self.max_box_area_ratio * image_area:
305
+ continue
306
+
307
+ ar = max(bw / max(bh, 1e-6), bh / max(bw, 1e-6))
308
+ if ar > self.max_aspect_ratio:
309
+ continue
310
+
311
+ keep.append(i)
312
+
313
+ if not keep:
314
+ return (
315
+ np.empty((0, 4), dtype=np.float32),
316
+ np.empty((0,), dtype=np.float32),
317
+ np.empty((0,), dtype=np.int32),
318
+ )
319
+
320
+ keep = np.array(keep, dtype=np.intp)
321
+ return boxes[keep], scores[keep], cls_ids[keep]
322
+
323
+ def _decode_final_dets(
324
+ self,
325
+ preds: np.ndarray,
326
+ ratio: float,
327
+ pad: tuple[float, float],
328
+ orig_size: tuple[int, int],
329
+ ) -> list[BoundingBox]:
330
+ if preds.ndim == 3 and preds.shape[0] == 1:
331
+ preds = preds[0]
332
+
333
+ if preds.ndim != 2 or preds.shape[1] < 6:
334
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
335
+
336
+ boxes = preds[:, :4].astype(np.float32)
337
+ scores = preds[:, 4].astype(np.float32)
338
+ cls_ids = self._remap_train_cls_ids(preds[:, 5].astype(np.int32))
339
+ # Multi-class beverage: cup / bottle / can (see self.class_names).
340
+
341
+ # candidate threshold
342
+ keep = scores >= self.conf_thres
343
+ boxes = boxes[keep]
344
+ scores = scores[keep]
345
+ cls_ids = cls_ids[keep]
346
+
347
+ if len(boxes) == 0:
348
+ return []
349
+
350
+ pad_w, pad_h = pad
351
+ orig_w, orig_h = orig_size
352
+
353
+ boxes[:, [0, 2]] -= pad_w
354
+ boxes[:, [1, 3]] -= pad_h
355
+ boxes /= ratio
356
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
357
+
358
+ boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
359
+ if len(boxes) == 0:
360
+ return []
361
+
362
+ keep_idx = self._nms_per_class(
363
+ boxes, scores, cls_ids, self.iou_thres, self.max_det
364
+ )
365
+
366
+ boxes = boxes[keep_idx]
367
+ scores = scores[keep_idx]
368
+ cls_ids = cls_ids[keep_idx]
369
+
370
+ return [
371
+ BoundingBox(
372
+ x1=int(math.floor(box[0])),
373
+ y1=int(math.floor(box[1])),
374
+ x2=int(math.ceil(box[2])),
375
+ y2=int(math.ceil(box[3])),
376
+ cls_id=int(cls_id),
377
+ conf=float(conf),
378
+ )
379
+ for box, conf, cls_id in zip(boxes, scores, cls_ids)
380
+ if box[2] > box[0] and box[3] > box[1]
381
+ ]
382
+
383
+ def _decode_raw_yolo(
384
+ self,
385
+ preds: np.ndarray,
386
+ ratio: float,
387
+ pad: tuple[float, float],
388
+ orig_size: tuple[int, int],
389
+ ) -> list[BoundingBox]:
390
+ if preds.ndim != 3:
391
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
392
+ if preds.shape[0] != 1:
393
+ raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
394
+
395
+ preds = preds[0]
396
+
397
+ # Normalize to [N, C]
398
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
399
+ preds = preds.T
400
+
401
+ if preds.ndim != 2 or preds.shape[1] < 5:
402
+ raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
403
+
404
+ boxes_xywh = preds[:, :4].astype(np.float32)
405
+ tail = preds[:, 4:].astype(np.float32)
406
+
407
+ # Supports:
408
+ # [x,y,w,h,score] single-class
409
+ # [x,y,w,h,obj,cls] YOLO standard single-class
410
+ # [x,y,w,h,obj,cls1,cls2,...] multi-class
411
+ if tail.shape[1] == 1:
412
+ scores = tail[:, 0]
413
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
414
+ elif tail.shape[1] == 2:
415
+ obj = tail[:, 0]
416
+ cls_prob = tail[:, 1]
417
+ scores = obj * cls_prob
418
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
419
+ else:
420
+ obj = tail[:, 0]
421
+ class_probs = tail[:, 1:]
422
+ cls_ids = np.argmax(class_probs, axis=1).astype(np.int32)
423
+ cls_scores = class_probs[np.arange(len(class_probs)), cls_ids]
424
+ scores = obj * cls_scores
425
+
426
+ cls_ids = self._remap_train_cls_ids(cls_ids)
427
+
428
+ keep = scores >= self.conf_thres
429
+ boxes_xywh = boxes_xywh[keep]
430
+ scores = scores[keep]
431
+ cls_ids = cls_ids[keep]
432
+
433
+ if len(boxes_xywh) == 0:
434
+ return []
435
+
436
+ boxes = self._xywh_to_xyxy(boxes_xywh)
437
+
438
+ pad_w, pad_h = pad
439
+ orig_w, orig_h = orig_size
440
+
441
+ boxes[:, [0, 2]] -= pad_w
442
+ boxes[:, [1, 3]] -= pad_h
443
+ boxes /= ratio
444
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
445
+
446
+ boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
447
+ if len(boxes) == 0:
448
+ return []
449
+
450
+ keep_idx = self._nms_per_class(
451
+ boxes, scores, cls_ids, self.iou_thres, self.max_det
452
+ )
453
+
454
+ boxes = boxes[keep_idx]
455
+ scores = scores[keep_idx]
456
+ cls_ids = cls_ids[keep_idx]
457
+
458
+ return [
459
+ BoundingBox(
460
+ x1=int(math.floor(box[0])),
461
+ y1=int(math.floor(box[1])),
462
+ x2=int(math.ceil(box[2])),
463
+ y2=int(math.ceil(box[3])),
464
+ cls_id=int(cls_id),
465
+ conf=float(conf),
466
+ )
467
+ for box, conf, cls_id in zip(boxes, scores, cls_ids)
468
+ if box[2] > box[0] and box[3] > box[1]
469
+ ]
470
+
471
+ def _postprocess(
472
+ self,
473
+ output: np.ndarray,
474
+ ratio: float,
475
+ pad: tuple[float, float],
476
+ orig_size: tuple[int, int],
477
+ ) -> list[BoundingBox]:
478
+ if output.ndim == 2 and output.shape[1] >= 6:
479
+ return self._decode_final_dets(output, ratio, pad, orig_size)
480
+
481
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] >= 6:
482
+ return self._decode_final_dets(output, ratio, pad, orig_size)
483
+
484
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
485
+
486
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
487
+ if image is None:
488
+ raise ValueError("Input image is None")
489
+ if not isinstance(image, np.ndarray):
490
+ raise TypeError(f"Input is not numpy array: {type(image)}")
491
+ if image.ndim != 3:
492
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
493
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
494
+ raise ValueError(f"Invalid image shape={image.shape}")
495
+ if image.shape[2] != 3:
496
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
497
+
498
+ if image.dtype != np.uint8:
499
+ image = image.astype(np.uint8)
500
+
501
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
502
+
503
+ expected_shape = (1, 3, self.input_height, self.input_width)
504
+ if input_tensor.shape != expected_shape:
505
+ raise ValueError(
506
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}"
507
+ )
508
+
509
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
510
+ det_output = outputs[0]
511
+ return self._postprocess(det_output, ratio, pad, orig_size)
512
+
513
+ def _merge_tta_consensus(
514
+ self,
515
+ boxes_orig: list[BoundingBox],
516
+ boxes_flip: list[BoundingBox],
517
+ *,
518
+ conf_high: float | None = None,
519
+ tta_match_iou: float | None = None,
520
+ iou_thres: float | None = None,
521
+ ) -> list[BoundingBox]:
522
+ """
523
+ Keep:
524
+ - any box with conf >= conf_high
525
+ - low/medium-conf boxes only if confirmed across TTA views
526
+ Then run final hard NMS.
527
+
528
+ All thresholds default to the instance attributes when not supplied,
529
+ so the non-sweep path can call this without args. The sweep path
530
+ passes explicit values to avoid mutating shared state across
531
+ parameter combinations (and to be safe under any future concurrency).
532
+ """
533
+ ch = float(conf_high) if conf_high is not None else float(self.conf_high)
534
+ tm = float(tta_match_iou) if tta_match_iou is not None else float(self.tta_match_iou)
535
+ ih = float(iou_thres) if iou_thres is not None else float(self.iou_thres)
536
+
537
+ if not boxes_orig and not boxes_flip:
538
+ return []
539
+
540
+ coords_o = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0, 4), dtype=np.float32)
541
+ scores_o = np.array([b.conf for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0,), dtype=np.float32)
542
+ cls_o = np.array([b.cls_id for b in boxes_orig], dtype=np.int32) if boxes_orig else np.empty((0,), dtype=np.int32)
543
+
544
+ coords_f = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0, 4), dtype=np.float32)
545
+ scores_f = np.array([b.conf for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0,), dtype=np.float32)
546
+ cls_f = np.array([b.cls_id for b in boxes_flip], dtype=np.int32) if boxes_flip else np.empty((0,), dtype=np.int32)
547
+
548
+ accepted_boxes = []
549
+ accepted_scores = []
550
+ accepted_cls = []
551
+
552
+ # Original view candidates
553
+ for i in range(len(coords_o)):
554
+ score = scores_o[i]
555
+ if score >= ch:
556
+ accepted_boxes.append(coords_o[i])
557
+ accepted_scores.append(score)
558
+ accepted_cls.append(int(cls_o[i]))
559
+ elif len(coords_f) > 0:
560
+ ious = self._box_iou_one_to_many(coords_o[i], coords_f)
561
+ j = int(np.argmax(ious))
562
+ if ious[j] >= tm:
563
+ fused_score = max(score, scores_f[j])
564
+ accepted_boxes.append(coords_o[i])
565
+ accepted_scores.append(fused_score)
566
+ accepted_cls.append(int(cls_o[i]))
567
+
568
+ # Flipped-view high-confidence boxes that original missed
569
+ for i in range(len(coords_f)):
570
+ score = scores_f[i]
571
+ if score < ch:
572
+ continue
573
+
574
+ if len(coords_o) == 0:
575
+ accepted_boxes.append(coords_f[i])
576
+ accepted_scores.append(score)
577
+ accepted_cls.append(int(cls_f[i]))
578
+ continue
579
+
580
+ ious = self._box_iou_one_to_many(coords_f[i], coords_o)
581
+ if np.max(ious) < tm:
582
+ accepted_boxes.append(coords_f[i])
583
+ accepted_scores.append(score)
584
+ accepted_cls.append(int(cls_f[i]))
585
+
586
+ if not accepted_boxes:
587
+ return []
588
+
589
+ boxes = np.array(accepted_boxes, dtype=np.float32)
590
+ scores = np.array(accepted_scores, dtype=np.float32)
591
+ cls_ids = np.array(accepted_cls, dtype=np.int32)
592
+
593
+ keep = self._nms_per_class(boxes, scores, cls_ids, ih, self.max_det)
594
+
595
+ out = []
596
+ for idx in keep:
597
+ x1, y1, x2, y2 = boxes[idx].tolist()
598
+ out.append(
599
+ BoundingBox(
600
+ x1=int(math.floor(x1)),
601
+ y1=int(math.floor(y1)),
602
+ x2=int(math.ceil(x2)),
603
+ y2=int(math.ceil(y2)),
604
+ cls_id=int(cls_ids[idx]),
605
+ conf=float(scores[idx]),
606
+ )
607
+ )
608
+ return out
609
+
610
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
611
+ boxes_orig = self._predict_single(image)
612
+
613
+ flipped = cv2.flip(image, 1)
614
+ boxes_flip_raw = self._predict_single(flipped)
615
+
616
+ w = image.shape[1]
617
+ boxes_flip = [
618
+ BoundingBox(
619
+ x1=w - b.x2,
620
+ y1=b.y1,
621
+ x2=w - b.x1,
622
+ y2=b.y2,
623
+ cls_id=b.cls_id,
624
+ conf=b.conf,
625
+ )
626
+ for b in boxes_flip_raw
627
+ ]
628
+
629
+ return self._merge_tta_consensus(boxes_orig, boxes_flip)
630
+
631
+ # --- Fast sweep: two ONNX runs per image, then CPU-only threshold / NMS / TTA merge ---
632
+ # Must be <= the smallest conf_thres any sweep will try, otherwise the sweep silently
633
+ # caps the effective threshold and reported "best" params won't reproduce in non-sweep.
634
+ SWEEP_CONF_FLOOR = 0.0
635
+
636
+ def _final_dets_to_arrays_no_nms(
637
+ self,
638
+ preds: np.ndarray,
639
+ ratio: float,
640
+ pad: tuple[float, float],
641
+ orig_size: tuple[int, int],
642
+ score_floor: float,
643
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
644
+ if preds.ndim == 3 and preds.shape[0] == 1:
645
+ preds = preds[0]
646
+ if preds.ndim != 2 or preds.shape[1] < 6:
647
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
648
+ boxes = preds[:, :4].astype(np.float32)
649
+ scores = preds[:, 4].astype(np.float32)
650
+ cls_ids = self._remap_train_cls_ids(preds[:, 5].astype(np.int32))
651
+ keep = scores >= float(score_floor)
652
+ boxes = boxes[keep]
653
+ scores = scores[keep]
654
+ cls_ids = cls_ids[keep]
655
+ if len(boxes) == 0:
656
+ return (
657
+ np.empty((0, 4), dtype=np.float32),
658
+ np.empty((0,), dtype=np.float32),
659
+ np.empty((0,), dtype=np.int32),
660
+ )
661
+ pad_w, pad_h = pad
662
+ orig_w, orig_h = orig_size
663
+ boxes[:, [0, 2]] -= pad_w
664
+ boxes[:, [1, 3]] -= pad_h
665
+ boxes /= ratio
666
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
667
+ return self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
668
+
669
+ def _raw_yolo_to_arrays_no_nms(
670
+ self,
671
+ preds: np.ndarray,
672
+ ratio: float,
673
+ pad: tuple[float, float],
674
+ orig_size: tuple[int, int],
675
+ score_floor: float,
676
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
677
+ if preds.ndim != 3:
678
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
679
+ if preds.shape[0] != 1:
680
+ raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
681
+ preds = preds[0]
682
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
683
+ preds = preds.T
684
+ if preds.ndim != 2 or preds.shape[1] < 5:
685
+ raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
686
+ boxes_xywh = preds[:, :4].astype(np.float32)
687
+ tail = preds[:, 4:].astype(np.float32)
688
+ if tail.shape[1] == 1:
689
+ scores = tail[:, 0]
690
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
691
+ elif tail.shape[1] == 2:
692
+ obj = tail[:, 0]
693
+ cls_prob = tail[:, 1]
694
+ scores = obj * cls_prob
695
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
696
+ else:
697
+ obj = tail[:, 0]
698
+ class_probs = tail[:, 1:]
699
+ cls_ids = np.argmax(class_probs, axis=1).astype(np.int32)
700
+ cls_scores = class_probs[np.arange(len(class_probs)), cls_ids]
701
+ scores = obj * cls_scores
702
+ cls_ids = self._remap_train_cls_ids(cls_ids)
703
+ keep = scores >= float(score_floor)
704
+ boxes_xywh = boxes_xywh[keep]
705
+ scores = scores[keep]
706
+ cls_ids = cls_ids[keep]
707
+ if len(boxes_xywh) == 0:
708
+ return (
709
+ np.empty((0, 4), dtype=np.float32),
710
+ np.empty((0,), dtype=np.float32),
711
+ np.empty((0,), dtype=np.int32),
712
+ )
713
+ boxes = self._xywh_to_xyxy(boxes_xywh)
714
+ pad_w, pad_h = pad
715
+ orig_w, orig_h = orig_size
716
+ boxes[:, [0, 2]] -= pad_w
717
+ boxes[:, [1, 3]] -= pad_h
718
+ boxes /= ratio
719
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
720
+ return self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
721
+
722
+ def _postprocess_to_arrays_no_nms(
723
+ self,
724
+ output: np.ndarray,
725
+ ratio: float,
726
+ pad: tuple[float, float],
727
+ orig_size: tuple[int, int],
728
+ score_floor: float,
729
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
730
+ if output.ndim == 2 and output.shape[1] >= 6:
731
+ return self._final_dets_to_arrays_no_nms(output, ratio, pad, orig_size, score_floor)
732
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] >= 6:
733
+ return self._final_dets_to_arrays_no_nms(output, ratio, pad, orig_size, score_floor)
734
+ return self._raw_yolo_to_arrays_no_nms(output, ratio, pad, orig_size, score_floor)
735
+
736
+ @staticmethod
737
+ def _horizontal_flip_boxes_xyxy(boxes: np.ndarray, w: int) -> np.ndarray:
738
+ if len(boxes) == 0:
739
+ return boxes
740
+ out = boxes.astype(np.float32, copy=True)
741
+ x1 = out[:, 0].copy()
742
+ x2 = out[:, 2].copy()
743
+ out[:, 0] = w - x2
744
+ out[:, 2] = w - x1
745
+ return out
746
+
747
+ def build_vehicle_sweep_cache(self, image_bgr: np.ndarray) -> dict[str, Any]:
748
+ """Two ONNX forwards (TTA views); candidates kept at score >= SWEEP_CONF_FLOOR."""
749
+ if image_bgr.dtype != np.uint8:
750
+ image_bgr = image_bgr.astype(np.uint8)
751
+ h, w = int(image_bgr.shape[0]), int(image_bgr.shape[1])
752
+ input_tensor, ratio, pad, orig_size = self._preprocess(image_bgr)
753
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
754
+ bo, so, co = self._postprocess_to_arrays_no_nms(
755
+ outputs[0], ratio, pad, orig_size, self.SWEEP_CONF_FLOOR
756
+ )
757
+ flipped = cv2.flip(image_bgr, 1)
758
+ input_tensor_f, ratio_f, pad_f, orig_size_f = self._preprocess(flipped)
759
+ outputs_f = self.session.run(self.output_names, {self.input_name: input_tensor_f})
760
+ bf, sf, cf = self._postprocess_to_arrays_no_nms(
761
+ outputs_f[0], ratio_f, pad_f, orig_size_f, self.SWEEP_CONF_FLOOR
762
+ )
763
+ bf = self._horizontal_flip_boxes_xyxy(bf, w)
764
+ return {"orig": (bo, so, co), "flip": (bf, sf, cf), "image_shape": (h, w)}
765
+
766
+ def _arrays_to_boxes_after_conf_nms(
767
+ self,
768
+ boxes: np.ndarray,
769
+ scores: np.ndarray,
770
+ cls_ids: np.ndarray,
771
+ conf_thres: float,
772
+ iou_thres: float,
773
+ ) -> list[BoundingBox]:
774
+ if len(boxes) == 0:
775
+ return []
776
+ m = scores >= float(conf_thres)
777
+ if not np.any(m):
778
+ return []
779
+ boxes = boxes[m]
780
+ scores = scores[m]
781
+ cls_ids = cls_ids[m]
782
+ keep_idx = self._nms_per_class(boxes, scores, cls_ids, float(iou_thres), self.max_det)
783
+ out: list[BoundingBox] = []
784
+ for i in keep_idx:
785
+ box = boxes[i]
786
+ x1, y1, x2, y2 = float(box[0]), float(box[1]), float(box[2]), float(box[3])
787
+ if x2 <= x1 or y2 <= y1:
788
+ continue
789
+ out.append(
790
+ BoundingBox(
791
+ x1=int(math.floor(x1)),
792
+ y1=int(math.floor(y1)),
793
+ x2=int(math.ceil(x2)),
794
+ y2=int(math.ceil(y2)),
795
+ cls_id=int(cls_ids[i]),
796
+ conf=float(scores[i]),
797
+ )
798
+ )
799
+ return out
800
+
801
+ def predict_vehicle_from_sweep_cache(
802
+ self,
803
+ cache: dict[str, Any],
804
+ *,
805
+ conf_thres: float,
806
+ iou_thres: float,
807
+ conf_high: float | None = None,
808
+ tta_match_iou: float | None = None,
809
+ ) -> list[BoundingBox]:
810
+ bo, so, co = cache["orig"]
811
+ bf, sf, cf = cache["flip"]
812
+ boxes_orig = self._arrays_to_boxes_after_conf_nms(bo, so, co, conf_thres, iou_thres)
813
+ # Match predict_batch: single-view path when TTA is off (sweep cache must not force merge).
814
+ if not getattr(self, "use_tta", True):
815
+ return boxes_orig
816
+
817
+ boxes_flip = self._arrays_to_boxes_after_conf_nms(bf, sf, cf, conf_thres, iou_thres)
818
+ # Pass swept thresholds explicitly to avoid mutating self.* (race-free
819
+ # under any future concurrent sweep harness; also robust to early returns).
820
+ return self._merge_tta_consensus(
821
+ boxes_orig,
822
+ boxes_flip,
823
+ conf_high=conf_high,
824
+ tta_match_iou=tta_match_iou,
825
+ iou_thres=iou_thres,
826
+ )
827
+
828
+ def predict_batch(
829
+ self,
830
+ batch_images: list[ndarray],
831
+ offset: int,
832
+ n_keypoints: int,
833
+ ) -> list[TVFrameResult]:
834
+ results: list[TVFrameResult] = []
835
+
836
+ for frame_number_in_batch, image in enumerate(batch_images):
837
+ try:
838
+ if self.use_tta:
839
+ boxes = self._predict_tta(image)
840
+ else:
841
+ boxes = self._predict_single(image)
842
+ except Exception as e:
843
+ print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")
844
+ boxes = []
845
+
846
+ results.append(
847
+ TVFrameResult(
848
+ frame_id=offset + frame_number_in_batch,
849
+ boxes=boxes,
850
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
851
+ )
852
+ )
853
+
854
+ return results
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd22d3edbce964fd9ec6632f0aa44092a14af261563ef3bd5766a9b56f79e0fd
3
+ size 19407525