SuperBitDev commited on
Commit
5aedfc7
·
verified ·
1 Parent(s): f5459b0

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. chute_config.yml +27 -0
  2. miner.py +217 -0
  3. weights.onnx +3 -0
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 --index-url https://download.pytorch.org/whl/cu128 torch torchvision
6
+ - 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'
7
+ - pip install onnxruntime-gpu
8
+ set_workdir: /app
9
+ readme: "Image for chutes"
10
+
11
+ NodeSelector:
12
+ gpu_count: 1
13
+ min_vram_gb_per_gpu: 24
14
+ min_memory_gb: 32
15
+ min_cpu_count: 32
16
+
17
+ exclude:
18
+ - b200
19
+ - h200
20
+ - mi300x
21
+
22
+ Chute:
23
+ timeout_seconds: 900
24
+ concurrency: 4
25
+ max_instances: 5
26
+ scaling_threshold: 0.5
27
+ shutdown_after_seconds: 288000
miner.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch
10
+ from torchvision.ops import nms
11
+ from time import time
12
+
13
+ class BoundingBox(BaseModel):
14
+ x1: int
15
+ y1: int
16
+ x2: int
17
+ y2: int
18
+ cls_id: int
19
+ conf: float
20
+
21
+
22
+ class TVFrameResult(BaseModel):
23
+ frame_id: int
24
+ boxes: list[BoundingBox]
25
+ keypoints: list[tuple[int, int]]
26
+
27
+
28
+ class Miner:
29
+ """
30
+ Auto-generated by subnet_bridge from a Manako element repo.
31
+ This miner is intentionally self-contained for chute import restrictions.
32
+ """
33
+
34
+ def __init__(self, path_hf_repo: Path) -> None:
35
+ self.path_hf_repo = path_hf_repo
36
+ self.class_names = ['person']
37
+
38
+ onnx_path = path_hf_repo / "weights.onnx"
39
+ providers = ["CPUExecutionProvider"]
40
+ try:
41
+ # request CUDA first, fallback to CPU if not available
42
+ self.sess = ort.InferenceSession(onnx_path, providers=["CUDAExecutionProvider","CPUExecutionProvider"])
43
+ except Exception:
44
+ self.sess = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
45
+
46
+ model_input = self.sess.get_inputs()[0]
47
+ self.input_name = model_input.name
48
+ self.input_size = model_input.shape[2] # expected H (and W) from the model
49
+ self.conf_threshold = 0.3
50
+ self.iou_threshold = 0.3
51
+
52
+ def __repr__(self) -> str:
53
+ return f"ONNX Miner session={type(self.sess).__name__} classes={len(self.class_names)}"
54
+
55
+ def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, tuple[int, int]]:
56
+ image = image_bgr.copy()
57
+ shape = image.shape[:2] # (H, W)
58
+
59
+ sz = self.input_size
60
+ r = sz / max(shape[0], shape[1])
61
+ if r != 1:
62
+ resample = cv2.INTER_LINEAR if r > 1 else cv2.INTER_AREA
63
+ image = cv2.resize(image, dsize=(int(shape[1] * r), int(shape[0] * r)), interpolation=resample)
64
+ height, width = image.shape[:2]
65
+
66
+ r2 = min(1.0, sz / height, sz / width)
67
+
68
+ pad_w = int(round(width * r2))
69
+ pad_h = int(round(height * r2))
70
+ w = (sz - pad_w) / 2.0
71
+ h = (sz - pad_h) / 2.0
72
+
73
+ # resize to pad if different
74
+ if (width, height) != (pad_w, pad_h):
75
+ image = cv2.resize(image, (pad_w, pad_h), interpolation=cv2.INTER_LINEAR)
76
+
77
+ top = int(round(h - 0.1)); bottom = int(round(h + 0.1))
78
+ left = int(round(w - 0.1)); right = int(round(w + 0.1))
79
+ image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT) # add border
80
+ # Convert HWC->CHW and BGR->RGB (via [::-1]) then make contiguous and normalize
81
+ x = image.transpose((2, 0, 1))[::-1] # -> (C, H, W), BGR->RGB
82
+ x = np.ascontiguousarray(x)
83
+ x = x.astype(np.float32)
84
+ x = x[np.newaxis, ...] # (1, C, H, W)
85
+ x = x / 255.0
86
+ return x, (shape[0], shape[1]), (height, width), (h, w)
87
+
88
+ def wh2xy(self, x):
89
+ y = x.clone() if isinstance(x, torch.Tensor) else numpy.copy(x)
90
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
91
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
92
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
93
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
94
+ return y
95
+
96
+ def non_max_suppression(self, outputs, conf_threshold, iou_threshold):
97
+ max_wh = 7680
98
+ max_det = 300
99
+ max_nms = 30000
100
+
101
+ bs = outputs.shape[0] # batch size
102
+ nc = outputs.shape[1] - 4 # number of classes
103
+ xc = outputs[:, 4:4 + nc].amax(1) > conf_threshold # candidates
104
+
105
+ start = time()
106
+ limit = 0.5 + 0.05 * bs # seconds to quit after
107
+
108
+ output = [torch.zeros((0, 6), device=outputs.device)] * bs
109
+ for index, x in enumerate(outputs): # image index, image inference
110
+ x = x.transpose(0, -1)[xc[index]] # confidence
111
+
112
+ # If none remain process next image
113
+ if not x.shape[0]:
114
+ continue
115
+
116
+ box, cls = x.split((4, nc), 1)
117
+ box = self.wh2xy(box) # (cx, cy, w, h) to (x1, y1, x2, y2)
118
+ if nc > 1:
119
+ i, j = (cls > conf_threshold).nonzero(as_tuple=False).T
120
+ x = torch.cat((box[i], x[i, 4 + j, None], j[:, None].float()), 1)
121
+ else: # best class only
122
+ conf, j = cls.max(1, keepdim=True)
123
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_threshold]
124
+
125
+ if not x.shape[0]: # no boxes
126
+ continue
127
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence and remove excess boxes
128
+
129
+ # Batched NMS
130
+ c = x[:, 5:6] * max_wh # classes
131
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
132
+ i = nms(boxes, scores, iou_threshold) # NMS
133
+ i = i[:max_det] # limit detections
134
+
135
+ output[index] = x[i]
136
+ if (time() - start) > limit:
137
+ break # time limit exceeded
138
+
139
+ return output
140
+
141
+ def _postprocess(self, outputs, orig_w, orig_h, resized_w, resized_h, proc_h, proc_w):
142
+ outputs = torch.from_numpy(np.asarray(outputs)).float()
143
+ nms_results = self.non_max_suppression(outputs, self.conf_threshold, self.iou_threshold)
144
+ detections = []
145
+ scale_back_div = min(resized_h / orig_h, resized_w / orig_w) # same as your code
146
+ # iterate outputs (list of tensors)
147
+
148
+ for output in nms_results:
149
+ if output is None or output.numel() == 0:
150
+ continue
151
+ # ensure CPU float tensor
152
+ output = output.cpu().float()
153
+
154
+ # replicate original adjustments:
155
+ # subtract padding (x padding uses w, y uses h)
156
+ output[:, [0, 2]] -= proc_w # x padding
157
+ output[:, [1, 3]] -= proc_h # y padding
158
+
159
+ # scale back to original image coords
160
+ output[:, :4] /= float(scale_back_div)
161
+
162
+ # clamp to original image size
163
+ output[:, 0].clamp_(0, orig_w) # x1 (width)
164
+ output[:, 1].clamp_(0, orig_h) # y1 (height)
165
+ output[:, 2].clamp_(0, orig_w) # x2
166
+ output[:, 3].clamp_(0, orig_h) # y2
167
+
168
+ for box in output:
169
+ box_np = box.cpu().numpy()
170
+ x1, y1, x2, y2, score, index = box_np[:6] # matches your unpack
171
+ detections.append((float(x1), float(y1), float(x2), float(y2), float(score), int(index)))
172
+
173
+ return detections
174
+
175
+ def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
176
+ x, (orig_h, orig_w), (resized_h, resized_w), (proc_h, proc_w) = self._preprocess(image_bgr)
177
+
178
+ outputs = self.sess.run(None, {self.input_name: x})[0]
179
+ outputs = self._postprocess(outputs, orig_w, orig_h, resized_w, resized_h, proc_h, proc_w)
180
+
181
+ out_boxes: list[BoundingBox] = []
182
+ for x1, y1, x2, y2, conf, cls_id in outputs:
183
+ ix1 = max(0, min(orig_w, math.floor(x1)))
184
+ iy1 = max(0, min(orig_h, math.floor(y1)))
185
+ ix2 = max(0, min(orig_w, math.ceil(x2)))
186
+ iy2 = max(0, min(orig_h, math.ceil(y2)))
187
+ out_boxes.append(
188
+ BoundingBox(
189
+ x1=ix1,
190
+ y1=iy1,
191
+ x2=ix2,
192
+ y2=iy2,
193
+ cls_id=cls_id,
194
+ conf=max(0.0, min(1.0, conf)),
195
+ )
196
+ )
197
+
198
+ return out_boxes
199
+
200
+ def predict_batch(
201
+ self,
202
+ batch_images: list[ndarray],
203
+ offset: int,
204
+ n_keypoints: int,
205
+ ) -> list[TVFrameResult]:
206
+ results: list[TVFrameResult] = []
207
+ for idx, image in enumerate(batch_images):
208
+ boxes = self._infer_single(image)
209
+ keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
210
+ results.append(
211
+ TVFrameResult(
212
+ frame_id=offset + idx,
213
+ boxes=boxes,
214
+ keypoints=keypoints,
215
+ )
216
+ )
217
+ return results
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b30ba010ad019c0b820287b4e6c7dc970e4515eb84f2fb152c8400fba5b3a67a
3
+ size 19017604