iotaminer commited on
Commit
f08491d
·
verified ·
1 Parent(s): fe6b61b

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +185 -0
miner.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TurboVision miner for Detect-petrol-station-1-0.
2
+
3
+ YOLOv11s ONNX FP16 + NMS baked in, with horizontal-flip TTA to boost recall.
4
+ 4 classes: 0=petrol hose, 1=petrol pump, 2=price board, 3=roof canopy.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import List, Tuple
10
+
11
+ import cv2
12
+ import numpy as np
13
+ import onnxruntime as ort
14
+ from pydantic import BaseModel
15
+
16
+
17
+ class BoundingBox(BaseModel):
18
+ x1: int
19
+ y1: int
20
+ x2: int
21
+ y2: int
22
+ cls_id: int
23
+ conf: float
24
+
25
+
26
+ class TVFrameResult(BaseModel):
27
+ frame_id: int
28
+ boxes: list[BoundingBox]
29
+ keypoints: list[tuple[int, int]]
30
+
31
+
32
+ class Miner:
33
+ IMGSZ = 1280
34
+ # Per-class conf thresholds: 0=petrol hose, 1=petrol pump, 2=price board, 3=roof canopy.
35
+ # Tuned via greedy grid search on 100 fresh challenges vs real SAM3 pseudo-GT.
36
+ CLASS_CONF_THRES = (0.43, 0.63, 0.37, 0.41)
37
+ CONF_THRES = 0.37 # fallback / pre-filter at lowest per-class threshold
38
+ IOU_THRES = 0.45
39
+ NUM_CLASSES = 4
40
+ MIN_BOX_FRAC = 0.005
41
+ USE_TTA = True
42
+
43
+ def __init__(self, path_hf_repo: Path) -> None:
44
+ self.onnx_path = path_hf_repo / 'weights.onnx'
45
+ if not self.onnx_path.exists():
46
+ raise FileNotFoundError(f'Model not found at {self.onnx_path}')
47
+
48
+ providers: list = []
49
+ try:
50
+ ort.preload_dlls()
51
+ except Exception:
52
+ pass
53
+ available = ort.get_available_providers()
54
+ if 'CUDAExecutionProvider' in available:
55
+ providers.append(('CUDAExecutionProvider', {'device_id': 0}))
56
+ providers.append('CPUExecutionProvider')
57
+ so = ort.SessionOptions()
58
+ so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
59
+ self.session = ort.InferenceSession(str(self.onnx_path), sess_options=so, providers=providers)
60
+ self.input_name = self.session.get_inputs()[0].name
61
+ inp = self.session.get_inputs()[0]
62
+ self.input_shape = inp.shape
63
+ self.input_dtype = np.float16 if inp.type == 'tensor(float16)' else np.float32
64
+ print(f'[Miner] Loaded {self.onnx_path.name} | providers={self.session.get_providers()} | dtype={self.input_dtype}')
65
+
66
+ def __repr__(self) -> str:
67
+ return f'PetrolMiner(yolo11s-onnx-fp16-nms, tta={self.USE_TTA}, conf={self.CONF_THRES})'
68
+
69
+ @staticmethod
70
+ def _letterbox(img, new_size=1280, color=(114, 114, 114)):
71
+ h, w = img.shape[:2]
72
+ r = min(new_size / h, new_size / w)
73
+ nh, nw = int(round(h * r)), int(round(w * r))
74
+ resized = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)
75
+ top = (new_size - nh) // 2
76
+ bottom = new_size - nh - top
77
+ left = (new_size - nw) // 2
78
+ right = new_size - nw - left
79
+ padded = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
80
+ return padded, r, (left, top)
81
+
82
+ def _preprocess(self, img):
83
+ h, w = img.shape[:2]
84
+ img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
85
+ padded, r, (lx, ty) = self._letterbox(img_rgb, self.IMGSZ)
86
+ x = padded.astype(self.input_dtype) / 255.0
87
+ x = x.transpose(2, 0, 1)[None, ...]
88
+ return np.ascontiguousarray(x), r, (lx, ty), (w, h)
89
+
90
+ def _run_onnx(self, img):
91
+ x, r, (lx, ty), (W, H) = self._preprocess(img)
92
+ outputs = self.session.run(None, {self.input_name: x})
93
+ det = outputs[0]
94
+ if det.ndim == 3: det = det[0]
95
+ if det.size == 0: return [], [], [], W, H
96
+ det = np.asarray(det, dtype=np.float32)
97
+ if det.shape[-1] < 6: return [], [], [], W, H
98
+ xyxy = det[:, :4].copy()
99
+ conf = det[:, 4].copy()
100
+ cls_id = det[:, 5].astype(int)
101
+ keep = conf >= self.CONF_THRES
102
+ xyxy, conf, cls_id = xyxy[keep], conf[keep], cls_id[keep]
103
+ if len(xyxy) == 0: return [], [], [], W, H
104
+ xyxy[:, [0, 2]] = (xyxy[:, [0, 2]] - lx) / r
105
+ xyxy[:, [1, 3]] = (xyxy[:, [1, 3]] - ty) / r
106
+ xyxy[:, 0::2] = np.clip(xyxy[:, 0::2], 0, W - 1)
107
+ xyxy[:, 1::2] = np.clip(xyxy[:, 1::2], 0, H - 1)
108
+ min_side = self.MIN_BOX_FRAC * min(W, H)
109
+ mask = (
110
+ (cls_id >= 0) & (cls_id < self.NUM_CLASSES)
111
+ & ((xyxy[:, 2] - xyxy[:, 0]) >= min_side)
112
+ & ((xyxy[:, 3] - xyxy[:, 1]) >= min_side)
113
+ )
114
+ return xyxy[mask], conf[mask], cls_id[mask], W, H
115
+
116
+ @staticmethod
117
+ def _hard_nms_per_class(xyxy, conf, cls_id, iou_thres=0.5):
118
+ if len(xyxy) == 0: return np.empty((0,), dtype=int)
119
+ keep = []
120
+ for c in np.unique(cls_id):
121
+ idx = np.where(cls_id == c)[0]
122
+ b = xyxy[idx]; s = conf[idx]
123
+ order = np.argsort(-s)
124
+ b = b[order]; s = s[order]; idx = idx[order]
125
+ areas = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
126
+ suppressed = np.zeros(len(b), dtype=bool)
127
+ for i in range(len(b)):
128
+ if suppressed[i]: continue
129
+ keep.append(idx[i])
130
+ xx1 = np.maximum(b[i, 0], b[i+1:, 0])
131
+ yy1 = np.maximum(b[i, 1], b[i+1:, 1])
132
+ xx2 = np.minimum(b[i, 2], b[i+1:, 2])
133
+ yy2 = np.minimum(b[i, 3], b[i+1:, 3])
134
+ inter = np.maximum(0, xx2 - xx1) * np.maximum(0, yy2 - yy1)
135
+ iou = inter / (areas[i] + areas[i+1:] - inter + 1e-9)
136
+ suppressed[i+1:][iou > iou_thres] = True
137
+ return np.array(keep, dtype=int)
138
+
139
+ def _predict_single(self, img):
140
+ xyxy1, conf1, cls1, W, H = self._run_onnx(img)
141
+ if not self.USE_TTA:
142
+ xyxy, conf, cls_id = xyxy1, conf1, cls1
143
+ else:
144
+ img_f = cv2.flip(img, 1)
145
+ xyxy2, conf2, cls2, _, _ = self._run_onnx(img_f)
146
+ if len(xyxy2) > 0:
147
+ tmp = xyxy2.copy()
148
+ tmp[:, 0] = W - xyxy2[:, 2]
149
+ tmp[:, 2] = W - xyxy2[:, 0]
150
+ xyxy2 = tmp
151
+ pieces_xyxy = [a for a in (xyxy1, xyxy2) if len(a) > 0]
152
+ pieces_conf = [a for a in (conf1, conf2) if len(a) > 0]
153
+ pieces_cls = [a for a in (cls1, cls2) if len(a) > 0]
154
+ xyxy = np.vstack(pieces_xyxy) if pieces_xyxy else np.empty((0, 4))
155
+ conf = np.concatenate(pieces_conf) if pieces_conf else np.empty((0,))
156
+ cls_id = np.concatenate(pieces_cls) if pieces_cls else np.empty((0,))
157
+ if len(xyxy) > 0:
158
+ keep = self._hard_nms_per_class(xyxy, conf, cls_id, iou_thres=self.IOU_THRES)
159
+ xyxy, conf, cls_id = xyxy[keep], conf[keep], cls_id[keep]
160
+ boxes = []
161
+ for i in range(len(xyxy)):
162
+ ci = int(cls_id[i])
163
+ if 0 <= ci < self.NUM_CLASSES and float(conf[i]) < self.CLASS_CONF_THRES[ci]:
164
+ continue
165
+ boxes.append(BoundingBox(
166
+ x1=int(round(float(xyxy[i, 0]))),
167
+ y1=int(round(float(xyxy[i, 1]))),
168
+ x2=int(round(float(xyxy[i, 2]))),
169
+ y2=int(round(float(xyxy[i, 3]))),
170
+ cls_id=ci,
171
+ conf=float(conf[i]),
172
+ ))
173
+ return boxes
174
+
175
+ def predict_batch(self, batch_images, offset, n_keypoints):
176
+ results = []
177
+ for i, img in enumerate(batch_images):
178
+ try:
179
+ boxes = self._predict_single(img)
180
+ except Exception as e:
181
+ print(f'[Miner] predict error on frame {offset + i}: {e}')
182
+ boxes = []
183
+ kps = [(0, 0) for _ in range(n_keypoints)]
184
+ results.append(TVFrameResult(frame_id=offset + i, boxes=boxes, keypoints=kps))
185
+ return results