meaculpitt commited on
Commit
54f0e3e
·
verified ·
1 Parent(s): 6e9c779

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +105 -107
miner.py CHANGED
@@ -1,13 +1,3 @@
1
- """
2
- Score Vision SN44 — VehicleDetect miner. v2 (2026-03-25).
3
-
4
- Model: YOLO11n ONNX, 4 classes trained as:
5
- 0 = car, 1 = bus, 2 = truck, 3 = motorcycle
6
-
7
- Official submission order (remapped in MODEL_TO_OUT):
8
- 0 = bus, 1 = car, 2 = truck, 3 = motorcycle
9
- """
10
-
11
  from pathlib import Path
12
  import math
13
 
@@ -18,17 +8,6 @@ from numpy import ndarray
18
  from pydantic import BaseModel
19
 
20
 
21
- # ── Model class index → submission class index ───────────────────────────────
22
- # Trained order: car=0, bus=1, truck=2, motorcycle=3
23
- # Official order: bus=0, car=1, truck=2, motorcycle=3
24
- MODEL_TO_OUT: dict[int, int] = {0: 1, 1: 0, 2: 2, 3: 3}
25
- OUT_NAMES = ["bus", "car", "truck", "motorcycle"]
26
-
27
- IMG_SIZE = 640
28
- CONF_THRESH = 0.55 # sweep-optimised: max composite (0.60×mAP + 0.40×FP_score)
29
- IOU_THRESH = 0.45
30
-
31
-
32
  class BoundingBox(BaseModel):
33
  x1: int
34
  y1: int
@@ -46,117 +25,134 @@ class TVFrameResult(BaseModel):
46
 
47
  class Miner:
48
  """
49
- VehicleDetect miner for SN44. Loaded by turbovision template at startup.
 
50
  """
51
 
52
  def __init__(self, path_hf_repo: Path) -> None:
53
  self.path_hf_repo = path_hf_repo
 
54
  self.session = ort.InferenceSession(
55
  str(path_hf_repo / "weights.onnx"),
56
  providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
57
  )
58
  self.input_name = self.session.get_inputs()[0].name
59
- self.conf_threshold = CONF_THRESH
60
- self.iou_threshold = IOU_THRESH
 
 
 
 
61
 
62
  def __repr__(self) -> str:
63
- return f"VehicleDetect Miner session={type(self.session).__name__}"
64
-
65
- def _letterbox(self, img: ndarray) -> tuple[np.ndarray, float, int, int]:
66
- h, w = img.shape[:2]
67
- r = min(IMG_SIZE / h, IMG_SIZE / w)
68
- new_w, new_h = int(round(w * r)), int(round(h * r))
69
- img_r = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
70
- dw, dh = IMG_SIZE - new_w, IMG_SIZE - new_h
71
- pad_l, pad_t = dw // 2, dh // 2
72
- img_p = cv2.copyMakeBorder(
73
- img_r, pad_t, dh - pad_t, pad_l, dw - pad_l,
74
- cv2.BORDER_CONSTANT, value=(114, 114, 114),
75
- )
76
- return img_p, r, pad_l, pad_t
77
-
78
- def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, float, int, int]:
79
- img_p, ratio, pad_l, pad_t = self._letterbox(image_bgr)
80
- img_rgb = cv2.cvtColor(img_p, cv2.COLOR_BGR2RGB)
81
- inp = img_rgb.astype(np.float32) / 255.0
82
- inp = np.ascontiguousarray(inp.transpose(2, 0, 1)[np.newaxis])
83
- return inp, ratio, pad_l, pad_t
84
 
85
- def _nms(self, boxes: np.ndarray, scores: np.ndarray) -> list[int]:
86
- if not len(boxes):
87
  return []
88
- x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
89
- areas = (x2 - x1) * (y2 - y1)
 
90
  order = scores.argsort()[::-1]
91
- keep: list[int] = []
92
- while len(order):
 
93
  i = order[0]
94
- keep.append(int(i))
95
- xx1 = np.maximum(x1[i], x1[order[1:]])
96
- yy1 = np.maximum(y1[i], y1[order[1:]])
97
- xx2 = np.minimum(x2[i], x2[order[1:]])
98
- yy2 = np.minimum(y2[i], y2[order[1:]])
99
- inter = np.maximum(0, xx2 - xx1) * np.maximum(0, yy2 - yy1)
100
- iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-7)
101
- order = order[1:][iou <= self.iou_threshold]
102
- return keep
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
105
- orig_h, orig_w = image_bgr.shape[:2]
106
- inp, ratio, pad_l, pad_t = self._preprocess(image_bgr)
107
- raw = self.session.run(None, {self.input_name: inp})[0]
108
 
