meaculpitt commited on
Commit
bd1b95d
·
verified ·
1 Parent(s): 0a3be70

v1 crime weights (yolo26s 1280 e2e, 6 classes validator-aligned, 8.7k merged dataset, val mAP50=0.8301)

Browse files
Files changed (6) hide show
  1. README.md +21 -0
  2. chute_config.yml +27 -0
  3. class_names.txt +6 -0
  4. miner.py +343 -0
  5. model_type.json +4 -0
  6. weights.onnx +3 -0
README.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - element_type:detect
4
+ - model:yolov26-small
5
+ - object:balaclava
6
+ - object:hoodie
7
+ - object:glove
8
+ - object:bat
9
+ - object:spray-paint
10
+ - object:graffiti
11
+ manako:
12
+ description: SN44 crime detection — YOLOv26-small trained natively in validator class order [balaclava, hoodie, glove, bat, spray paint, graffiti] on a multi-source merged ~8.7k-image dataset (Roboflow Universe — test-pvctt/cover-no-aug, baseball-v1/baseball-and-bat, test-el83b/glove-absoo, natalieglove-ykc4i/glove-0pewz, student-b2pa9/hoodie-hjihp, ahmads-workspace-spqp0/wibu-detector-5okbw, gama-yvduk/hoodie-hnu6d, brave-official/hoodie, labeling-dataset-hology-70-train/deteksi-hoodie, trucks-i0qg4/spray-drulu, itmo-0kdik/graffiti-wvjbp).
13
+ input_payload:
14
+ - name: frame
15
+ type: image
16
+ description: RGB frame
17
+ output_payload:
18
+ - name: detections
19
+ type: detections
20
+ description: List of detections (balaclava / hoodie / glove / bat / spray paint / graffiti) with bbox + confidence
21
+ ---
chute_config.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Image:
2
+ from_base: parachutes/python:3.12
3
+ run_command:
4
+ - pip install --upgrade setuptools wheel
5
+ - pip install 'numpy>=1.23' 'onnxruntime-gpu[cuda,cudnn]>=1.16' 'opencv-python>=4.7' 'pillow>=9.5' 'huggingface_hub>=0.19.4' 'pydantic>=2.0' 'pyyaml>=6.0' 'aiohttp>=3.9'
6
+ - pip install torch torchvision
7
+
8
+ NodeSelector:
9
+ gpu_count: 1
10
+ min_vram_gb_per_gpu: 16
11
+ max_hourly_price_per_gpu: 0.5 # ← lower than beverage's $2.00; experimental
12
+ exclude: # ← exclude-only (no include pinning, unlike beverage)
13
+ - "5090"
14
+ - b200
15
+ - h200
16
+ - h20
17
+ - mi300x
18
+
19
+ Chute:
20
+ timeout_seconds: 900
21
+ concurrency: 4
22
+ max_instances: 5
23
+ scaling_threshold: 0.5
24
+ shutdown_after_seconds: 288000 # 80h idle (matches beverage)
25
+ # tee: false — omitted entirely (beverage uses tee: true; the SN44 repo
26
+ # example doesn't require TEE; testing whether crime element scores
27
+ # without it).
class_names.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ balaclava
2
+ hoodie
3
+ glove
4
+ bat
5
+ spray paint
6
+ graffiti
miner.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # build-marker: v1-yolo26s-1280-tta
2
+ """SN44 crime detection miner — single-element chute for manak0/Detect-crime.
3
+
4
+ Adapted from beverage v5 miner.py with these crime-specific changes:
5
+ - class_names = ["balaclava","hoodie","glove","bat","spray paint","graffiti"]
6
+ - cls_remap = identity (model trained natively in validator class order, no remap needed)
7
+ - conf_threshold = 0.52 (alfred-aligned, slightly looser than beverage's 0.55)
8
+ - iou_thresh = 0.4 (slightly tighter than beverage's 0.5)
9
+ - min_box_area = 196 (14x14 px², larger than beverage's 100; kills tiny FPs aggressively)
10
+ - weights.onnx is yolo26s e2e at 1280x1280 input
11
+
12
+ Pipeline:
13
+ preprocess (letterbox 1280, cubic upscale) -> ONNX (e2e [1,300,6])
14
+ -> conf filter -> per-class hard NMS -> cross-class dedup -> geometry filter
15
+ -> TTA (h-flip + conf-boost on consensus) -> BoundingBox list
16
+ """
17
+ import math
18
+ from pathlib import Path
19
+
20
+ import cv2
21
+ import numpy as np
22
+ import onnxruntime as ort
23
+ from numpy import ndarray
24
+ from pydantic import BaseModel
25
+
26
+
27
+ class BoundingBox(BaseModel):
28
+ x1: int
29
+ y1: int
30
+ x2: int
31
+ y2: int
32
+ cls_id: int
33
+ conf: float
34
+
35
+
36
+ class TVFrameResult(BaseModel):
37
+ frame_id: int
38
+ boxes: list[BoundingBox]
39
+ keypoints: list[tuple[int, int]]
40
+
41
+
42
+ class Miner:
43
+ """yolo26s e2e ONNX miner for manak0/Detect-crime.
44
+ Chute platform calls predict_batch(batch_images, offset, n_keypoints).
45
+ """
46
+
47
+ def __init__(self, path_hf_repo) -> None:
48
+ self.path_hf_repo = Path(path_hf_repo)
49
+
50
+ # Validator class order — model trained natively in this order so identity remap.
51
+ self.class_names = ["balaclava", "hoodie", "glove", "bat", "spray paint", "graffiti"]
52
+ self.cls_remap = np.arange(len(self.class_names), dtype=np.int32)
53
+
54
+ try:
55
+ ort.preload_dlls()
56
+ except Exception:
57
+ pass
58
+
59
+ sess_options = ort.SessionOptions()
60
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
61
+
62
+ try:
63
+ self.session = ort.InferenceSession(
64
+ str(self.path_hf_repo / "weights.onnx"),
65
+ sess_options=sess_options,
66
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
67
+ )
68
+ except Exception:
69
+ self.session = ort.InferenceSession(
70
+ str(self.path_hf_repo / "weights.onnx"),
71
+ sess_options=sess_options,
72
+ providers=["CPUExecutionProvider"],
73
+ )
74
+
75
+ self.input_name = self.session.get_inputs()[0].name
76
+ self.output_names = [o.name for o in self.session.get_outputs()]
77
+
78
+ # Match exported ONNX resolution.
79
+ self.input_h = 1280
80
+ self.input_w = 1280
81
+
82
+ # alfred-aligned crime thresholds.
83
+ self.conf_threshold = 0.52
84
+ self.iou_thresh = 0.4 # per-class hard NMS
85
+ self.cross_iou_thresh = 0.7 # cross-class dedup
86
+ self.max_det = 150
87
+ self.use_tta = True
88
+
89
+ # Geometry filters (alfred crime values).
90
+ self.min_box_area = 196 # 14x14 px²
91
+ self.min_side = 8
92
+ self.max_aspect_ratio = 8.0
93
+
94
+ # GPU warmup.
95
+ warm = np.zeros((self.input_h, self.input_w, 3), dtype=np.uint8)
96
+ for _ in range(5):
97
+ try:
98
+ self._infer_single(warm)
99
+ except Exception:
100
+ break
101
+
102
+ def __repr__(self) -> str:
103
+ return (
104
+ f"CrimeMiner v1 input={self.input_h}x{self.input_w} "
105
+ f"classes={len(self.class_names)} use_tta={self.use_tta} "
106
+ f"providers={self.session.get_providers()}"
107
+ )
108
+
109
+ # ---------------------------------------------------------------- preproc
110
+ def _letterbox(self, image: ndarray) -> tuple[ndarray, float, tuple[float, float]]:
111
+ """Aspect-preserving resize + 114-grey pad to (input_h, input_w).
112
+ Cubic when upscaling (small-object fidelity), linear when downscaling.
113
+ """
114
+ h, w = image.shape[:2]
115
+ ratio = min(self.input_w / w, self.input_h / h)
116
+ nw, nh = int(round(w * ratio)), int(round(h * ratio))
117
+ if (nw, nh) != (w, h):
118
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
119
+ resized = cv2.resize(image, (nw, nh), interpolation=interp)
120
+ else:
121
+ resized = image
122
+ canvas = np.full((self.input_h, self.input_w, 3), 114, dtype=np.uint8)
123
+ dy = (self.input_h - nh) // 2
124
+ dx = (self.input_w - nw) // 2
125
+ canvas[dy:dy + nh, dx:dx + nw] = resized
126
+ return canvas, ratio, (float(dx), float(dy))
127
+
128
+ def _preprocess(self, image_bgr: ndarray):
129
+ canvas, ratio, pad = self._letterbox(image_bgr)
130
+ rgb = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
131
+ x = (rgb.astype(np.float32) / 255.0).transpose(2, 0, 1)[None, ...]
132
+ return np.ascontiguousarray(x, dtype=np.float32), ratio, pad
133
+
134
+ # ---------------------------------------------------------------- nms helpers
135
+ @staticmethod
136
+ def _hard_nms(boxes: ndarray, scores: ndarray, iou_thresh: float) -> ndarray:
137
+ n = len(boxes)
138
+ if n == 0:
139
+ return np.array([], dtype=np.intp)
140
+ order = np.argsort(scores)[::-1]
141
+ keep: list[int] = []
142
+ suppressed = np.zeros(n, dtype=bool)
143
+ for i in range(n):
144
+ idx = order[i]
145
+ if suppressed[idx]:
146
+ continue
147
+ keep.append(int(idx))
148
+ bi = boxes[idx]
149
+ for k in range(i + 1, n):
150
+ jdx = order[k]
151
+ if suppressed[jdx]:
152
+ continue
153
+ bj = boxes[jdx]
154
+ xx1 = max(bi[0], bj[0]); yy1 = max(bi[1], bj[1])
155
+ xx2 = min(bi[2], bj[2]); yy2 = min(bi[3], bj[3])
156
+ inter = max(0.0, xx2 - xx1) * max(0.0, yy2 - yy1)
157
+ ai = (bi[2] - bi[0]) * (bi[3] - bi[1])
158
+ aj = (bj[2] - bj[0]) * (bj[3] - bj[1])
159
+ iou = inter / (ai + aj - inter + 1e-7)
160
+ if iou > iou_thresh:
161
+ suppressed[jdx] = True
162
+ return np.array(keep, dtype=np.intp)
163
+
164
+ def _per_class_hard_nms(
165
+ self, boxes: ndarray, scores: ndarray, cls_ids: ndarray, iou_thresh: float
166
+ ) -> ndarray:
167
+ if len(boxes) == 0:
168
+ return np.array([], dtype=np.intp)
169
+ all_keep: list[int] = []
170
+ for c in np.unique(cls_ids):
171
+ mask = cls_ids == c
172
+ indices = np.where(mask)[0]
173
+ keep = self._hard_nms(boxes[mask], scores[mask], iou_thresh)
174
+ all_keep.extend(indices[keep].tolist())
175
+ all_keep.sort()
176
+ return np.array(all_keep, dtype=np.intp)
177
+
178
+ @staticmethod
179
+ def _cross_class_dedup(
180
+ boxes: ndarray, scores: ndarray, cls_ids: ndarray, iou_thresh: float
181
+ ) -> tuple[ndarray, ndarray, ndarray]:
182
+ """Suppress high-overlap duplicates across classes (FP reducer)."""
183
+ n = len(boxes)
184
+ if n <= 1:
185
+ return boxes, scores, cls_ids
186
+ areas = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
187
+ order = np.lexsort((-scores, -areas))
188
+ suppressed = np.zeros(n, dtype=bool)
189
+ keep: list[int] = []
190
+ for i in order:
191
+ if suppressed[i]:
192
+ continue
193
+ keep.append(int(i))
194
+ bi = boxes[i]
195
+ xx1 = np.maximum(bi[0], boxes[:, 0]); yy1 = np.maximum(bi[1], boxes[:, 1])
196
+ xx2 = np.minimum(bi[2], boxes[:, 2]); yy2 = np.minimum(bi[3], boxes[:, 3])
197
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
198
+ ai = max(1e-7, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
199
+ iou = inter / (ai + areas - inter + 1e-7)
200
+ dup = iou > iou_thresh
201
+ dup[i] = False
202
+ suppressed |= dup
203
+ kept = np.array(keep, dtype=np.intp)
204
+ return boxes[kept], scores[kept], cls_ids[kept]
205
+
206
+ @staticmethod
207
+ def _max_score_per_cluster(
208
+ coords: ndarray, scores: ndarray, keep_idx: ndarray, iou_thresh: float
209
+ ) -> ndarray:
210
+ """For each kept box, return max original score among any overlapping cluster member."""
211
+ if len(keep_idx) == 0:
212
+ return np.array([], dtype=np.float32)
213
+ out = np.empty(len(keep_idx), dtype=np.float32)
214
+ for j, idx in enumerate(keep_idx):
215
+ bi = coords[idx]
216
+ xx1 = np.maximum(bi[0], coords[:, 0]); yy1 = np.maximum(bi[1], coords[:, 1])
217
+ xx2 = np.minimum(bi[2], coords[:, 2]); yy2 = np.minimum(bi[3], coords[:, 3])
218
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
219
+ ai = (bi[2] - bi[0]) * (bi[3] - bi[1])
220
+ aj = (coords[:, 2] - coords[:, 0]) * (coords[:, 3] - coords[:, 1])
221
+ iou = inter / (ai + aj - inter + 1e-7)
222
+ out[j] = float(np.max(scores[iou >= iou_thresh]))
223
+ return out
224
+
225
+ # ---------------------------------------------------------------- inference
226
+ def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
227
+ inp, ratio, (dx, dy) = self._preprocess(image_bgr)
228
+ out = self.session.run(self.output_names, {self.input_name: inp})[0]
229
+ if out.ndim == 3:
230
+ out = out[0]
231
+
232
+ confs = out[:, 4].astype(np.float32)
233
+ keep = confs >= self.conf_threshold
234
+ if not keep.any():
235
+ return []
236
+ out = out[keep]
237
+
238
+ boxes = out[:, :4].astype(np.float32).copy()
239
+ confs = out[:, 4].astype(np.float32)
240
+ cls_ids = self.cls_remap[out[:, 5].astype(np.int32)]
241
+
242
+ # Reverse letterbox: model-space xyxy -> original-image xyxy
243
+ boxes[:, [0, 2]] = (boxes[:, [0, 2]] - dx) / ratio
244
+ boxes[:, [1, 3]] = (boxes[:, [1, 3]] - dy) / ratio
245
+
246
+ orig_h, orig_w = image_bgr.shape[:2]
247
+ boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, orig_w - 1)
248
+ boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, orig_h - 1)
249
+
250
+ if len(boxes) > 1:
251
+ keep_idx = self._per_class_hard_nms(boxes, confs, cls_ids, self.iou_thresh)
252
+ keep_idx = keep_idx[: self.max_det]
253
+ boxes = boxes[keep_idx]
254
+ confs = confs[keep_idx]
255
+ cls_ids = cls_ids[keep_idx]
256
+ boxes, confs, cls_ids = self._cross_class_dedup(
257
+ boxes, confs, cls_ids, self.cross_iou_thresh
258
+ )
259
+
260
+ return self._to_boundingboxes(boxes, confs, cls_ids, orig_w, orig_h)
261
+
262
+ def _infer_tta(self, image_bgr: ndarray) -> list[BoundingBox]:
263
+ """H-flip TTA: union(orig, flipped) -> per-class NMS -> conf-boost."""
264
+ boxes_orig = self._infer_single(image_bgr)
265
+
266
+ h, w = image_bgr.shape[:2]
267
+ flipped = cv2.flip(image_bgr, 1)
268
+ boxes_flip_raw = self._infer_single(flipped)
269
+ boxes_flip = [
270
+ BoundingBox(x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
271
+ cls_id=b.cls_id, conf=b.conf)
272
+ for b in boxes_flip_raw
273
+ ]
274
+
275
+ all_boxes = boxes_orig + boxes_flip
276
+ if not all_boxes:
277
+ return []
278
+
279
+ coords = np.array([[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32)
280
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
281
+ cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
282
+
283
+ keep_idx = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thresh)
284
+ if len(keep_idx) == 0:
285
+ return []
286
+ keep_idx = keep_idx[: self.max_det]
287
+ boosted = self._max_score_per_cluster(coords, scores, keep_idx, self.iou_thresh)
288
+
289
+ out_boxes: list[BoundingBox] = []
290
+ for j, idx in enumerate(keep_idx):
291
+ b = all_boxes[idx]
292
+ out_boxes.append(BoundingBox(
293
+ x1=b.x1, y1=b.y1, x2=b.x2, y2=b.y2,
294
+ cls_id=b.cls_id,
295
+ conf=max(0.0, min(1.0, float(boosted[j]))),
296
+ ))
297
+ return out_boxes
298
+
299
+ def _to_boundingboxes(
300
+ self, boxes: ndarray, confs: ndarray, cls_ids: ndarray,
301
+ orig_w: int, orig_h: int,
302
+ ) -> list[BoundingBox]:
303
+ out: list[BoundingBox] = []
304
+ for i in range(len(boxes)):
305
+ x1, y1, x2, y2 = boxes[i]
306
+ ix1 = max(0, min(orig_w, math.floor(x1)))
307
+ iy1 = max(0, min(orig_h, math.floor(y1)))
308
+ ix2 = max(0, min(orig_w, math.ceil(x2)))
309
+ iy2 = max(0, min(orig_h, math.ceil(y2)))
310
+ if ix2 <= ix1 or iy2 <= iy1:
311
+ continue
312
+ bw, bh = ix2 - ix1, iy2 - iy1
313
+ if bw * bh < self.min_box_area:
314
+ continue
315
+ if min(bw, bh) < self.min_side:
316
+ continue
317
+ ar = max(bw / max(bh, 1), bh / max(bw, 1))
318
+ if ar > self.max_aspect_ratio:
319
+ continue
320
+ out.append(BoundingBox(
321
+ x1=ix1, y1=iy1, x2=ix2, y2=iy2,
322
+ cls_id=int(cls_ids[i]),
323
+ conf=max(0.0, min(1.0, float(confs[i]))),
324
+ ))
325
+ return out
326
+
327
+ # ---------------------------------------------------------------- entry
328
+ def predict_batch(
329
+ self,
330
+ batch_images: list[ndarray],
331
+ offset: int,
332
+ n_keypoints: int,
333
+ ) -> list[TVFrameResult]:
334
+ infer = self._infer_tta if self.use_tta else self._infer_single
335
+ results: list[TVFrameResult] = []
336
+ for idx, image in enumerate(batch_images):
337
+ boxes = infer(image)
338
+ results.append(TVFrameResult(
339
+ frame_id=offset + idx,
340
+ boxes=boxes,
341
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
342
+ ))
343
+ return results
model_type.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "task_type": "object-detection",
3
+ "model_type": "yolov26-small"
4
+ }
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14cfd547ec7b6f2e675546492236b4ded323076bd72d38cf30591e2105c69ea0
3
+ size 19409670