gtensorapp commited on
Commit
61558a2
·
verified ·
1 Parent(s): bd55fac

Detect-construction-detect miner

Browse files
Files changed (3) hide show
  1. chute_config.yml +23 -0
  2. miner.py +908 -0
  3. weights.onnx +3 -0
chute_config.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Image:
2
+ from_base: parachutes/python:3.12
3
+ run_command:
4
+ - pip install --upgrade setuptools wheel
5
+ # CPU onnxruntime pinned to the conformity checker's version (Dockerfile.latency_conformity):
6
+ # identical kernels => identical boxes between the live chute and the offline FAIL_OUTPUT check.
7
+ - pip install 'numpy>=1.23,<3' 'onnxruntime==1.26.0' 'opencv-python-headless>=4.8' 'pillow>=9.5' 'huggingface_hub>=0.24' 'pydantic>=2.0' 'pyyaml>=6.0' 'aiohttp>=3.9'
8
+ - pip install torch==2.8.0 torchvision==0.23.0 --index-url https://download.pytorch.org/whl/cu128
9
+
10
+ NodeSelector:
11
+ gpu_count: 1
12
+ min_vram_gb_per_gpu: 16
13
+ max_hourly_price_per_gpu: 2
14
+ include:
15
+ - pro_6000
16
+
17
+ Chute:
18
+ timeout_seconds: 900
19
+ concurrency: 4
20
+ max_instances: 5
21
+ scaling_threshold: 0.5
22
+ shutdown_after_seconds: 288000
23
+ tee: true
miner.py ADDED
@@ -0,0 +1,908 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ONNX Runtime miner for road-sign detection (single class).
28
+ Strategy (ported from offense / fire001 miner):
29
+ - per-class confidence threshold with per-class rescue bonus
30
+ - per-class hard NMS, then cross-class dedup (no-op for single class)
31
+ - horizontal-flip TTA with full-set cluster score boost
32
+ Plus: class remap, sanity-box filter tuned for small distant signs,
33
+ TTA toggle.
34
+ """
35
+
36
+ class_names = ['box', 'hard hat', 'heavy machinery', 'high-vis jacket', 'ladder']
37
+ # Order the model emits classes in -- remapped to `class_names` index.
38
+ _model_class_order = ['box', 'hard hat', 'heavy machinery', 'high-vis jacket', 'ladder']
39
+
40
+ iou_thres = 0.75
41
+ cross_iou_thresh = 0.8
42
+ max_det = 150
43
+
44
+ # Per-class confidence threshold. Road signs in this dataset are
45
+ # frequently degraded / rear-facing / partly-obscured / distant, so we
46
+ # run noticeably below the fire/smoke baseline. The validator's
47
+ # false_positive pillar = max(0, 1 - ffpi/10): we can tolerate ~2 FP per
48
+ # image and still keep that pillar above 0.8.
49
+ _conf_thres_array = np.array(
50
+ [0.65, 0.4, 0.55, 0.45, 0.4], dtype=np.float32
51
+ )
52
+ # Per-class rescue bonus. If a class has ZERO boxes passing the threshold
53
+ # in a frame, its top-1 candidate is admitted when its score is at least
54
+ # (threshold - bonus). Bumped from 0.05 -> 0.10 so a single faint sign in
55
+ # an otherwise empty frame still produces a detection (map50 recall win,
56
+ # at most one extra FP per such frame).
57
+ _bonus_array = np.array(
58
+ [0, 0.1, 0.2, 0.1, 0.1], dtype=np.float32
59
+ )
60
+
61
+ # Box sanity filter: drop tiny / degenerate / image-spanning / extreme
62
+ # aspect ratio boxes.
63
+ # min_box_area = 14x14 -> 14x14 is the smallest credible sign. The old
64
+ # value of 64 (8x8) silently discarded narrow
65
+ # distant signs like a 10x6 px overhead chevron.
66
+ # min_side = 3 -> matches min_box_area; anything thinner is
67
+ # almost certainly a pole or shadow false alarm.
68
+ # max_aspect_ratio = 12.0
69
+ # -> overhead destination panels and lane-assignment
70
+ # signs are very wide (long, thin rectangles);
71
+ # 8.0 was clipping legitimate detections.
72
+ min_box_area = 8 * 8
73
+ min_side = 3
74
+ max_aspect_ratio = 12.0
75
+
76
+ # Tile-based TTA: when the source image is significantly larger than the
77
+ # model input, letterboxing throws away ~1.5x of effective resolution,
78
+ # which kills small-sign recall. Splitting into overlapping horizontal
79
+ # tiles preserves native resolution on each half. Triggered only when
80
+ # source width >= tile_trigger_ratio * model_input_width to avoid wasted
81
+ # compute on already-small images.
82
+ tile_trigger_ratio = 1.4
83
+ tile_overlap_ratio = 0.20
84
+
85
+ def __init__(self, path_hf_repo: Path) -> None:
86
+ model_path = path_hf_repo / "weights.onnx"
87
+ print("ORT version:", ort.__version__)
88
+
89
+ try:
90
+ ort.preload_dlls()
91
+ print("✅ onnxruntime.preload_dlls() success")
92
+ except Exception as e:
93
+ print(f"⚠️ preload_dlls failed: {e}")
94
+
95
+ print("ORT available providers BEFORE session:", ort.get_available_providers())
96
+
97
+ sess_options = ort.SessionOptions()
98
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
99
+ sess_options.intra_op_num_threads = 2
100
+ sess_options.inter_op_num_threads = 1
101
+ sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
102
+
103
+ try:
104
+ self.session = ort.InferenceSession(
105
+ str(model_path),
106
+ sess_options=sess_options,
107
+ providers=["CPUExecutionProvider"],
108
+ )
109
+ except Exception as e:
110
+ self.session = ort.InferenceSession(
111
+ str(model_path),
112
+ sess_options=sess_options,
113
+ providers=["CPUExecutionProvider"],
114
+ )
115
+
116
+ print("ORT session providers:", self.session.get_providers())
117
+
118
+ # Build cls_remap: for each model-emit index i,
119
+ # cls_remap[i] = self.class_names.index(model_class_order[i])
120
+ # i.e. convert a model-side class id into the output class id that
121
+ # downstream code (BoundingBox.cls_id, the per-class threshold/bonus
122
+ # arrays) expects. The model-side order comes from the ONNX metadata
123
+ # when available, else falls back to the static _model_class_order.
124
+ model_class_order = self._read_model_class_order()
125
+ if model_class_order is None:
126
+ model_class_order = list(self._model_class_order)
127
+ print(f"cls order: no usable ONNX metadata, FALLBACK {model_class_order}")
128
+ else:
129
+ print(f"cls order: from ONNX metadata {model_class_order}")
130
+ self.cls_remap = np.array(
131
+ [self.class_names.index(n) for n in model_class_order],
132
+ dtype=np.int32,
133
+ )
134
+
135
+ for inp in self.session.get_inputs():
136
+ print("INPUT:", inp.name, inp.shape, inp.type)
137
+ for out in self.session.get_outputs():
138
+ print("OUTPUT:", out.name, out.shape, out.type)
139
+
140
+ self.input_name = self.session.get_inputs()[0].name
141
+ self.output_names = [output.name for output in self.session.get_outputs()]
142
+ self.input_shape = self.session.get_inputs()[0].shape
143
+
144
+ # weights.onnx is exported at 1280x1280 (Ultralytics imgsz metadata),
145
+ # static (dynamic=False). The default is only the fallback for when the
146
+ # ONNX input dims aren't fixed; the real value is read from the session.
147
+ self.input_height = self._safe_dim(self.input_shape[2], default=1280)
148
+ self.input_width = self._safe_dim(self.input_shape[3], default=1280)
149
+
150
+ self.use_tta = False
151
+ self.use_tile_tta = False
152
+ # Soft-NMS (ported from carwash001): Gaussian score decay of overlapping
153
+ # boxes instead of hard removal. OFF by default to preserve the current
154
+ # deployed behaviour; flip on (and tune sigma) via tune_miner.py to see if
155
+ # it scores better — useful where signs cluster (gantries, sign assemblies).
156
+ self.use_soft_nms = False
157
+ self.soft_nms_sigma = 0.5
158
+ self.soft_nms_score_thresh = 0.01
159
+
160
+ print(f"✅ ONNX model loaded from: {model_path}")
161
+ print(f"✅ ONNX providers: {self.session.get_providers()}")
162
+ print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
163
+ print(f"✅ ONNX input size: {self.input_width}x{self.input_height}, "
164
+ f"use_tta={self.use_tta}, use_tile_tta={self.use_tile_tta}")
165
+ print("per-class conf: " + ", ".join(
166
+ f"{n}={t:.3f}" for n, t in zip(
167
+ self.class_names, self._conf_thres_array.tolist()
168
+ )
169
+ ))
170
+
171
+ self._warmup()
172
+
173
+ def _warmup(self, iters: int = 3) -> None:
174
+ try:
175
+ dummy = np.zeros((720, 1280, 3), dtype=np.uint8)
176
+ for _ in range(max(1, iters)):
177
+ self.predict_batch(batch_images=[dummy], offset=0, n_keypoints=0)
178
+ print(f"✅ warmup: {iters} dummy predict_batch call(s) done")
179
+ except Exception as e:
180
+ print(f"⚠️ warmup skipped: {e}")
181
+
182
+ def _read_model_class_order(self) -> "list[str] | None":
183
+ """Read the model's class order from Ultralytics ONNX metadata.
184
+ Returns the class names ordered by model-emit index, or None when the
185
+ metadata is missing/unparsable or doesn't match `class_names` as a set
186
+ (in which case the static _model_class_order fallback is used)."""
187
+ try:
188
+ import ast
189
+
190
+ meta = self.session.get_modelmeta().custom_metadata_map
191
+ names = ast.literal_eval(meta["names"]) # e.g. {0: 'road_sign'}
192
+ if isinstance(names, dict):
193
+ order = [str(names[i]) for i in sorted(names)]
194
+ else:
195
+ order = [str(n) for n in names]
196
+ except Exception as e:
197
+ print(f"cls order: could not read ONNX names metadata ({e})")
198
+ return None
199
+ if sorted(order) != sorted(self.class_names):
200
+ print(
201
+ f"cls order: ONNX names {order} do not match expected classes "
202
+ f"{self.class_names}; ignoring metadata"
203
+ )
204
+ return None
205
+ return order
206
+
207
+ def __repr__(self) -> str:
208
+ return (
209
+ f"ONNXRuntime(session={type(self.session).__name__}, "
210
+ f"providers={self.session.get_providers()})"
211
+ )
212
+
213
+ @staticmethod
214
+ def _safe_dim(value, default: int) -> int:
215
+ return value if isinstance(value, int) and value > 0 else default
216
+
217
+ def _letterbox(
218
+ self,
219
+ image: ndarray,
220
+ new_shape: tuple[int, int],
221
+ color=(114, 114, 114),
222
+ ) -> tuple[ndarray, float, tuple[float, float]]:
223
+ h, w = image.shape[:2]
224
+ new_w, new_h = new_shape
225
+
226
+ ratio = min(new_w / w, new_h / h)
227
+ resized_w = int(round(w * ratio))
228
+ resized_h = int(round(h * ratio))
229
+
230
+ if (resized_w, resized_h) != (w, h):
231
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
232
+ image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
233
+
234
+ dw = (new_w - resized_w) / 2.0
235
+ dh = (new_h - resized_h) / 2.0
236
+
237
+ left = int(round(dw - 0.1))
238
+ right = int(round(dw + 0.1))
239
+ top = int(round(dh - 0.1))
240
+ bottom = int(round(dh + 0.1))
241
+
242
+ padded = cv2.copyMakeBorder(
243
+ image, top, bottom, left, right,
244
+ borderType=cv2.BORDER_CONSTANT, value=color,
245
+ )
246
+ return padded, ratio, (dw, dh)
247
+
248
+ def _preprocess(
249
+ self, image: ndarray
250
+ ) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
251
+ orig_h, orig_w = image.shape[:2]
252
+ img, ratio, pad = self._letterbox(
253
+ image, (self.input_width, self.input_height)
254
+ )
255
+ # Fused scale(1/255) + BGR->RGB swap + HWC->NCHW + contiguous float32 in
256
+ # one optimized OpenCV call (bit-identical to the cvtColor + astype/255 +
257
+ # transpose chain, but ~half the preprocess time).
258
+ blob = cv2.dnn.blobFromImage(img, scalefactor=1.0 / 255.0, swapRB=True)
259
+ return blob, ratio, pad, (orig_w, orig_h)
260
+
261
+ @staticmethod
262
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
263
+ w, h = image_size
264
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
265
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
266
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
267
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
268
+ return boxes
269
+
270
+ @staticmethod
271
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
272
+ out = np.empty_like(boxes)
273
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
274
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
275
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
276
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
277
+ return out
278
+
279
+ @staticmethod
280
+ def _hard_nms(
281
+ boxes: np.ndarray, scores: np.ndarray, iou_thresh: float
282
+ ) -> np.ndarray:
283
+ n = len(boxes)
284
+ if n == 0:
285
+ return np.array([], dtype=np.intp)
286
+ order = np.argsort(-scores)
287
+ keep: list[int] = []
288
+ while len(order) > 0:
289
+ i = int(order[0])
290
+ keep.append(i)
291
+ if len(order) == 1:
292
+ break
293
+ rest = order[1:]
294
+ xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
295
+ yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
296
+ xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
297
+ yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
298
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
299
+ a_i = (max(0.0, boxes[i, 2] - boxes[i, 0]) *
300
+ max(0.0, boxes[i, 3] - boxes[i, 1]))
301
+ a_r = (np.maximum(0.0, boxes[rest, 2] - boxes[rest, 0]) *
302
+ np.maximum(0.0, boxes[rest, 3] - boxes[rest, 1]))
303
+ iou = inter / (a_i + a_r - inter + 1e-7)
304
+ order = rest[iou <= iou_thresh]
305
+ return np.array(keep, dtype=np.intp)
306
+
307
+ def _per_class_hard_nms(
308
+ self,
309
+ boxes: np.ndarray,
310
+ scores: np.ndarray,
311
+ cls_ids: np.ndarray,
312
+ iou_thresh: float,
313
+ ) -> np.ndarray:
314
+ if len(boxes) == 0:
315
+ return np.array([], dtype=np.intp)
316
+ all_keep: list[int] = []
317
+ for c in np.unique(cls_ids):
318
+ mask = cls_ids == c
319
+ indices = np.where(mask)[0]
320
+ keep = self._hard_nms(boxes[mask], scores[mask], iou_thresh)
321
+ all_keep.extend(indices[keep].tolist())
322
+ all_keep.sort()
323
+ return np.array(all_keep, dtype=np.intp)
324
+
325
+ def _soft_nms(
326
+ self,
327
+ boxes: np.ndarray,
328
+ scores: np.ndarray,
329
+ sigma: float = 0.5,
330
+ score_thresh: float = 0.01,
331
+ ) -> tuple[np.ndarray, np.ndarray]:
332
+ """Soft-NMS: Gaussian decay of overlapping scores instead of hard removal.
333
+ Returns (kept_original_indices, updated_scores). (Ported from carwash001.)"""
334
+ N = len(boxes)
335
+ if N == 0:
336
+ return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
337
+ boxes = boxes.astype(np.float32, copy=True)
338
+ scores = scores.astype(np.float32, copy=True)
339
+ order = np.arange(N)
340
+ for i in range(N):
341
+ max_pos = i + int(np.argmax(scores[i:]))
342
+ boxes[[i, max_pos]] = boxes[[max_pos, i]]
343
+ scores[[i, max_pos]] = scores[[max_pos, i]]
344
+ order[[i, max_pos]] = order[[max_pos, i]]
345
+ if i + 1 >= N:
346
+ break
347
+ xx1 = np.maximum(boxes[i, 0], boxes[i + 1:, 0])
348
+ yy1 = np.maximum(boxes[i, 1], boxes[i + 1:, 1])
349
+ xx2 = np.minimum(boxes[i, 2], boxes[i + 1:, 2])
350
+ yy2 = np.minimum(boxes[i, 3], boxes[i + 1:, 3])
351
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
352
+ area_i = max(0.0, float(
353
+ (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])))
354
+ areas_j = (np.maximum(0.0, boxes[i + 1:, 2] - boxes[i + 1:, 0])
355
+ * np.maximum(0.0, boxes[i + 1:, 3] - boxes[i + 1:, 1]))
356
+ iou = inter / (area_i + areas_j - inter + 1e-7)
357
+ scores[i + 1:] *= np.exp(-(iou ** 2) / sigma)
358
+ mask = scores > score_thresh
359
+ return order[mask], scores[mask]
360
+
361
+ def _per_class_soft_nms(
362
+ self,
363
+ boxes: np.ndarray,
364
+ scores: np.ndarray,
365
+ cls_ids: np.ndarray,
366
+ sigma: float = 0.5,
367
+ score_thresh: float = 0.01,
368
+ ) -> tuple[np.ndarray, np.ndarray]:
369
+ """Soft-NMS applied independently per class. Returns (kept_idx, updated_scores)."""
370
+ if len(boxes) == 0:
371
+ return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
372
+ all_keep: list[int] = []
373
+ all_scores: list[float] = []
374
+ for c in np.unique(cls_ids):
375
+ indices = np.where(cls_ids == c)[0]
376
+ keep, updated = self._soft_nms(boxes[indices], scores[indices],
377
+ sigma, score_thresh)
378
+ for k, s in zip(keep, updated):
379
+ all_keep.append(int(indices[k])); all_scores.append(float(s))
380
+ if not all_keep:
381
+ return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
382
+ return np.array(all_keep, dtype=np.intp), np.array(all_scores, dtype=np.float32)
383
+
384
+ def _cross_class_dedup_op(
385
+ self,
386
+ boxes: np.ndarray,
387
+ scores: np.ndarray,
388
+ cls_ids: np.ndarray,
389
+ iou_thresh: float,
390
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
391
+ """Remove near-duplicate boxes across classes.
392
+ Order candidates by (score - per_class_threshold) margin, then by area;
393
+ keep the highest, suppress every other box with IoU > iou_thresh.
394
+ With a single road_sign class this is effectively a no-op, but the
395
+ method is kept so the pipeline stays compatible with the multi-class
396
+ miner template.
397
+ """
398
+ n = len(boxes)
399
+ if n <= 1:
400
+ return boxes, scores, cls_ids
401
+ boxes = np.asarray(boxes, dtype=np.float32)
402
+ scores = np.asarray(scores, dtype=np.float32)
403
+ cls_ids = np.asarray(cls_ids, dtype=np.int32)
404
+ areas = (np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) *
405
+ np.maximum(0.0, boxes[:, 3] - boxes[:, 1]))
406
+ margins = scores - self._conf_thres_array[cls_ids]
407
+ order = np.lexsort((-areas, -margins))
408
+ suppressed = np.zeros(n, dtype=bool)
409
+ keep: list[int] = []
410
+ for i in order:
411
+ if suppressed[i]:
412
+ continue
413
+ keep.append(int(i))
414
+ bi = boxes[i]
415
+ xx1 = np.maximum(bi[0], boxes[:, 0])
416
+ yy1 = np.maximum(bi[1], boxes[:, 1])
417
+ xx2 = np.minimum(bi[2], boxes[:, 2])
418
+ yy2 = np.minimum(bi[3], boxes[:, 3])
419
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
420
+ a_i = max(1e-7, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
421
+ iou = inter / (a_i + areas - inter + 1e-7)
422
+ dup = iou > iou_thresh
423
+ dup[i] = False
424
+ suppressed |= dup
425
+ keep_idx = np.array(keep, dtype=np.intp)
426
+ return boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx]
427
+
428
+ @staticmethod
429
+ def _max_score_per_cluster(
430
+ post_boxes: np.ndarray,
431
+ post_cls: np.ndarray,
432
+ full_boxes: np.ndarray,
433
+ full_scores: np.ndarray,
434
+ full_cls: np.ndarray,
435
+ iou_thresh: float,
436
+ ) -> np.ndarray:
437
+ """For each kept (post-NMS) box, return the max score over the FULL
438
+ candidate set among same-class boxes with IoU >= iou_thresh.
439
+ Used after horizontal-flip TTA: a high-confidence flipped detection
440
+ can raise the score of the corresponding original detection.
441
+ """
442
+ n = len(post_boxes)
443
+ if n == 0:
444
+ return np.empty(0, dtype=np.float32)
445
+ full_areas = (np.maximum(0.0, full_boxes[:, 2] - full_boxes[:, 0]) *
446
+ np.maximum(0.0, full_boxes[:, 3] - full_boxes[:, 1]))
447
+ out = np.empty(n, dtype=np.float32)
448
+ for i in range(n):
449
+ bi = post_boxes[i]
450
+ xx1 = np.maximum(bi[0], full_boxes[:, 0])
451
+ yy1 = np.maximum(bi[1], full_boxes[:, 1])
452
+ xx2 = np.minimum(bi[2], full_boxes[:, 2])
453
+ yy2 = np.minimum(bi[3], full_boxes[:, 3])
454
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
455
+ a_i = max(0.0, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
456
+ iou = inter / (a_i + full_areas - inter + 1e-7)
457
+ cluster = (iou >= iou_thresh) & (full_cls == post_cls[i])
458
+ out[i] = float(np.max(full_scores[cluster])) if np.any(cluster) else 0.0
459
+ return out
460
+
461
+ def _conf_filter_mask(
462
+ self, scores: np.ndarray, cls_ids: np.ndarray
463
+ ) -> np.ndarray:
464
+ """Boolean keep-mask: score >= per-class threshold, with a per-class
465
+ rescue -- if a class has zero boxes passing, admit its top-1 candidate
466
+ when its score >= (per-class threshold - per-class bonus)."""
467
+ if len(scores) == 0:
468
+ return np.zeros(0, dtype=bool)
469
+ thr = self._conf_thres_array[cls_ids]
470
+ keep = scores >= thr
471
+ for c in np.unique(cls_ids):
472
+ b = float(self._bonus_array[c])
473
+ if b <= 0.0:
474
+ continue
475
+ cm = cls_ids == c
476
+ if keep[cm].any():
477
+ continue
478
+ idx = np.where(cm)[0]
479
+ top = int(idx[int(np.argmax(scores[idx]))])
480
+ if scores[top] >= self._conf_thres_array[c] - b:
481
+ keep[top] = True
482
+ return keep
483
+
484
+ def _filter_sane_boxes(
485
+ self,
486
+ boxes: np.ndarray,
487
+ scores: np.ndarray,
488
+ cls_ids: np.ndarray,
489
+ orig_size: tuple[int, int],
490
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
491
+ """Drop tiny / degenerate / image-spanning / extreme-AR boxes (FP)."""
492
+ if len(boxes) == 0:
493
+ return boxes, scores, cls_ids
494
+ orig_w, orig_h = orig_size
495
+ image_area = float(orig_w * orig_h)
496
+ keep = []
497
+ for i, box in enumerate(boxes):
498
+ x1, y1, x2, y2 = box.tolist()
499
+ bw = x2 - x1
500
+ bh = y2 - y1
501
+ if bw <= 0 or bh <= 0:
502
+ continue
503
+ if bw < self.min_side or bh < self.min_side:
504
+ continue
505
+ area = bw * bh
506
+ if area < self.min_box_area:
507
+ continue
508
+ if area > 0.95 * image_area:
509
+ continue
510
+ ar = max(bw / max(bh, 1e-6), bh / max(bw, 1e-6))
511
+ if ar > self.max_aspect_ratio:
512
+ continue
513
+ keep.append(i)
514
+ if not keep:
515
+ return (
516
+ np.empty((0, 4), dtype=np.float32),
517
+ np.empty((0,), dtype=np.float32),
518
+ np.empty((0,), dtype=np.int32),
519
+ )
520
+ k = np.array(keep, dtype=np.intp)
521
+ return boxes[k], scores[k], cls_ids[k]
522
+
523
+ def _per_view_pipeline(
524
+ self,
525
+ boxes: np.ndarray,
526
+ scores: np.ndarray,
527
+ cls_ids: np.ndarray,
528
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
529
+ """Per-view post-processing pipeline: per-class NMS -> cap -> cross-class dedup."""
530
+ if len(boxes) > 1:
531
+ if self.use_soft_nms:
532
+ keep, new_scores = self._per_class_soft_nms(
533
+ boxes, scores, cls_ids,
534
+ self.soft_nms_sigma, self.soft_nms_score_thresh)
535
+ boxes, scores, cls_ids = boxes[keep], new_scores, cls_ids[keep]
536
+ else:
537
+ keep = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
538
+ boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
539
+ if len(scores) > self.max_det:
540
+ top = np.argsort(-scores)[: self.max_det]
541
+ boxes, scores, cls_ids = boxes[top], scores[top], cls_ids[top]
542
+ if len(boxes) > 1:
543
+ boxes, scores, cls_ids = self._cross_class_dedup_op(
544
+ boxes, scores, cls_ids, self.cross_iou_thresh
545
+ )
546
+ return boxes, scores, cls_ids
547
+
548
+ @staticmethod
549
+ def _build_results(
550
+ boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray
551
+ ) -> list[BoundingBox]:
552
+ results: list[BoundingBox] = []
553
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
554
+ x1, y1, x2, y2 = box.tolist()
555
+ if x2 <= x1 or y2 <= y1:
556
+ continue
557
+ results.append(
558
+ BoundingBox(
559
+ x1=int(math.floor(x1)),
560
+ y1=int(math.floor(y1)),
561
+ x2=int(math.ceil(x2)),
562
+ y2=int(math.ceil(y2)),
563
+ cls_id=int(cls_id),
564
+ conf=float(conf),
565
+ )
566
+ )
567
+ return results
568
+
569
+ def _decode_final_dets(
570
+ self,
571
+ preds: np.ndarray,
572
+ ratio: float,
573
+ pad: tuple[float, float],
574
+ orig_size: tuple[int, int],
575
+ ) -> list[BoundingBox]:
576
+ """Final-detection output path: rows shaped [x1, y1, x2, y2, conf, cls_id]."""
577
+ if preds.ndim == 3 and preds.shape[0] == 1:
578
+ preds = preds[0]
579
+ if preds.ndim != 2 or preds.shape[1] < 6:
580
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
581
+
582
+ boxes = preds[:, :4].astype(np.float32)
583
+ scores = preds[:, 4].astype(np.float32)
584
+ cls_ids = preds[:, 5].astype(np.int32)
585
+ cls_ids = self.cls_remap[cls_ids]
586
+
587
+ keep = self._conf_filter_mask(scores, cls_ids)
588
+ boxes = boxes[keep]
589
+ scores = scores[keep]
590
+ cls_ids = cls_ids[keep]
591
+ if len(boxes) == 0:
592
+ return []
593
+
594
+ pad_w, pad_h = pad
595
+ boxes[:, [0, 2]] -= pad_w
596
+ boxes[:, [1, 3]] -= pad_h
597
+ boxes /= ratio
598
+ boxes = self._clip_boxes(boxes, orig_size)
599
+
600
+ boxes, scores, cls_ids = self._filter_sane_boxes(
601
+ boxes, scores, cls_ids, orig_size
602
+ )
603
+ if len(boxes) == 0:
604
+ return []
605
+
606
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
607
+ return self._build_results(boxes, scores, cls_ids)
608
+
609
+ def _decode_raw_yolo(
610
+ self,
611
+ preds: np.ndarray,
612
+ ratio: float,
613
+ pad: tuple[float, float],
614
+ orig_size: tuple[int, int],
615
+ ) -> list[BoundingBox]:
616
+ """Fallback raw-YOLO output path: per-anchor class logits."""
617
+ if preds.ndim != 3 or preds.shape[0] != 1:
618
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
619
+ preds = preds[0]
620
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
621
+ preds = preds.T
622
+ if preds.ndim != 2 or preds.shape[1] < 5:
623
+ raise ValueError(f"Unexpected raw output shape: {preds.shape}")
624
+
625
+ boxes_xywh = preds[:, :4].astype(np.float32)
626
+ cls_part = preds[:, 4:].astype(np.float32)
627
+ if cls_part.shape[1] == 1:
628
+ scores = cls_part[:, 0]
629
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
630
+ else:
631
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
632
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
633
+ cls_ids = self.cls_remap[cls_ids]
634
+
635
+ keep = self._conf_filter_mask(scores, cls_ids)
636
+ boxes_xywh = boxes_xywh[keep]
637
+ scores = scores[keep]
638
+ cls_ids = cls_ids[keep]
639
+ if len(boxes_xywh) == 0:
640
+ return []
641
+ boxes = self._xywh_to_xyxy(boxes_xywh)
642
+
643
+ pad_w, pad_h = pad
644
+ boxes[:, [0, 2]] -= pad_w
645
+ boxes[:, [1, 3]] -= pad_h
646
+ boxes /= ratio
647
+ boxes = self._clip_boxes(boxes, orig_size)
648
+
649
+ boxes, scores, cls_ids = self._filter_sane_boxes(
650
+ boxes, scores, cls_ids, orig_size
651
+ )
652
+ if len(boxes) == 0:
653
+ return []
654
+
655
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
656
+ return self._build_results(boxes, scores, cls_ids)
657
+
658
+ def _postprocess(
659
+ self,
660
+ output: np.ndarray,
661
+ ratio: float,
662
+ pad: tuple[float, float],
663
+ orig_size: tuple[int, int],
664
+ ) -> list[BoundingBox]:
665
+ if output.ndim == 2 and output.shape[1] >= 6:
666
+ return self._decode_final_dets(output, ratio, pad, orig_size)
667
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
668
+ return self._decode_final_dets(output, ratio, pad, orig_size)
669
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
670
+
671
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
672
+ if image is None:
673
+ raise ValueError("Input image is None")
674
+ if not isinstance(image, np.ndarray):
675
+ raise TypeError(f"Input is not numpy array: {type(image)}")
676
+ if image.ndim != 3:
677
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
678
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
679
+ raise ValueError(f"Invalid image shape={image.shape}")
680
+ if image.shape[2] != 3:
681
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
682
+ if image.dtype != np.uint8:
683
+ image = image.astype(np.uint8)
684
+
685
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
686
+ expected = (1, 3, self.input_height, self.input_width)
687
+ if input_tensor.shape != expected:
688
+ raise ValueError(
689
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected}"
690
+ )
691
+
692
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
693
+ return self._postprocess(outputs[0], ratio, pad, orig_size)
694
+
695
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
696
+ """Horizontal-flip TTA.
697
+ Strategy:
698
+ 1. Predict on original and on flipped image.
699
+ 2. Map flipped boxes back to original coordinates.
700
+ 3. Per-class hard NMS on the union.
701
+ 4. For each kept box, compute the max same-class score across the
702
+ FULL union (not just the post-NMS subset) -- this lets a high-
703
+ confidence flipped detection raise a borderline original one.
704
+ 5. Cross-class dedup to suppress same-physical-object multi-class.
705
+ """
706
+ boxes_orig = self._predict_single(image)
707
+ flipped = cv2.flip(image, 1)
708
+ boxes_flip = self._predict_single(flipped)
709
+ w = image.shape[1]
710
+ boxes_flip = [
711
+ BoundingBox(
712
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
713
+ cls_id=b.cls_id, conf=b.conf,
714
+ )
715
+ for b in boxes_flip
716
+ ]
717
+ all_boxes = boxes_orig + boxes_flip
718
+ if not all_boxes:
719
+ return []
720
+
721
+ coords = np.array(
722
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
723
+ )
724
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
725
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
726
+
727
+ hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
728
+ if len(hard_keep) == 0:
729
+ return []
730
+ if len(hard_keep) > self.max_det:
731
+ top = np.argsort(-scores[hard_keep])[: self.max_det]
732
+ hard_keep = hard_keep[top]
733
+
734
+ boosted = self._max_score_per_cluster(
735
+ coords[hard_keep], cls_ids[hard_keep],
736
+ coords, scores, cls_ids, self.iou_thres,
737
+ )
738
+
739
+ kept_coords = coords[hard_keep]
740
+ kept_cls = cls_ids[hard_keep]
741
+ if len(kept_coords) > 1:
742
+ kept_coords, boosted, kept_cls = self._cross_class_dedup_op(
743
+ kept_coords, boosted, kept_cls, self.cross_iou_thresh
744
+ )
745
+
746
+ return [
747
+ BoundingBox(
748
+ x1=int(math.floor(kept_coords[j, 0])),
749
+ y1=int(math.floor(kept_coords[j, 1])),
750
+ x2=int(math.ceil(kept_coords[j, 2])),
751
+ y2=int(math.ceil(kept_coords[j, 3])),
752
+ cls_id=int(kept_cls[j]),
753
+ conf=float(boosted[j]),
754
+ )
755
+ for j in range(len(kept_coords))
756
+ ]
757
+
758
+ def _predict_tiles(self, image: np.ndarray) -> list[BoundingBox]:
759
+ """Tile-based TTA for high-resolution images.
760
+ Splits the source image into two overlapping horizontal tiles, runs
761
+ single-pass inference on each at native scale, and translates boxes
762
+ back to the global frame. Useful when source width >> model input
763
+ width because letterboxing otherwise discards effective resolution
764
+ that small / distant signs depend on.
765
+ Returns an empty list if the image isn't wide enough to benefit; the
766
+ caller falls back to the regular pipeline in that case.
767
+ """
768
+ h, w = image.shape[:2]
769
+ if w < int(self.input_width * self.tile_trigger_ratio):
770
+ return []
771
+
772
+ overlap = int(w * self.tile_overlap_ratio)
773
+ mid = w // 2
774
+ x_left_end = min(w, mid + overlap // 2)
775
+ x_right_start = max(0, mid - overlap // 2)
776
+
777
+ left = image[:, :x_left_end]
778
+ right = image[:, x_right_start:]
779
+
780
+ boxes_left = self._predict_single(left)
781
+ boxes_right = self._predict_single(right)
782
+
783
+ shifted_right = [
784
+ BoundingBox(
785
+ x1=b.x1 + x_right_start,
786
+ y1=b.y1,
787
+ x2=b.x2 + x_right_start,
788
+ y2=b.y2,
789
+ cls_id=b.cls_id,
790
+ conf=b.conf,
791
+ )
792
+ for b in boxes_right
793
+ ]
794
+ return boxes_left + shifted_right
795
+
796
+ def _merge_views(
797
+ self,
798
+ view_boxes: list[list[BoundingBox]],
799
+ image_size: tuple[int, int],
800
+ ) -> list[BoundingBox]:
801
+ """Merge boxes from multiple views (single / hflip / tiles).
802
+ Same logic as `_predict_tta`'s tail: per-class hard NMS to dedupe,
803
+ then for each kept box take the max same-class score across the full
804
+ candidate union — a high-confidence detection in any view boosts
805
+ borderline matches in others.
806
+ """
807
+ all_boxes: list[BoundingBox] = []
808
+ for vb in view_boxes:
809
+ all_boxes.extend(vb)
810
+ if not all_boxes:
811
+ return []
812
+
813
+ coords = np.array(
814
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
815
+ )
816
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
817
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
818
+
819
+ coords = self._clip_boxes(coords, image_size)
820
+
821
+ hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
822
+ if len(hard_keep) == 0:
823
+ return []
824
+ if len(hard_keep) > self.max_det:
825
+ top = np.argsort(-scores[hard_keep])[: self.max_det]
826
+ hard_keep = hard_keep[top]
827
+
828
+ boosted = self._max_score_per_cluster(
829
+ coords[hard_keep], cls_ids[hard_keep],
830
+ coords, scores, cls_ids, self.iou_thres,
831
+ )
832
+
833
+ kept_coords = coords[hard_keep]
834
+ kept_cls = cls_ids[hard_keep]
835
+ if len(kept_coords) > 1:
836
+ kept_coords, boosted, kept_cls = self._cross_class_dedup_op(
837
+ kept_coords, boosted, kept_cls, self.cross_iou_thresh
838
+ )
839
+
840
+ return [
841
+ BoundingBox(
842
+ x1=int(math.floor(kept_coords[j, 0])),
843
+ y1=int(math.floor(kept_coords[j, 1])),
844
+ x2=int(math.ceil(kept_coords[j, 2])),
845
+ y2=int(math.ceil(kept_coords[j, 3])),
846
+ cls_id=int(kept_cls[j]),
847
+ conf=float(boosted[j]),
848
+ )
849
+ for j in range(len(kept_coords))
850
+ ]
851
+
852
+ def _predict_full(self, image: np.ndarray) -> list[BoundingBox]:
853
+ """Top-level per-frame prediction with all enabled augmentations.
854
+ - `use_tta=True`: original + horizontal flip
855
+ - `use_tile_tta=True` AND image wide enough: two overlapping tiles
856
+ All views are merged via per-class NMS + cluster-max score boost.
857
+ """
858
+ if not self.use_tta and not self.use_tile_tta:
859
+ return self._predict_single(image)
860
+
861
+ views: list[list[BoundingBox]] = []
862
+ if self.use_tta:
863
+ views.append(self._predict_single(image))
864
+ flipped = cv2.flip(image, 1)
865
+ w = image.shape[1]
866
+ flipped_dets = self._predict_single(flipped)
867
+ views.append([
868
+ BoundingBox(
869
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
870
+ cls_id=b.cls_id, conf=b.conf,
871
+ )
872
+ for b in flipped_dets
873
+ ])
874
+ else:
875
+ views.append(self._predict_single(image))
876
+
877
+ if self.use_tile_tta:
878
+ tile_boxes = self._predict_tiles(image)
879
+ if tile_boxes:
880
+ views.append(tile_boxes)
881
+
882
+ h, w = image.shape[:2]
883
+ return self._merge_views(views, (w, h))
884
+
885
+ def predict_batch(
886
+ self,
887
+ batch_images: list[ndarray],
888
+ offset: int,
889
+ n_keypoints: int,
890
+ ) -> list[TVFrameResult]:
891
+ results: list[TVFrameResult] = []
892
+ for frame_number_in_batch, image in enumerate(batch_images):
893
+ try:
894
+ boxes = self._predict_full(image)
895
+ except Exception as e:
896
+ print(
897
+ f"⚠️ Inference failed for frame "
898
+ f"{offset + frame_number_in_batch}: {e}"
899
+ )
900
+ boxes = []
901
+ results.append(
902
+ TVFrameResult(
903
+ frame_id=offset + frame_number_in_batch,
904
+ boxes=boxes,
905
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
906
+ )
907
+ )
908
+ return results
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c03e85a2fc719b759941a984c4b37b00af777b6d192d3e2a5574967626b6dca2
3
+ size 9864167