109
- # Output: [1, 8, 8400] pred: [8, 8400] → [8400, 8]
110
- pred = raw[0]
111
- if pred.shape[0] < pred.shape[1]:
112
- pred = pred.T # [8400, 8]
113
 
114
- bboxes_cx = pred[:, :4] # cx, cy, w, h in letterboxed coords
115
- cls_scores = pred[:, 4:] # [8400, 4]
 
 
 
116
 
117
  cls_ids = np.argmax(cls_scores, axis=1)
118
  confs = np.max(cls_scores, axis=1)
119
- mask = confs >= self.conf_threshold
 
 
 
 
120
 
121
- if not mask.any():
122
  return []
123
 
124
- bboxes_cx = bboxes_cx[mask]
125
- confs = confs[mask]
126
- cls_ids = cls_ids[mask]
127
 
128
- # cx,cy,w,h x1,y1,x2,y2 (in letterboxed image coords)
129
- cx, cy, bw, bh = bboxes_cx[:, 0], bboxes_cx[:, 1], bboxes_cx[:, 2], bboxes_cx[:, 3]
130
- lx1 = cx - bw / 2
131
- ly1 = cy - bh / 2
132
- lx2 = cx + bw / 2
133
- ly2 = cy + bh / 2
 
 
134
 
135
- # Unletterbox back to original image coords
136
- x1 = np.clip((lx1 - pad_l) / ratio, 0, orig_w)
137
- y1 = np.clip((ly1 - pad_t) / ratio, 0, orig_h)
138
- x2 = np.clip((lx2 - pad_l) / ratio, 0, orig_w)
139
- y2 = np.clip((ly2 - pad_t) / ratio, 0, orig_h)
140
- boxes = np.stack([x1, y1, x2, y2], axis=1)
141
 
142
  out_boxes: list[BoundingBox] = []
143
- for model_cls in range(4):
144
- cls_mask = cls_ids == model_cls
145
- if not cls_mask.any():
146
- continue
147
- keep = self._nms(boxes[cls_mask], confs[cls_mask])
148
- sub_cls = MODEL_TO_OUT[model_cls]
149
- for k in keep:
150
- box = boxes[cls_mask][k]
151
- conf = float(confs[cls_mask][k])
152
- out_boxes.append(BoundingBox(
153
- x1=max(0, min(orig_w, math.floor(box[0]))),
154
- y1=max(0, min(orig_h, math.floor(box[1]))),
155
- x2=max(0, min(orig_w, math.ceil(box[2]))),
156
- y2=max(0, min(orig_h, math.ceil(box[3]))),
157
- cls_id=sub_cls,
158
  conf=max(0.0, min(1.0, conf)),
159
- ))
 
160
  return out_boxes
161
 
162
  def predict_batch(
@@ -169,9 +165,11 @@ class Miner:
169
  for idx, image in enumerate(batch_images):
170
  boxes = self._infer_single(image)
171
  keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
172
- results.append(TVFrameResult(
173
- frame_id=offset + idx,
174
- boxes=boxes,
175
- keypoints=keypoints,
176
- ))
 
 
177
  return results
 
 
 
 
 
 
 
 
 
 
 
1
  from pathlib import Path
2
  import math
3
 
 
8
  from pydantic import BaseModel
9
 
10
 
 
 
 
 
 
 
 
 
 
 
 
11
  class BoundingBox(BaseModel):
12
  x1: int
13
  y1: int
 
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 = ['person']
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.50 # sweep-optimised: composite 0.5379 at 0.50 vs 0.5045 at 0.70
45
+ self.iou_threshold = 0.45
46
 
47
  def __repr__(self) -> str:
48
+ return f"ONNX Miner session={type(self.session).__name__} classes={len(self.class_names)}"
49
+
50
+ def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, tuple[int, int]]:
51
+ h, w = image_bgr.shape[:2]
52
+ rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
53
+ resized = cv2.resize(rgb, (self.input_w, self.input_h))
54
+ x = resized.astype(np.float32) / 255.0
55
+ x = np.transpose(x, (2, 0, 1))[None, ...]
56
+ return x, (h, w)
57
+
58
+ def _normalize_predictions(self, raw: np.ndarray) -> np.ndarray:
59
+ # Common ultralytics export shapes:
60
+ # - [1, C, N] where C=4+num_classes
61
+ # - [1, N, C]
62
+ pred = raw[0]
63
+ if pred.ndim != 2:
64
+ raise ValueError(f"Unexpected prediction shape: {raw.shape}")
65
+ if pred.shape[0] < pred.shape[1]:
66
+ pred = pred.transpose(1, 0)
67
+ return pred
 
