coolroman commited on
Commit
f94cdc7
·
verified ·
1 Parent(s): 6ae1e6e

Upload miner.py

Browse files
Files changed (1) hide show
  1. miner.py +190 -0
miner.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
28
+ Auto-generated by subnet_bridge from a Manako element repo.
29
+ This miner is intentionally self-contained for chute import restrictions.
30
+ """
31
+
32
+ def __init__(self, path_hf_repo: Path) -> None:
33
+ self.path_hf_repo = path_hf_repo
34
+ self.class_names = ['numberplate']
35
+ self.session = ort.InferenceSession(
36
+ str(path_hf_repo / "weights.onnx"),
37
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
38
+ )
39
+ self.input_name = self.session.get_inputs()[0].name
40
+ input_shape = self.session.get_inputs()[0].shape
41
+ # expected [N, C, H, W]
42
+ self.input_h = int(input_shape[2])
43
+ self.input_w = int(input_shape[3])
44
+ self.conf_threshold = 0.15
45
+ self.iou_threshold = 0.3
46
+ self.use_tta = True
47
+
48
+ def __repr__(self) -> str:
49
+ return f"ONNX Miner session={type(self.session).__name__} classes={len(self.class_names)}"
50
+
51
+ def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, tuple[int, int]]:
52
+ h, w = image_bgr.shape[:2]
53
+ rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
54
+ resized = cv2.resize(rgb, (self.input_w, self.input_h))
55
+ x = resized.astype(np.float32) / 255.0
56
+ x = np.transpose(x, (2, 0, 1))[None, ...]
57
+ return x, (h, w)
58
+
59
+ def _normalize_predictions(self, raw: np.ndarray) -> np.ndarray:
60
+ pred = raw[0]
61
+ if pred.ndim != 2:
62
+ raise ValueError(f"Unexpected prediction shape: {raw.shape}")
63
+ if pred.shape[0] < pred.shape[1]:
64
+ pred = pred.transpose(1, 0)
65
+ return pred
66
+
67
+ def _nms(self, dets: list[tuple[float, float, float, float, float, int]]) -> list[tuple[float, float, float, float, float, int]]:
68
+ if not dets:
69
+ return []
70
+
71
+ boxes = np.array([[d[0], d[1], d[2], d[3]] for d in dets], dtype=np.float32)
72
+ scores = np.array([d[4] for d in dets], dtype=np.float32)
73
+ order = scores.argsort()[::-1]
74
+ keep = []
75
+
76
+ while order.size > 0:
77
+ i = order[0]
78
+ keep.append(i)
79
+
80
+ xx1 = np.maximum(boxes[i, 0], boxes[order[1:], 0])
81
+ yy1 = np.maximum(boxes[i, 1], boxes[order[1:], 1])
82
+ xx2 = np.minimum(boxes[i, 2], boxes[order[1:], 2])
83
+ yy2 = np.minimum(boxes[i, 3], boxes[order[1:], 3])
84
+
85
+ w = np.maximum(0.0, xx2 - xx1)
86
+ h = np.maximum(0.0, yy2 - yy1)
87
+ inter = w * h
88
+
89
+ area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
90
+ area_rest = (boxes[order[1:], 2] - boxes[order[1:], 0]) * (boxes[order[1:], 3] - boxes[order[1:], 1])
91
+ union = np.maximum(area_i + area_rest - inter, 1e-6)
92
+ iou = inter / union
93
+
94
+ remaining = np.where(iou <= self.iou_threshold)[0]
95
+ order = order[remaining + 1]
96
+
97
+ return [dets[idx] for idx in keep]
98
+
99
+ def _decode(self, image_bgr: ndarray) -> list[tuple[float, float, float, float, float, int]]:
100
+ """Run model and return raw detections before NMS."""
101
+ inp, (orig_h, orig_w) = self._preprocess(image_bgr)
102
+ out = self.session.run(None, {self.input_name: inp})[0]
103
+ pred = self._normalize_predictions(out)
104
+
105
+ if pred.shape[1] < 5:
106
+ return []
107
+
108
+ boxes = pred[:, :4]
109
+ cls_scores = pred[:, 4:]
110
+
111
+ if cls_scores.shape[1] == 0:
112
+ return []
113
+
114
+ cls_ids = np.argmax(cls_scores, axis=1)
115
+ confs = np.max(cls_scores, axis=1)
116
+ keep = confs >= self.conf_threshold
117
+
118
+ boxes = boxes[keep]
119
+ confs = confs[keep]
120
+ cls_ids = cls_ids[keep]
121
+
122
+ if boxes.shape[0] == 0:
123
+ return []
124
+
125
+ sx = orig_w / float(self.input_w)
126
+ sy = orig_h / float(self.input_h)
127
+
128
+ dets: list[tuple[float, float, float, float, float, int]] = []
129
+ for i in range(boxes.shape[0]):
130
+ cx, cy, bw, bh = boxes[i].tolist()
131
+ x1 = (cx - bw / 2.0) * sx
132
+ y1 = (cy - bh / 2.0) * sy
133
+ x2 = (cx + bw / 2.0) * sx
134
+ y2 = (cy + bh / 2.0) * sy
135
+ dets.append((x1, y1, x2, y2, float(confs[i]), int(cls_ids[i])))
136
+
137
+ return dets
138
+
139
+ def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
140
+ orig_h, orig_w = image_bgr.shape[:2]
141
+
142
+ # Original pass
143
+ all_dets = self._decode(image_bgr)
144
+
145
+ # TTA: horizontal flip pass
146
+ if self.use_tta:
147
+ flipped = cv2.flip(image_bgr, 1)
148
+ flip_dets = self._decode(flipped)
149
+ for x1, y1, x2, y2, conf, cls_id in flip_dets:
150
+ all_dets.append((orig_w - x2, y1, orig_w - x1, y2, conf, cls_id))
151
+
152
+ # NMS
153
+ all_dets = self._nms(all_dets)
154
+
155
+ out_boxes: list[BoundingBox] = []
156
+ for x1, y1, x2, y2, conf, cls_id in all_dets:
157
+ ix1 = max(0, min(orig_w, math.floor(x1)))
158
+ iy1 = max(0, min(orig_h, math.floor(y1)))
159
+ ix2 = max(0, min(orig_w, math.ceil(x2)))
160
+ iy2 = max(0, min(orig_h, math.ceil(y2)))
161
+ out_boxes.append(
162
+ BoundingBox(
163
+ x1=ix1,
164
+ y1=iy1,
165
+ x2=ix2,
166
+ y2=iy2,
167
+ cls_id=cls_id,
168
+ conf=max(0.0, min(1.0, conf)),
169
+ )
170
+ )
171
+ return out_boxes
172
+
173
+ def predict_batch(
174
+ self,
175
+ batch_images: list[ndarray],
176
+ offset: int,
177
+ n_keypoints: int,
178
+ ) -> list[TVFrameResult]:
179
+ results: list[TVFrameResult] = []
180
+ for idx, image in enumerate(batch_images):
181
+ boxes = self._infer_single(image)
182
+ keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
183
+ results.append(
184
+ TVFrameResult(
185
+ frame_id=offset + idx,
186
+ boxes=boxes,
187
+ keypoints=keypoints,
188
+ )
189
+ )
190
+ return results