codeskip commited on
Commit
fbe95cf
·
verified ·
1 Parent(s): 9bf5396

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +288 -0
miner.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
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
+ class BoundingBox(BaseModel):
11
+ x1: int
12
+ y1: int
13
+ x2: int
14
+ y2: int
15
+ cls_id: int
16
+ conf: float
17
+
18
+ class TVFrameResult(BaseModel):
19
+ frame_id: int
20
+ boxes: list[BoundingBox]
21
+ keypoints: list[tuple[int, int]]
22
+
23
+ class Miner:
24
+ cpu_threads = 2
25
+
26
+ input_size = 640
27
+ num_queries = 300
28
+ interp = cv2.INTER_AREA
29
+ conf_thres = 0.42
30
+ nms_iou = 0.5
31
+ max_det = 300
32
+ min_side = 8.0
33
+ min_box_area = 9.0
34
+ max_aspect_ratio = 12.0
35
+
36
+ rescue_bonus = 0.10
37
+
38
+ use_cuda_graph = False
39
+
40
+ def __init__(self, path_hf_repo: Path) -> None:
41
+ model_path = Path(path_hf_repo) / "weights.onnx"
42
+ if not model_path.is_file():
43
+ raise FileNotFoundError(f"Missing {model_path}.")
44
+
45
+ try:
46
+ ort.preload_dlls()
47
+ except Exception:
48
+ pass
49
+
50
+ n_threads = max(1, min(self.cpu_threads, os.cpu_count() or self.cpu_threads))
51
+
52
+ sess_options = ort.SessionOptions()
53
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
54
+ sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
55
+ sess_options.intra_op_num_threads = n_threads
56
+ sess_options.inter_op_num_threads = 1
57
+ sess_options.enable_mem_pattern = True
58
+ sess_options.enable_cpu_mem_arena = True
59
+
60
+ providers = self._provider_list_with_opts()
61
+ try:
62
+ self.session = ort.InferenceSession(
63
+ str(model_path),
64
+ sess_options=sess_options,
65
+ disabled_optimizers=["SimplifiedLayerNormFusion"],
66
+ providers=providers,
67
+ )
68
+ except Exception:
69
+ try:
70
+ self.session = ort.InferenceSession(
71
+ str(model_path), sess_options=sess_options, providers=providers
72
+ )
73
+ except Exception:
74
+ self.session = ort.InferenceSession(
75
+ str(model_path),
76
+ sess_options=sess_options,
77
+ providers=["CPUExecutionProvider"],
78
+ )
79
+
80
+ self.input_name = self.session.get_inputs()[0].name
81
+ self.size_name = self.session.get_inputs()[1].name
82
+ self.output_names = [output.name for output in self.session.get_outputs()]
83
+ self._boxes_name = self.output_names[1]
84
+ self._scores_name = self.output_names[2]
85
+
86
+ self._init_buffers()
87
+ self._on_cuda = self.session.get_providers()[0] == "CUDAExecutionProvider"
88
+ self._init_iobinding()
89
+ self._warmup()
90
+
91
+ active = self.session.get_providers()[0]
92
+ print(f"Model loaded from {model_path} provider={active} iobinding=ON")
93
+
94
+ def __repr__(self) -> str:
95
+ return (
96
+ f"road-sign Miner "
97
+ f"input={self.input_size} queries={self.num_queries}"
98
+ )
99
+
100
+ @staticmethod
101
+ def _providers() -> list[str]:
102
+ avail = ort.get_available_providers()
103
+ return [p for p in ("CUDAExecutionProvider", "CPUExecutionProvider") if p in avail]
104
+
105
+ def _provider_list_with_opts(self):
106
+ cuda_opts: dict[str, str] = {"cudnn_conv_algo_search": "HEURISTIC"}
107
+ if self.use_cuda_graph:
108
+ cuda_opts["enable_cuda_graph"] = "1"
109
+ out = []
110
+ for p in self._providers():
111
+ if p == "CUDAExecutionProvider":
112
+ out.append((p, cuda_opts))
113
+ else:
114
+ out.append(p)
115
+ return out
116
+
117
+ def _init_buffers(self) -> None:
118
+ size = self.input_size
119
+ q = self.num_queries
120
+
121
+ self._rgb = np.empty((size, size, 3), dtype=np.uint8)
122
+ self._input_tensor = np.zeros((1, 3, size, size), dtype=np.float32)
123
+ self._sizes = np.zeros((1, 2), dtype=np.int64)
124
+
125
+ self._out_labels = np.empty((1, q), dtype=np.int64)
126
+ self._out_boxes = np.empty((1, q, 4), dtype=np.float32)
127
+ self._out_scores = np.empty((1, q), dtype=np.float32)
128
+
129
+ def _init_iobinding(self) -> None:
130
+ self._io_binding = self.session.io_binding()
131
+ self._io_binding.bind_cpu_input(self.input_name, self._input_tensor)
132
+ self._io_binding.bind_cpu_input(self.size_name, self._sizes)
133
+ if self._on_cuda:
134
+ for name in self.output_names:
135
+ self._io_binding.bind_output(name, "cuda")
136
+ else:
137
+ for name, buf, dtype in (
138
+ (self.output_names[0], self._out_labels, np.int64),
139
+ (self._boxes_name, self._out_boxes, np.float32),
140
+ (self._scores_name, self._out_scores, np.float32),
141
+ ):
142
+ self._io_binding.bind_output(
143
+ name, "cpu", 0, dtype, buf.shape, buf.ctypes.data
144
+ )
145
+
146
+ def _warmup(self) -> None:
147
+ self._input_tensor.fill(0.0)
148
+ self._sizes[0, 0] = self.input_size
149
+ self._sizes[0, 1] = self.input_size
150
+ self.session.run(
151
+ self.output_names,
152
+ {self.input_name: self._input_tensor, self.size_name: self._sizes},
153
+ )
154
+
155
+ @staticmethod
156
+ def _nms(boxes: ndarray, scores: ndarray, iou_thres: float) -> list[int]:
157
+ if boxes.shape[0] == 0:
158
+ return []
159
+ x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
160
+ areas = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1)
161
+ order = scores.argsort()[::-1]
162
+ keep: list[int] = []
163
+ while order.size > 0:
164
+ i = order[0]
165
+ keep.append(int(i))
166
+ if order.size == 1:
167
+ break
168
+ rest = order[1:]
169
+ xx1 = np.maximum(x1[i], x1[rest])
170
+ yy1 = np.maximum(y1[i], y1[rest])
171
+ xx2 = np.minimum(x2[i], x2[rest])
172
+ yy2 = np.minimum(y2[i], y2[rest])
173
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
174
+ union = areas[i] + areas[rest] - inter
175
+ iou = np.where(union > 0, inter / union, 0.0)
176
+ order = rest[iou <= iou_thres]
177
+ return keep
178
+
179
+ def _preprocess(self, image: ndarray) -> tuple[int, int]:
180
+ size = self.input_size
181
+ oh, ow = image.shape[:2]
182
+ resized = cv2.resize(image, (size, size), interpolation=self.interp)
183
+ cv2.cvtColor(resized, cv2.COLOR_BGR2RGB, dst=self._rgb)
184
+ chw = self._rgb.transpose(2, 0, 1).astype(np.float32, copy=False) / 255.0
185
+ self._input_tensor[0] = chw
186
+ self._sizes[0, 0] = ow
187
+ self._sizes[0, 1] = oh
188
+ return ow, oh
189
+
190
+ def _run_inference(self) -> None:
191
+ if self._on_cuda:
192
+ self._io_binding.clear_binding_inputs()
193
+ self._io_binding.bind_cpu_input(self.input_name, self._input_tensor)
194
+ self._io_binding.bind_cpu_input(self.size_name, self._sizes)
195
+ self.session.run_with_iobinding(self._io_binding)
196
+ if self._on_cuda:
197
+ labels, boxes, scores = self._io_binding.copy_outputs_to_cpu()
198
+ np.copyto(self._out_labels, labels)
199
+ np.copyto(self._out_boxes, boxes)
200
+ np.copyto(self._out_scores, scores)
201
+
202
+ def _decode(self, boxes, scores, orig_w, orig_h):
203
+ primary = scores > self.conf_thres
204
+
205
+ if not primary.any() and len(scores) > 0:
206
+ best = int(np.argmax(scores))
207
+ if scores[best] >= self.conf_thres - self.rescue_bonus:
208
+ primary = np.zeros(len(scores), dtype=bool)
209
+ primary[best] = True
210
+
211
+ boxes = boxes[primary].astype(np.float32)
212
+ scores = scores[primary]
213
+ if boxes.shape[0] == 0:
214
+ return []
215
+
216
+ boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, orig_w - 1)
217
+ boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, orig_h - 1)
218
+
219
+ bw = np.maximum(0.0, boxes[:, 2] - boxes[:, 0])
220
+ bh = np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
221
+ area = bw * bh
222
+ ar = np.where(
223
+ (bw > 0) & (bh > 0),
224
+ np.maximum(bw / np.maximum(bh, 1e-6), bh / np.maximum(bw, 1e-6)),
225
+ np.inf,
226
+ )
227
+ sane = (
228
+ (bw >= self.min_side) & (bh >= self.min_side)
229
+ & (area >= self.min_box_area)
230
+ & (area <= 0.95 * float(orig_w * orig_h))
231
+ & (ar <= self.max_aspect_ratio)
232
+ )
233
+ boxes, scores = boxes[sane], scores[sane]
234
+ if boxes.shape[0] == 0:
235
+ return []
236
+
237
+ if boxes.shape[0] > 1:
238
+ kept = self._nms(boxes, scores, self.nms_iou)
239
+ boxes, scores = boxes[kept], scores[kept]
240
+
241
+ if scores.shape[0] > self.max_det:
242
+ top = np.argsort(-scores)[: self.max_det]
243
+ boxes, scores = boxes[top], scores[top]
244
+
245
+ out: list[BoundingBox] = []
246
+ for (x1, y1, x2, y2), conf in zip(boxes, scores):
247
+ if x2 <= x1 or y2 <= y1:
248
+ continue
249
+ out.append(
250
+ BoundingBox(
251
+ x1=int(x1), y1=int(y1), x2=int(x2), y2=int(y2),
252
+ cls_id=0, conf=float(conf),
253
+ )
254
+ )
255
+ return out
256
+
257
+ def _predict_single(self, image: ndarray) -> list[BoundingBox]:
258
+ orig_w, orig_h = self._preprocess(image)
259
+ self._run_inference()
260
+ return self._decode(
261
+ self._out_boxes[0],
262
+ self._out_scores[0],
263
+ orig_w,
264
+ orig_h,
265
+ )
266
+
267
+ def predict_batch(
268
+ self,
269
+ batch_images: list[ndarray],
270
+ offset: int,
271
+ n_keypoints: int,
272
+ ) -> list[TVFrameResult]:
273
+ results: list[TVFrameResult] = []
274
+ kp = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
275
+
276
+ for i, image in enumerate(batch_images):
277
+ frame_id = offset + i
278
+ try:
279
+ frame_boxes = self._predict_single(image)
280
+ except Exception:
281
+ frame_boxes = []
282
+
283
+ results.append(TVFrameResult(
284
+ frame_id=frame_id,
285
+ boxes=frame_boxes,
286
+ keypoints=list(kp),
287
+ ))
288
+ return results