68
 
69
+ def _nms(self, dets: list[tuple[float, float, float, float, float, int]]) -> list[tuple[float, float, float, float, float, int]]:
70
+ if not dets:
71
  return []
72
+
73
+ boxes = np.array([[d[0], d[1], d[2], d[3]] for d in dets], dtype=np.float32)
74
+ scores = np.array([d[4] for d in dets], dtype=np.float32)
75
  order = scores.argsort()[::-1]
76
+ keep = []
77
+
78
+ while order.size > 0:
79
  i = order[0]
80
+ keep.append(i)
81
+
82
+ xx1 = np.maximum(boxes[i, 0], boxes[order[1:], 0])
83
+ yy1 = np.maximum(boxes[i, 1], boxes[order[1:], 1])
84
+ xx2 = np.minimum(boxes[i, 2], boxes[order[1:], 2])
85
+ yy2 = np.minimum(boxes[i, 3], boxes[order[1:], 3])
86
+
87
+ w = np.maximum(0.0, xx2 - xx1)
88
+ h = np.maximum(0.0, yy2 - yy1)
89
+ inter = w * h
90
+
91
+ area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
92
+ area_rest = (boxes[order[1:], 2] - boxes[order[1:], 0]) * (boxes[order[1:], 3] - boxes[order[1:], 1])
93
+ union = np.maximum(area_i + area_rest - inter, 1e-6)
94
+ iou = inter / union
95
+
96
+ remaining = np.where(iou <= self.iou_threshold)[0]
97
+ order = order[remaining + 1]
98
+
99
+ return [dets[idx] for idx in keep]
100
 
101
  def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
102
+ inp, (orig_h, orig_w) = self._preprocess(image_bgr)
103
+ out = self.session.run(None, {self.input_name: inp})[0]
104
+ pred = self._normalize_predictions(out)
105
 
106
+ if pred.shape[1] < 5:
107
+ return []
 
 
108
 
109
+ boxes = pred[:, :4]
110
+ cls_scores = pred[:, 4:]
111
+
112
+ if cls_scores.shape[1] == 0:
113
+ return []
114
 
115
  cls_ids = np.argmax(cls_scores, axis=1)
116
  confs = np.max(cls_scores, axis=1)
117
+ keep = confs >= self.conf_threshold
118
+
119
+ boxes = boxes[keep]
120
+ confs = confs[keep]
121
+ cls_ids = cls_ids[keep]
122
 
123
+ if boxes.shape[0] == 0:
124
  return []
125
 
126
+ sx = orig_w / float(self.input_w)
127
+ sy = orig_h / float(self.input_h)
 
128
 
129
+ dets: list[tuple[float, float, float, float, float, int]] = []
130
+ for i in range(boxes.shape[0]):
131
+ cx, cy, bw, bh = boxes[i].tolist()
132
+ x1 = (cx - bw / 2.0) * sx
133
+ y1 = (cy - bh / 2.0) * sy
134
+ x2 = (cx + bw / 2.0) * sx
135
+ y2 = (cy + bh / 2.0) * sy
136
+ dets.append((x1, y1, x2, y2, float(confs[i]), int(cls_ids[i])))
137
 
138
+ dets = self._nms(dets)
 
 
 
 
 
139
 
140
  out_boxes: list[BoundingBox] = []
141
+ for x1, y1, x2, y2, conf, cls_id in dets:
142
+ ix1 = max(0, min(orig_w, math.floor(x1)))
143
+ iy1 = max(0, min(orig_h, math.floor(y1)))
144
+ ix2 = max(0, min(orig_w, math.ceil(x2)))
145
+ iy2 = max(0, min(orig_h, math.ceil(y2)))
146
+ out_boxes.append(
147
+ BoundingBox(
148
+ x1=ix1,
149
+ y1=iy1,
150
+ x2=ix2,
151
+ y2=iy2,
152
+ cls_id=cls_id,
 
 
 
153
  conf=max(0.0, min(1.0, conf)),
154
+ )
155
+ )
156
  return out_boxes
157
 
158
  def predict_batch(
 
165
  for idx, image in enumerate(batch_images):
166
  boxes = self._infer_single(image)
167
  keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
168
+ results.append(
169
+ TVFrameResult(
170
+ frame_id=offset + idx,
171
+ boxes=boxes,
172
+ keypoints=keypoints,
173
+ )
174
+ )
175
  return results