gtensorapp commited on
Commit
acfdc8c
·
verified ·
1 Parent(s): 992f5f0

Detect-crime miner

Browse files
Files changed (3) hide show
  1. chute_config.yml +23 -0
  2. miner.py +598 -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,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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. Hard per-class NMS + cross-class dedup + flip TTA."""
28
+
29
+ class_names = ["balaclava", "hoodie", "glove", "bat", "spray paint", "graffiti"]
30
+
31
+ # FALLBACK order the model emits classes in -- remapped to `class_names`
32
+ # index by `self.cls_remap` (built in __init__). The authoritative order is
33
+ # read from the ONNX `names` metadata that Ultralytics embeds at export time
34
+ # (ships inside weights.onnx), so a retrained model with a different class
35
+ # order is remapped correctly without code changes. This static list is used
36
+ # only when that metadata is missing or unparsable.
37
+ model_class_names = ["balaclava", "bat", "glove", "graffiti", "hoodie", "spray paint"]
38
+
39
+ input_size = 1280
40
+
41
+ # Test-time augmentation (horizontal-flip ensemble) runs a SECOND forward
42
+ # pass per frame and roughly DOUBLES latency. This 640 model is built for a
43
+ # <100 ms single-pass budget, so TTA is OFF by default. Turn it on only with
44
+ # latency headroom — and note the per-class thresholds below should be
45
+ # re-swept for whichever mode you deploy, since flipping TTA shifts scores.
46
+ use_tta = False
47
+
48
+ iou_thres = 0.3
49
+ cross_iou_thresh = 0.8
50
+ max_det = 150
51
+
52
+ # Final box tightening, applied about each box's own center AFTER NMS /
53
+ # cross-class dedup so the tuned IoU thresholds above still see the raw
54
+ # geometry. `box_shrink` is the fraction of width/height the box keeps:
55
+ # 1.0 = unchanged, 0.96 pulls each edge inward by 2% of that dimension.
56
+ # A box is never shrunk below `min_box_size` px, and never below its own
57
+ # original size.
58
+ box_shrink = 0.98
59
+ min_box_size = 2.0
60
+
61
+ _conf_thres_array = np.array(
62
+ [0.38, 0.38, 0.23, 0.19, 0.22, 0.12], dtype=np.float32,
63
+ )
64
+ _bonus_array = np.array(
65
+ [0.18, 0.18, 0.19, 0.1, 0.10, 0.06], dtype=np.float32,
66
+ )
67
+
68
+ def __init__(self, path_hf_repo: Path) -> None:
69
+ model_path = path_hf_repo / "weights.onnx"
70
+ # model_path = path_hf_repo / "weights.onnx"
71
+ print("ORT version:", ort.__version__)
72
+
73
+ try:
74
+ ort.preload_dlls()
75
+ print("preload_dlls success")
76
+ except Exception as e:
77
+ print(f"preload_dlls failed: {e}")
78
+
79
+ print("ORT available providers BEFORE session:", ort.get_available_providers())
80
+
81
+ sess_options = ort.SessionOptions()
82
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
83
+ # Pin threads for the 2vCPU/4GB public-track latency gate (p95 <= 100ms).
84
+ sess_options.intra_op_num_threads = 2
85
+ sess_options.inter_op_num_threads = 1
86
+ sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
87
+
88
+ try:
89
+ self.session = ort.InferenceSession(
90
+ str(model_path),
91
+ sess_options=sess_options,
92
+ providers=["CPUExecutionProvider"],
93
+ )
94
+ except Exception as e:
95
+ print(f"CUDA session creation failed, falling back to CPU: {e}")
96
+ self.session = ort.InferenceSession(
97
+ str(model_path),
98
+ sess_options=sess_options,
99
+ providers=["CPUExecutionProvider"],
100
+ )
101
+
102
+ print("ORT session providers:", self.session.get_providers())
103
+
104
+ # Build cls_remap: for each model-emit index i,
105
+ # cls_remap[i] = self.class_names.index(model_class_order[i])
106
+ # i.e. convert a model-side class id into the output class id that
107
+ # downstream code (BoundingBox.cls_id, the per-class threshold/bonus
108
+ # arrays) expects. The model-side order comes from the ONNX metadata
109
+ # when available, else falls back to the static model_class_names.
110
+ model_class_order = self._read_model_class_order()
111
+ if model_class_order is None:
112
+ model_class_order = list(self.model_class_names)
113
+ print(f"cls order: no usable ONNX metadata, FALLBACK {model_class_order}")
114
+ else:
115
+ print(f"cls order: from ONNX metadata {model_class_order}")
116
+ self.cls_remap = np.array(
117
+ [self.class_names.index(n) for n in model_class_order],
118
+ dtype=np.int32,
119
+ )
120
+
121
+ for inp in self.session.get_inputs():
122
+ print("INPUT:", inp.name, inp.shape, inp.type)
123
+ for out in self.session.get_outputs():
124
+ print("OUTPUT:", out.name, out.shape, out.type)
125
+
126
+ self.input_name = self.session.get_inputs()[0].name
127
+ self.output_names = [output.name for output in self.session.get_outputs()]
128
+ self.input_shape = self.session.get_inputs()[0].shape
129
+
130
+ self.input_height = self._safe_dim(self.input_shape[2], default=self.input_size)
131
+ self.input_width = self._safe_dim(self.input_shape[3], default=self.input_size)
132
+
133
+ print(f"ONNX model loaded from: {model_path}")
134
+ print(f"ONNX providers: {self.session.get_providers()}")
135
+ print(f"ONNX input: name={self.input_name}, shape={self.input_shape}")
136
+ print(f"ONNX input size: {self.input_width}x{self.input_height}, use_tta={self.use_tta}")
137
+ print("per-class conf: " + ", ".join(
138
+ f"{n}={t:.3f}" for n, t in zip(self.class_names,
139
+ self._conf_thres_array.tolist())))
140
+
141
+ self._warmup()
142
+
143
+ def _warmup(self, iters: int = 3) -> None:
144
+ try:
145
+ dummy = np.zeros((720, 1280, 3), dtype=np.uint8)
146
+ for _ in range(max(1, iters)):
147
+ self.predict_batch(batch_images=[dummy], offset=0, n_keypoints=0)
148
+ print(f"warmup: {iters} dummy predict_batch call(s) done")
149
+ except Exception as e:
150
+ print(f"warmup skipped: {e}")
151
+
152
+ def _read_model_class_order(self) -> "list[str] | None":
153
+ """Read the model's class order from Ultralytics ONNX metadata.
154
+ Returns the class names ordered by model-emit index, or None when the
155
+ metadata is missing/unparsable or doesn't match `class_names` as a set
156
+ (in which case the static model_class_names fallback is used)."""
157
+ try:
158
+ import ast
159
+
160
+ meta = self.session.get_modelmeta().custom_metadata_map
161
+ names = ast.literal_eval(meta["names"]) # e.g. {0: 'balaclava', ...}
162
+ if isinstance(names, dict):
163
+ order = [str(names[i]) for i in sorted(names)]
164
+ else:
165
+ order = [str(n) for n in names]
166
+ except Exception as e:
167
+ print(f"cls order: could not read ONNX names metadata ({e})")
168
+ return None
169
+ if sorted(order) != sorted(self.class_names):
170
+ print(
171
+ f"cls order: ONNX names {order} do not match expected classes "
172
+ f"{self.class_names}; ignoring metadata"
173
+ )
174
+ return None
175
+ return order
176
+
177
+ def __repr__(self) -> str:
178
+ return (
179
+ f"ONNXRuntime(session={type(self.session).__name__}, "
180
+ f"providers={self.session.get_providers()})"
181
+ )
182
+
183
+ @staticmethod
184
+ def _safe_dim(value, default: int) -> int:
185
+ return value if isinstance(value, int) and value > 0 else default
186
+
187
+ def _letterbox(self, image: ndarray, new_shape: tuple[int, int],
188
+ color=(114, 114, 114)
189
+ ) -> tuple[ndarray, float, tuple[float, float]]:
190
+ h, w = image.shape[:2]
191
+ new_w, new_h = new_shape
192
+ ratio = min(new_w / w, new_h / h)
193
+ resized_w = int(round(w * ratio))
194
+ resized_h = int(round(h * ratio))
195
+ if (resized_w, resized_h) != (w, h):
196
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
197
+ image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
198
+ dw = (new_w - resized_w) / 2.0
199
+ dh = (new_h - resized_h) / 2.0
200
+ left = int(round(dw - 0.1))
201
+ right = int(round(dw + 0.1))
202
+ top = int(round(dh - 0.1))
203
+ bottom = int(round(dh + 0.1))
204
+ padded = cv2.copyMakeBorder(image, top, bottom, left, right,
205
+ borderType=cv2.BORDER_CONSTANT, value=color)
206
+ return padded, ratio, (dw, dh)
207
+
208
+ def _preprocess(self, image: ndarray
209
+ ) -> tuple[np.ndarray, float, tuple[float, float],
210
+ tuple[int, int]]:
211
+ orig_h, orig_w = image.shape[:2]
212
+ img, ratio, pad = self._letterbox(image, (self.input_width, self.input_height))
213
+ # Fused scale(1/255) + BGR->RGB swap + HWC->NCHW + contiguous float32 in
214
+ # one optimized OpenCV call (bit-identical to the cvtColor + astype/255 +
215
+ # transpose chain, but ~half the preprocess time).
216
+ blob = cv2.dnn.blobFromImage(img, scalefactor=1.0 / 255.0, swapRB=True)
217
+ return blob, ratio, pad, (orig_w, orig_h)
218
+
219
+ @staticmethod
220
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
221
+ w, h = image_size
222
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
223
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
224
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
225
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
226
+ return boxes
227
+
228
+ @staticmethod
229
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
230
+ out = np.empty_like(boxes)
231
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
232
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
233
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
234
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
235
+ return out
236
+
237
+ @staticmethod
238
+ def _hard_nms(boxes: np.ndarray, scores: np.ndarray,
239
+ iou_thresh: float) -> np.ndarray:
240
+ n = len(boxes)
241
+ if n == 0:
242
+ return np.array([], dtype=np.intp)
243
+ order = np.argsort(-scores)
244
+ keep: list[int] = []
245
+ while len(order) > 0:
246
+ i = int(order[0])
247
+ keep.append(i)
248
+ if len(order) == 1:
249
+ break
250
+ rest = order[1:]
251
+ xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
252
+ yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
253
+ xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
254
+ yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
255
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
256
+ a_i = (max(0.0, boxes[i, 2] - boxes[i, 0]) *
257
+ max(0.0, boxes[i, 3] - boxes[i, 1]))
258
+ a_r = (np.maximum(0.0, boxes[rest, 2] - boxes[rest, 0]) *
259
+ np.maximum(0.0, boxes[rest, 3] - boxes[rest, 1]))
260
+ iou = inter / (a_i + a_r - inter + 1e-7)
261
+ order = rest[iou <= iou_thresh]
262
+ return np.array(keep, dtype=np.intp)
263
+
264
+ def _per_class_hard_nms(self, boxes: np.ndarray, scores: np.ndarray,
265
+ cls_ids: np.ndarray, iou_thresh: float
266
+ ) -> np.ndarray:
267
+ if len(boxes) == 0:
268
+ return np.array([], dtype=np.intp)
269
+ all_keep: list[int] = []
270
+ for c in np.unique(cls_ids):
271
+ mask = cls_ids == c
272
+ indices = np.where(mask)[0]
273
+ keep = self._hard_nms(boxes[mask], scores[mask], iou_thresh)
274
+ all_keep.extend(indices[keep].tolist())
275
+ all_keep.sort()
276
+ return np.array(all_keep, dtype=np.intp)
277
+
278
+ def _cross_class_dedup_op(self, boxes: np.ndarray, scores: np.ndarray,
279
+ cls_ids: np.ndarray, iou_thresh: float
280
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
281
+ n = len(boxes)
282
+ if n <= 1:
283
+ return boxes, scores, cls_ids
284
+ boxes = np.asarray(boxes, dtype=np.float32)
285
+ scores = np.asarray(scores, dtype=np.float32)
286
+ cls_ids = np.asarray(cls_ids, dtype=np.int32)
287
+ areas = (np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) *
288
+ np.maximum(0.0, boxes[:, 3] - boxes[:, 1]))
289
+ margins = scores - self._conf_thres_array[cls_ids]
290
+ order = np.lexsort((-areas, -margins))
291
+ suppressed = np.zeros(n, dtype=bool)
292
+ keep: list[int] = []
293
+ for i in order:
294
+ if suppressed[i]:
295
+ continue
296
+ keep.append(int(i))
297
+ bi = boxes[i]
298
+ xx1 = np.maximum(bi[0], boxes[:, 0])
299
+ yy1 = np.maximum(bi[1], boxes[:, 1])
300
+ xx2 = np.minimum(bi[2], boxes[:, 2])
301
+ yy2 = np.minimum(bi[3], boxes[:, 3])
302
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
303
+ a_i = max(1e-7, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
304
+ iou = inter / (a_i + areas - inter + 1e-7)
305
+ dup = iou > iou_thresh
306
+ dup[i] = False
307
+ suppressed |= dup
308
+ keep_idx = np.array(keep, dtype=np.intp)
309
+ return boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx]
310
+
311
+ @staticmethod
312
+ def _max_score_per_cluster(post_boxes: np.ndarray,
313
+ post_cls: np.ndarray,
314
+ full_boxes: np.ndarray,
315
+ full_scores: np.ndarray,
316
+ full_cls: np.ndarray,
317
+ iou_thresh: float) -> np.ndarray:
318
+ n = len(post_boxes)
319
+ if n == 0:
320
+ return np.empty(0, dtype=np.float32)
321
+ full_areas = (np.maximum(0.0, full_boxes[:, 2] - full_boxes[:, 0]) *
322
+ np.maximum(0.0, full_boxes[:, 3] - full_boxes[:, 1]))
323
+ out = np.empty(n, dtype=np.float32)
324
+ for i in range(n):
325
+ bi = post_boxes[i]
326
+ xx1 = np.maximum(bi[0], full_boxes[:, 0])
327
+ yy1 = np.maximum(bi[1], full_boxes[:, 1])
328
+ xx2 = np.minimum(bi[2], full_boxes[:, 2])
329
+ yy2 = np.minimum(bi[3], full_boxes[:, 3])
330
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
331
+ a_i = max(0.0, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
332
+ iou = inter / (a_i + full_areas - inter + 1e-7)
333
+ cluster = (iou >= iou_thresh) & (full_cls == post_cls[i])
334
+ out[i] = float(np.max(full_scores[cluster])) if np.any(cluster) else 0.0
335
+ return out
336
+
337
+ def _conf_filter_mask(self, scores: np.ndarray,
338
+ cls_ids: np.ndarray) -> np.ndarray:
339
+ """Boolean keep-mask: score >= per-class threshold, with a per-class
340
+ rescue — if a class has zero boxes passing, admit its top-1 candidate
341
+ when its score >= (per-class threshold - per-class bonus)."""
342
+ if len(scores) == 0:
343
+ return np.zeros(0, dtype=bool)
344
+ thr = self._conf_thres_array[cls_ids]
345
+ keep = scores >= thr
346
+ for c in np.unique(cls_ids):
347
+ b = float(self._bonus_array[c])
348
+ if b <= 0.0:
349
+ continue
350
+ cm = cls_ids == c
351
+ if keep[cm].any():
352
+ continue
353
+ idx = np.where(cm)[0]
354
+ top = int(idx[int(np.argmax(scores[idx]))])
355
+ if scores[top] >= self._conf_thres_array[c] - b:
356
+ keep[top] = True
357
+ return keep
358
+
359
+ def _per_view_pipeline(self, boxes: np.ndarray, scores: np.ndarray,
360
+ cls_ids: np.ndarray
361
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
362
+ if len(boxes) > 1:
363
+ keep = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
364
+ boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
365
+ if len(scores) > self.max_det:
366
+ top = np.argsort(-scores)[: self.max_det]
367
+ boxes, scores, cls_ids = boxes[top], scores[top], cls_ids[top]
368
+ if len(boxes) > 1:
369
+ boxes, scores, cls_ids = self._cross_class_dedup_op(
370
+ boxes, scores, cls_ids, self.cross_iou_thresh
371
+ )
372
+ return boxes, scores, cls_ids
373
+
374
+ def _decode_final_dets(self, preds: np.ndarray, ratio: float,
375
+ pad: tuple[float, float],
376
+ orig_size: tuple[int, int]) -> list[BoundingBox]:
377
+ if preds.ndim == 3 and preds.shape[0] == 1:
378
+ preds = preds[0]
379
+ if preds.ndim != 2 or preds.shape[1] < 6:
380
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
381
+
382
+ boxes = preds[:, :4].astype(np.float32)
383
+ scores = preds[:, 4].astype(np.float32)
384
+ cls_ids = preds[:, 5].astype(np.int32)
385
+
386
+ # Remap model cls_ids -> output cls_ids BEFORE the conf filter, so the
387
+ # per-class threshold/bonus arrays (indexed in `class_names` order) are
388
+ # applied to the right class.
389
+ n_model_cls = len(self.model_class_names)
390
+ vmask = (cls_ids >= 0) & (cls_ids < n_model_cls)
391
+ boxes, scores, cls_ids = boxes[vmask], scores[vmask], cls_ids[vmask]
392
+ cls_ids = self.cls_remap[cls_ids]
393
+
394
+ keep = self._conf_filter_mask(scores, cls_ids)
395
+ boxes = boxes[keep]
396
+ scores = scores[keep]
397
+ cls_ids = cls_ids[keep]
398
+ if len(boxes) == 0:
399
+ return []
400
+
401
+ pad_w, pad_h = pad
402
+ boxes[:, [0, 2]] -= pad_w
403
+ boxes[:, [1, 3]] -= pad_h
404
+ boxes /= ratio
405
+ boxes = self._clip_boxes(boxes, orig_size)
406
+
407
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
408
+ return self._build_results(boxes, scores, cls_ids)
409
+
410
+ def _decode_raw_yolo(self, preds: np.ndarray, ratio: float,
411
+ pad: tuple[float, float],
412
+ orig_size: tuple[int, int]) -> list[BoundingBox]:
413
+ if preds.ndim != 3 or preds.shape[0] != 1:
414
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
415
+ preds = preds[0]
416
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
417
+ preds = preds.T
418
+ if preds.ndim != 2 or preds.shape[1] < 5:
419
+ raise ValueError(f"Unexpected raw output shape: {preds.shape}")
420
+
421
+ boxes_xywh = preds[:, :4].astype(np.float32)
422
+ cls_part = preds[:, 4:].astype(np.float32)
423
+ if cls_part.shape[1] == 1:
424
+ scores = cls_part[:, 0]
425
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
426
+ else:
427
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
428
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
429
+
430
+ # Remap model cls_ids -> output cls_ids BEFORE the conf filter, so the
431
+ # per-class threshold/bonus arrays (indexed in `class_names` order) are
432
+ # applied to the right class.
433
+ n_model_cls = len(self.model_class_names)
434
+ vmask = (cls_ids >= 0) & (cls_ids < n_model_cls)
435
+ boxes_xywh, scores, cls_ids = boxes_xywh[vmask], scores[vmask], cls_ids[vmask]
436
+ cls_ids = self.cls_remap[cls_ids]
437
+
438
+ keep = self._conf_filter_mask(scores, cls_ids)
439
+ boxes_xywh = boxes_xywh[keep]
440
+ scores = scores[keep]
441
+ cls_ids = cls_ids[keep]
442
+ if len(boxes_xywh) == 0:
443
+ return []
444
+ boxes = self._xywh_to_xyxy(boxes_xywh)
445
+
446
+ pad_w, pad_h = pad
447
+ boxes[:, [0, 2]] -= pad_w
448
+ boxes[:, [1, 3]] -= pad_h
449
+ boxes /= ratio
450
+ boxes = self._clip_boxes(boxes, orig_size)
451
+
452
+ boxes, scores, cls_ids = self._per_view_pipeline(boxes, scores, cls_ids)
453
+ return self._build_results(boxes, scores, cls_ids)
454
+
455
+ def _shrink_boxes(self, boxes: np.ndarray) -> np.ndarray:
456
+ """Scale every xyxy box toward its own center by `box_shrink`.
457
+ Center, class and score are untouched; only the extent changes."""
458
+ scale = float(self.box_shrink)
459
+ if len(boxes) == 0 or scale >= 1.0:
460
+ return boxes
461
+ boxes = np.asarray(boxes, dtype=np.float32)
462
+ cx = (boxes[:, 0] + boxes[:, 2]) * 0.5
463
+ cy = (boxes[:, 1] + boxes[:, 3]) * 0.5
464
+ w = np.maximum(0.0, boxes[:, 2] - boxes[:, 0])
465
+ h = np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
466
+ # Shrink, but never past min_box_size and never larger than the original
467
+ # (the floor must not inflate an already-tiny detection).
468
+ new_w = np.minimum(np.maximum(w * scale, self.min_box_size), w)
469
+ new_h = np.minimum(np.maximum(h * scale, self.min_box_size), h)
470
+ out = np.empty_like(boxes)
471
+ out[:, 0] = cx - new_w * 0.5
472
+ out[:, 1] = cy - new_h * 0.5
473
+ out[:, 2] = cx + new_w * 0.5
474
+ out[:, 3] = cy + new_h * 0.5
475
+ return out
476
+
477
+ def _build_results(self, boxes: np.ndarray, scores: np.ndarray,
478
+ cls_ids: np.ndarray) -> list[BoundingBox]:
479
+ boxes = self._shrink_boxes(boxes)
480
+ results: list[BoundingBox] = []
481
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
482
+ x1, y1, x2, y2 = box.tolist()
483
+ # Round to nearest instead of floor/ceil: the old outward
484
+ # rounding grew every box by up to 1 px on each of the 4 edges.
485
+ ix1, iy1 = int(round(x1)), int(round(y1))
486
+ ix2, iy2 = int(round(x2)), int(round(y2))
487
+ if ix2 <= ix1 or iy2 <= iy1:
488
+ continue
489
+ results.append(
490
+ BoundingBox(
491
+ x1=ix1, y1=iy1, x2=ix2, y2=iy2,
492
+ cls_id=int(cls_id),
493
+ conf=float(conf),
494
+ )
495
+ )
496
+ return results
497
+
498
+ def _postprocess(self, output: np.ndarray, ratio: float,
499
+ pad: tuple[float, float],
500
+ orig_size: tuple[int, int]) -> list[BoundingBox]:
501
+ if output.ndim == 2 and output.shape[1] >= 6:
502
+ return self._decode_final_dets(output, ratio, pad, orig_size)
503
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
504
+ return self._decode_final_dets(output, ratio, pad, orig_size)
505
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
506
+
507
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
508
+ if image is None:
509
+ raise ValueError("Input image is None")
510
+ if not isinstance(image, np.ndarray):
511
+ raise TypeError(f"Input is not numpy array: {type(image)}")
512
+ if image.ndim != 3:
513
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
514
+ if image.shape[2] != 3:
515
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
516
+ if image.dtype != np.uint8:
517
+ image = image.astype(np.uint8)
518
+
519
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
520
+ expected = (1, 3, self.input_height, self.input_width)
521
+ if input_tensor.shape != expected:
522
+ raise ValueError(
523
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected}"
524
+ )
525
+
526
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
527
+ return self._postprocess(outputs[0], ratio, pad, orig_size)
528
+
529
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
530
+ boxes_orig = self._predict_single(image)
531
+ flipped = cv2.flip(image, 1)
532
+ boxes_flip = self._predict_single(flipped)
533
+ w = image.shape[1]
534
+ boxes_flip = [
535
+ BoundingBox(
536
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
537
+ cls_id=b.cls_id, conf=b.conf,
538
+ )
539
+ for b in boxes_flip
540
+ ]
541
+ all_boxes = boxes_orig + boxes_flip
542
+ if not all_boxes:
543
+ return []
544
+
545
+ coords = np.array(
546
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
547
+ )
548
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
549
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
550
+
551
+ hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
552
+ if len(hard_keep) == 0:
553
+ return []
554
+ if len(hard_keep) > self.max_det:
555
+ top = np.argsort(-scores[hard_keep])[: self.max_det]
556
+ hard_keep = hard_keep[top]
557
+ boosted = self._max_score_per_cluster(
558
+ coords[hard_keep], cls_ids[hard_keep],
559
+ coords, scores, cls_ids, self.iou_thres,
560
+ )
561
+
562
+ kept_coords = coords[hard_keep]
563
+ kept_cls = cls_ids[hard_keep]
564
+ if len(kept_coords) > 1:
565
+ kept_coords, boosted, kept_cls = self._cross_class_dedup_op(
566
+ kept_coords, boosted, kept_cls, self.cross_iou_thresh
567
+ )
568
+
569
+ return [
570
+ BoundingBox(
571
+ x1=int(math.floor(kept_coords[j, 0])),
572
+ y1=int(math.floor(kept_coords[j, 1])),
573
+ x2=int(math.ceil(kept_coords[j, 2])),
574
+ y2=int(math.ceil(kept_coords[j, 3])),
575
+ cls_id=int(kept_cls[j]),
576
+ conf=float(boosted[j]),
577
+ )
578
+ for j in range(len(kept_coords))
579
+ ]
580
+
581
+ def predict_batch(self, batch_images: list[ndarray], offset: int,
582
+ n_keypoints: int) -> list[TVFrameResult]:
583
+ results: list[TVFrameResult] = []
584
+ predict = self._predict_tta if self.use_tta else self._predict_single
585
+ for frame_number_in_batch, image in enumerate(batch_images):
586
+ try:
587
+ boxes = predict(image)
588
+ except Exception as e:
589
+ print(f"Inference failed for frame {offset + frame_number_in_batch}: {e}")
590
+ boxes = []
591
+ results.append(
592
+ TVFrameResult(
593
+ frame_id=offset + frame_number_in_batch,
594
+ boxes=boxes,
595
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
596
+ )
597
+ )
598
+ return results
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:412938d71d10d1ab492640c3008ce055e159f3e5f37b4a6deeb36071ae5f0fad
3
+ size 9844576