File size: 9,497 Bytes
cc19355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""TurboVision public-track miner for manak0/Detect-petrol-station-1-0.

YOLO26n exported to ONNX (raw detection head), served with onnxruntime + numpy.
Lives at the root of the Hugging Face repo next to weights.onnx and chute_config.yml.
The validator audit forbids socket/subprocess/urllib/requests imports and
eval/exec/open calls in this file, so everything is self-contained.

Constants between the BUILD markers are rewritten by build_package.py.
"""

from pathlib import Path

import cv2
import numpy as np
import onnxruntime as ort
from pydantic import BaseModel

# ---- BUILD CONSTANTS ----
MODEL_FILE = "weights.onnx"
CLASS_NAMES = ["petrol pump", "petrol hose", "roof canopy", "price board"]
IMGSZ = 736
CONF = [0.4, 0.325, 0.5, 0.45]
NMS_IOU = [0.45, 0.55, 0.75, 0.55]
RESCUE_MARGIN = 0.04
CROSS_CLASS_IOU = 0.0
MIN_BOX_SIDE = 2
MAX_ASPECT = 60.0
MAX_DET = 300
# ---- END BUILD CONSTANTS ----

CANDIDATE_FLOOR = 0.01
PRE_NMS_TOPK = 1000
PAD_VALUE = 114
CPU_THREADS = 2


class BoundingBox(BaseModel):
    x1: int
    y1: int
    x2: int
    y2: int
    cls_id: int
    conf: float


class Polygon(BaseModel):
    cls_id: int
    conf: float
    points: list[tuple[int, int]]


class TVFrameResult(BaseModel):
    frame_id: int
    boxes: list[BoundingBox] | None = None
    polygons: list[Polygon] | None = None
    keypoints: list[tuple[int, int]] | None = None


def letterbox(image: np.ndarray, size: int) -> tuple[np.ndarray, float, float, float]:
    """Ultralytics-equivalent LetterBox(center=True, padding 114, INTER_LINEAR)."""
    h, w = image.shape[:2]
    ratio = min(size / h, size / w)
    new_w, new_h = int(round(w * ratio)), int(round(h * ratio))
    if (new_w, new_h) != (w, h):
        image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
    dw, dh = (size - new_w) / 2, (size - new_h) / 2
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    image = cv2.copyMakeBorder(
        image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(PAD_VALUE,) * 3
    )
    return image, ratio, float(left), float(top)


def decode(output: np.ndarray, n_classes: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Raw head (1, 4 + nc, anchors) or end-to-end (1, N, 6) -> xyxy, score, class (input pixels)."""
    arr = np.asarray(output, dtype=np.float32)
    arr = arr[0] if arr.ndim == 3 else arr
    if arr.shape[0] == 4 + n_classes:
        arr = arr.T
        cls = arr[:, 4:].argmax(axis=1)
        score = arr[np.arange(len(arr)), 4 + cls]
        cx, cy, bw, bh = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3]
        boxes = np.stack([cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2], axis=1)
    elif arr.ndim == 2 and arr.shape[1] == 6:
        boxes, score, cls = arr[:, :4], arr[:, 4], arr[:, 5].astype(np.int64)
    else:
        raise ValueError(f"unexpected model output shape {output.shape}")
    keep = score >= CANDIDATE_FLOOR
    boxes, score, cls = boxes[keep], score[keep], cls[keep].astype(np.int64)
    if len(score) > PRE_NMS_TOPK:
        top = np.argpartition(-score, PRE_NMS_TOPK)[:PRE_NMS_TOPK]
        boxes, score, cls = boxes[top], score[top], cls[top]
    return boxes, score, cls


