MTerryJack commited on
Commit
89ab6da
·
verified ·
1 Parent(s): d8d3b5a

subnet_bridge: add miner.py + chute_config.yml

Browse files
Files changed (2) hide show
  1. chute_config.yml +18 -0
  2. miner.py +185 -0
chute_config.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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>=1.16' 'opencv-python>=4.7' 'pillow>=9.5' 'huggingface_hub>=0.19.4' 'pydantic>=2.0' 'pyyaml>=6.0' 'aiohttp>=3.9' 'torch>=2.8'
6
+
7
+ NodeSelector:
8
+ gpu_count: 1
9
+ min_vram_gb_per_gpu: 16
10
+ include:
11
+ - pro_6000
12
+
13
+ Chute:
14
+ timeout_seconds: 300
15
+ concurrency: 4
16
+ max_instances: 5
17
+ scaling_threshold: 0.5
18
+ tee: true
miner.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_NAMES = ['gun', 'bullets', 'blade', 'blunt force weapon', 'projectile', 'explosive', 'spray', 'projectile launcher']
27
+ TASK_TYPE = 'instance-segmentation'
28
+ NUM_MASK_COEFFS = 32
29
+
30
+
31
+ class Miner:
32
+ """
33
+ Auto-generated by subnet_bridge from a Manako element repo.
34
+ This miner is intentionally self-contained for chute import restrictions.
35
+ """
36
+
37
+ def __init__(self, path_hf_repo: Path) -> None:
38
+ self.path_hf_repo = path_hf_repo
39
+ self.class_names = list(CLASS_NAMES)
40
+ self.session = ort.InferenceSession(
41
+ str(path_hf_repo / "weights.onnx"),
42
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
43
+ )
44
+ self.input_name = self.session.get_inputs()[0].name
45
+ input_shape = self.session.get_inputs()[0].shape
46
+ # expected [N, C, H, W]
47
+ self.input_h = int(input_shape[2])
48
+ self.input_w = int(input_shape[3])
49
+ self.conf_threshold = 0.25
50
+ self.iou_threshold = 0.45
51
+
52
+ def __repr__(self) -> str:
53
+ return f"ONNX Miner session={type(self.session).__name__} classes={len(self.class_names)}"
54
+
55
+ def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, tuple[int, int]]:
56
+ h, w = image_bgr.shape[:2]
57
+ rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
58
+ resized = cv2.resize(rgb, (self.input_w, self.input_h))
59
+ x = resized.astype(np.float32) / 255.0
60
+ x = np.transpose(x, (2, 0, 1))[None, ...]
61
+ return x, (h, w)
62
+
63
+ def _normalize_predictions(self, raw: np.ndarray) -> np.ndarray:
64
+ # Common ultralytics export shapes:
65
+ # - [1, C, N] where C=4+num_classes
66
+ # - [1, N, C]
67
+ pred = raw[0]
68
+ if pred.ndim != 2:
69
+ raise ValueError(f"Unexpected prediction shape: {raw.shape}")
70
+ if pred.shape[0] < pred.shape[1]:
71
+ pred = pred.transpose(1, 0)
72
+ return pred
73
+
74
+ def _nms(self, dets: list[tuple[float, float, float, float, float, int]]) -> list[tuple[float, float, float, float, float, int]]:
75
+ if not dets:
76
+ return []
77
+
78
+ boxes = np.array([[d[0], d[1], d[2], d[3]] for d in dets], dtype=np.float32)
79
+ scores = np.array([d[4] for d in dets], dtype=np.float32)
80
+ order = scores.argsort()[::-1]
81
+ keep = []
82
+
83
+ while order.size > 0:
84
+ i = order[0]
85
+ keep.append(i)
86
+
87
+ xx1 = np.maximum(boxes[i, 0], boxes[order[1:], 0])
88
+ yy1 = np.maximum(boxes[i, 1], boxes[order[1:], 1])
89
+ xx2 = np.minimum(boxes[i, 2], boxes[order[1:], 2])
90
+ yy2 = np.minimum(boxes[i, 3], boxes[order[1:], 3])
91
+
92
+ w = np.maximum(0.0, xx2 - xx1)
93
+ h = np.maximum(0.0, yy2 - yy1)
94
+ inter = w * h
95
+
96
+ area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
97
+ area_rest = (boxes[order[1:], 2] - boxes[order[1:], 0]) * (boxes[order[1:], 3] - boxes[order[1:], 1])
98
+ union = np.maximum(area_i + area_rest - inter, 1e-6)
99
+ iou = inter / union
100
+
101
+ remaining = np.where(iou <= self.iou_threshold)[0]
102
+ order = order[remaining + 1]
103
+
104
+ return [dets[idx] for idx in keep]
105
+
106
+ def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
107
+ inp, (orig_h, orig_w) = self._preprocess(image_bgr)
108
+ out = self.session.run(None, {self.input_name: inp})[0]
109
+ pred = self._normalize_predictions(out)
110
+
111
+ nc = len(CLASS_NAMES)
112
+ nm = NUM_MASK_COEFFS
113
+ expected_channels = 4 + nc + nm
114
+ if pred.shape[1] != expected_channels:
115
+ raise ValueError(
116
+ f"Unexpected prediction channels: got {pred.shape[1]}, expected "
117
+ f"{expected_channels} (4 box + {nc} classes + {nm} mask coeffs; task={TASK_TYPE})"
118
+ )
119
+
120
+ boxes = pred[:, :4]
121
+ cls_scores = pred[:, 4 : 4 + nc]
122
+
123
+ cls_ids = np.argmax(cls_scores, axis=1)
124
+ confs = np.max(cls_scores, axis=1)
125
+ if cls_ids.size and int(cls_ids.max()) >= nc:
126
+ raise ValueError(f"class id {int(cls_ids.max())} out of range for nc={nc}")
127
+ keep = confs >= self.conf_threshold
128
+
129
+ boxes = boxes[keep]
130
+ confs = confs[keep]
131
+ cls_ids = cls_ids[keep]
132
+
133
+ if boxes.shape[0] == 0:
134
+ return []
135
+
136
+ sx = orig_w / float(self.input_w)
137
+ sy = orig_h / float(self.input_h)
138
+
139
+ dets: list[tuple[float, float, float, float, float, int]] = []
140
+ for i in range(boxes.shape[0]):
141
+ cx, cy, bw, bh = boxes[i].tolist()
142
+ x1 = (cx - bw / 2.0) * sx
143
+ y1 = (cy - bh / 2.0) * sy
144
+ x2 = (cx + bw / 2.0) * sx
145
+ y2 = (cy + bh / 2.0) * sy
146
+ dets.append((x1, y1, x2, y2, float(confs[i]), int(cls_ids[i])))
147
+
148
+ dets = self._nms(dets)
149
+
150
+ out_boxes: list[BoundingBox] = []
151
+ for x1, y1, x2, y2, conf, cls_id in dets:
152
+ ix1 = max(0, min(orig_w, math.floor(x1)))
153
+ iy1 = max(0, min(orig_h, math.floor(y1)))
154
+ ix2 = max(0, min(orig_w, math.ceil(x2)))
155
+ iy2 = max(0, min(orig_h, math.ceil(y2)))
156
+ out_boxes.append(
157
+ BoundingBox(
158
+ x1=ix1,
159
+ y1=iy1,
160
+ x2=ix2,
161
+ y2=iy2,
162
+ cls_id=cls_id,
163
+ conf=max(0.0, min(1.0, conf)),
164
+ )
165
+ )
166
+ return out_boxes
167
+
168
+ def predict_batch(
169
+ self,
170
+ batch_images: list[ndarray],
171
+ offset: int,
172
+ n_keypoints: int,
173
+ ) -> list[TVFrameResult]:
174
+ results: list[TVFrameResult] = []
175
+ for idx, image in enumerate(batch_images):
176
+ boxes = self._infer_single(image)
177
+ keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
178
+ results.append(
179
+ TVFrameResult(
180
+ frame_id=offset + idx,
181
+ boxes=boxes,
182
+ keypoints=keypoints,
183
+ )
184
+ )
185
+ return results