def _iou_one_to_many(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:
    iw = np.clip(np.minimum(box[2], boxes[:, 2]) - np.maximum(box[0], boxes[:, 0]), 0, None)
    ih = np.clip(np.minimum(box[3], boxes[:, 3]) - np.maximum(box[1], boxes[:, 1]), 0, None)
    inter = iw * ih
    area = (box[2] - box[0]) * (box[3] - box[1])
    areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
    return inter / np.maximum(area + areas - inter, 1e-9)


def nms(boxes: np.ndarray, scores: np.ndarray, iou_threshold: float) -> np.ndarray:
    order = np.argsort(-scores, kind="stable")
    keep = []
    while order.size:
        i = order[0]
        keep.append(i)
        if order.size == 1:
            break
        order = order[1:][_iou_one_to_many(boxes[i], boxes[order[1:]]) <= iou_threshold]
    return np.asarray(keep, dtype=np.int64)


def postprocess(
    boxes: np.ndarray,
    scores: np.ndarray,
    classes: np.ndarray,
    orig_w: int,
    orig_h: int,
    conf: list[float] = CONF,
    nms_iou: list[float] = NMS_IOU,
    rescue_margin: float = RESCUE_MARGIN,
    cross_class_iou: float = CROSS_CLASS_IOU,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Candidates in original-image pixels -> final detections."""
    boxes = boxes.copy()
    boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, orig_w)
    boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, orig_h)
    bw, bh = boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]
    sane = (bw >= MIN_BOX_SIDE) & (bh >= MIN_BOX_SIDE)
    sane &= np.maximum(bw / np.maximum(bh, 1e-6), bh / np.maximum(bw, 1e-6)) <= MAX_ASPECT
    boxes, scores, classes = boxes[sane], scores[sane], classes[sane]

    kept_idx = []
    for c in range(len(CLASS_NAMES)):
        idx = np.where(classes == c)[0]
        if not idx.size:
            continue
        floor = conf[c] - rescue_margin
        idx = idx[scores[idx] >= floor]
        if not idx.size:
            continue
        idx = idx[nms(boxes[idx], scores[idx], nms_iou[c])]
        above = idx[scores[idx] >= conf[c]]
        if above.size:
            kept_idx.extend(above.tolist())
        elif rescue_margin > 0:
            kept_idx.append(int(idx[np.argmax(scores[idx])]))
    if not kept_idx:
        empty = np.zeros((0,), dtype=np.float32)
        return np.zeros((0, 4), dtype=np.float32), empty, np.zeros((0,), dtype=np.int64)
    keep = np.asarray(kept_idx, dtype=np.int64)
    boxes, scores, classes = boxes[keep], scores[keep], classes[keep]

    if cross_class_iou > 0 and len(scores) > 1:
        margin = scores - np.asarray(conf, dtype=np.float32)[classes]
        order = np.argsort(-margin, kind="stable")
        survivors = []
        for i in order:
            if survivors and (_iou_one_to_many(boxes[i], boxes[survivors]) > cross_class_iou).any():
                continue
            survivors.append(i)
        survivors = np.asarray(survivors, dtype=np.int64)
        boxes, scores, classes = boxes[survivors], scores[survivors], classes[survivors]

    order = np.argsort(-scores, kind="stable")[:MAX_DET]
    return boxes[order], scores[order], classes[order]


class Miner:
    def __init__(self, path_hf_repo: Path) -> None:
        model_path = Path(path_hf_repo) / MODEL_FILE
        options = ort.SessionOptions()
        options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
        available = ort.get_available_providers()
        providers = [p for p in ("CUDAExecutionProvider", "CPUExecutionProvider") if p in available]
        if providers[0] == "CPUExecutionProvider":
            options.intra_op_num_threads = CPU_THREADS
            options.inter_op_num_threads = 1
        try:
            self.session = ort.InferenceSession(str(model_path), options, providers=providers)
        except Exception as exc:
            print(f"⚠️ {providers[0]} session failed ({exc}); falling back to CPU")
            options.intra_op_num_threads = CPU_THREADS
            options.inter_op_num_threads = 1
            self.session = ort.InferenceSession(str(model_path), options, providers=["CPUExecutionProvider"])
        model_input = self.session.get_inputs()[0]
        self.input_name = model_input.name
        size = model_input.shape[-1]
        self.imgsz = size if isinstance(size, int) and size > 0 else IMGSZ
        self.predict_batch([np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8)], 0, 0)
        print(f"✅ ONNX model loaded ({self.session.get_providers()[0]}, imgsz={self.imgsz})")

    def __repr__(self) -> str:
        return f"YOLO26n ONNX {MODEL_FILE} imgsz={self.imgsz} provider={self.session.get_providers()[0]}"

    def candidates(self, image: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Pre-NMS candidates in original-image pixels for a BGR uint8 frame."""
        canvas, ratio, pad_x, pad_y = letterbox(image, self.imgsz)
        blob = np.ascontiguousarray(canvas[:, :, ::-1].transpose(2, 0, 1)[None], dtype=np.float32) / 255.0
        output = self.session.run(None, {self.input_name: blob})[0]
        boxes, scores, classes = decode(output, len(CLASS_NAMES))
        boxes[:, [0, 2]] = (boxes[:, [0, 2]] - pad_x) / ratio
        boxes[:, [1, 3]] = (boxes[:, [1, 3]] - pad_y) / ratio
        return boxes, scores, classes

    def detect(self, image: np.ndarray) -> list[BoundingBox]:
        h, w = image.shape[:2]
        boxes, scores, classes = postprocess(*self.candidates(image), orig_w=w, orig_h=h)
        return [
            BoundingBox(
                x1=int(round(b[0])), y1=int(round(b[1])), x2=int(round(b[2])), y2=int(round(b[3])),
                cls_id=int(c), conf=round(float(s), 5),
            )
            for b, s, c in zip(boxes, scores, classes)
        ]

    def predict_batch(
        self, batch_images: list[np.ndarray], offset: int, n_keypoints: int
    ) -> list[TVFrameResult]:
        results = []
        for i, image in enumerate(batch_images):
            try:
                boxes = self.detect(image)
            except Exception as exc:
                print(f"⚠️ frame {offset + i}: {type(exc).__name__}: {exc}")
                boxes = []
            results.append(TVFrameResult(frame_id=offset + i, boxes=boxes, polygons=[], keypoints=None))
        return results