File size: 11,011 Bytes
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
e3b60de
190dbf0
06bdaca
 
 
 
 
e3b60de
cac4938
 
e3b60de
 
2b21a73
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
cac4938
 
 
 
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d16c4ed
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b21a73
06bdaca
2b21a73
06bdaca
2b21a73
06bdaca
 
 
 
 
cac4938
 
 
2b21a73
06bdaca
 
 
cac4938
 
 
 
 
 
 
 
 
06bdaca
 
 
2b21a73
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d16c4ed
 
 
 
 
 
 
 
 
 
 
 
 
06bdaca
 
 
 
 
 
d16c4ed
 
 
 
 
 
 
 
 
 
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
cac4938
 
 
06bdaca
cac4938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cac4938
 
 
06bdaca
 
cac4938
 
 
 
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cac4938
06bdaca
 
 
 
 
 
 
cac4938
06bdaca
 
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b505c60
06bdaca
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Server-side ONNX pipe detection (CPU).

Used as a fallback when a client device cannot load / run the in-browser model.
Mirrors the browser inference pipeline (letterbox -> ONNX -> decode -> NMS) so
results are consistent regardless of where inference runs.
"""
from __future__ import annotations

import os
from pathlib import Path
from threading import Lock
from typing import Any

from postprocess import apply_detection_postprocess, select_nms_iou

STATIC_PATH = Path(__file__).resolve().parent / "static"
MODEL_DIR = STATIC_PATH / "models"

INFERENCE_SIZE = 1024
INFERENCE_SIZE_SMALL = 640
CONF_THRESHOLD = 0.52
CONF_THRESHOLD_YOLO11 = 0.25
CONF_THRESHOLD_YOLO11_SINGLE = 0.45
IOU_THRESHOLD = 0.45
MAX_DET = 6000
TILE_OVERLAP = 0.28

_sessions: dict[str, Any] = {}
_session_lock = Lock()
_active_backend = "cpu"


def is_available() -> bool:
    """True when server-side inference can run (deps + model files present)."""
    try:
        import numpy  # noqa: F401
        import onnxruntime  # noqa: F401
        import cv2  # noqa: F401
    except Exception:
        return False
    return any(
        (MODEL_DIR / name).is_file()
        for name in ("yolo11s-pvc.onnx", "yolo11m-pvc.onnx", "countmodel.onnx", "countmodel-640.onnx")
    )


def get_active_backend() -> str:
    return _active_backend


def _get_session(model_path: Path):
    global _active_backend
    key = str(model_path)
    sess = _sessions.get(key)
    if sess is not None:
        return sess
    with _session_lock:
        sess = _sessions.get(key)
        if sess is not None:
            return sess
        import onnxruntime as ort

        opts = ort.SessionOptions()
        cores = os.cpu_count() or 2
        opts.intra_op_num_threads = max(1, min(8, cores))
        opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
        providers = ort.get_available_providers()
        # Prefer GPU if present on the host, else CPU.
        chosen = [p for p in ("CUDAExecutionProvider", "CPUExecutionProvider") if p in providers]
        if not chosen:
            chosen = ["CPUExecutionProvider"]
        _active_backend = "cuda" if chosen[0] == "CUDAExecutionProvider" else "cpu"
        sess = ort.InferenceSession(str(model_path), sess_options=opts, providers=chosen)
        _sessions[key] = sess
        return sess


def _megapixels(w: int, h: int) -> float:
    return (w * h) / 1_000_000


def _suggest_tile_grid(w: int, h: int) -> int:
    mp = _megapixels(w, h)
    if mp >= 6:
        return 5
    if mp >= 3:
        return 4
    if mp >= 1.2:
        return 3
    return 2


def _should_auto_tile(w: int, h: int) -> bool:
    # Tile liberally: dense bundles need tiling for small-pipe recall even at
    # modest resolutions (a ~1MP image can hold 1000+ pipe ends). The higher
    # 3.0MP / 2000px cutoff under-counted dense-but-small photos.
    return _megapixels(w, h) >= 0.75 or max(w, h) > 1400


def _select_model(w: int, h: int) -> tuple[Path, int]:
    # Prefer YOLO11s (fastest CPU, best tiling performance)
    yolo11s = MODEL_DIR / "yolo11s-pvc.onnx"
    if yolo11s.is_file():
        return yolo11s, INFERENCE_SIZE_SMALL
    # Fall back to YOLO11m
    yolo11m = MODEL_DIR / "yolo11m-pvc.onnx"
    if yolo11m.is_file():
        return yolo11m, INFERENCE_SIZE_SMALL
    # Fall back to YOLOv5
    big = MODEL_DIR / "countmodel.onnx"
    if big.is_file():
        return big, INFERENCE_SIZE
    return MODEL_DIR / "countmodel-640.onnx", INFERENCE_SIZE_SMALL


def _letterbox(img, size: int):
    import cv2
    import numpy as np

    h, w = img.shape[:2]
    scale = min(size / w, size / h)
    new_w, new_h = int(round(w * scale)), int(round(h * scale))
    pad_x = (size - new_w) // 2
    pad_y = (size - new_h) // 2
    out = np.full((size, size, 3), 114, dtype=np.uint8)
    resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
    out[pad_y : pad_y + new_h, pad_x : pad_x + new_w] = resized
    tensor = out[:, :, ::-1].astype(np.float32) / 255.0
    chw = np.transpose(tensor, (2, 0, 1))[None, ...]
    return chw, {"scale": scale, "pad_x": pad_x, "pad_y": pad_y}


def _nms(boxes, scores, iou_thres=IOU_THRESHOLD, max_det=MAX_DET):
    import numpy as np

    if len(boxes) == 0:
        return []

    boxes_arr = np.asarray(boxes, dtype=np.float32)
    scores_arr = np.asarray(scores, dtype=np.float32)
    x1 = boxes_arr[:, 0]
    y1 = boxes_arr[:, 1]
    x2 = boxes_arr[:, 2]
    y2 = boxes_arr[:, 3]
    areas = (x2 - x1) * (y2 - y1)
    order = scores_arr.argsort()[::-1]
    keep: list[int] = []

    while order.size > 0 and len(keep) < max_det:
        i = int(order[0])
        keep.append(i)
        if order.size == 1:
            break
        rest = order[1:]
        xx1 = np.maximum(x1[i], x1[rest])
        yy1 = np.maximum(y1[i], y1[rest])
        xx2 = np.minimum(x2[i], x2[rest])
        yy2 = np.minimum(y2[i], y2[rest])
        w = np.maximum(0.0, xx2 - xx1)
        h = np.maximum(0.0, yy2 - yy1)
        inter = w * h
        iou = inter / (areas[i] + areas[rest] - inter + 1e-6)
        order = rest[iou <= iou_thres]

    return keep


def _filter_outliers(boxes):
    import numpy as np

    if len(boxes) < 3:
        return list(range(len(boxes)))
    areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
    median = float(np.median(areas))
    return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]


def _decode(output, meta, img_w, img_h, offset_x=0, offset_y=0, conf_threshold=None):
    if conf_threshold is None:
        conf_threshold = CONF_THRESHOLD
    boxes, scores = [], []
    # YOLO11 output: (1, 5, 8400) -> squeeze -> (5, 8400) -> transpose -> (8400, 5)
    # YOLOv5 output: (1, 25200, 6) -> squeeze -> (25200, 6) -> already rows
    if output.ndim == 3:
        output = output[0]  # remove batch dim
    if output.shape[0] == 5:
        # YOLOv8/v11 format: transposed to (N, 5) where cols are [cx, cy, w, h, conf]
        for row in output.T:
            cx, cy, w, h, conf = float(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4])
            if conf < conf_threshold:
                continue
            x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
            y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
            x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
            y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
            x1, y1 = max(0, x1), max(0, y1)
            x2, y2 = min(img_w, x2), min(img_h, y2)
            if x2 <= x1 or y2 <= y1:
                continue
            boxes.append([x1, y1, x2, y2])
            scores.append(conf)
    else:
        # YOLOv5 format: (N, 6) where cols are [cx, cy, w, h, obj, cls]
        for row in output.reshape(-1, 6):
            cx, cy, w, h, obj, cls = row
            conf = float(obj * cls)
            if conf < CONF_THRESHOLD:
                continue
            x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
            y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
            x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
            y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
            x1, y1 = max(0, x1), max(0, y1)
            x2, y2 = min(img_w, x2), min(img_h, y2)
            if x2 <= x1 or y2 <= y1:
                continue
            boxes.append([x1, y1, x2, y2])
            scores.append(conf)
    return boxes, scores


def detect_bytes(
    image_bytes: bytes,
    use_tiling: bool | None = None,
    auto_tile: bool = True,
    filter_outliers_flag: bool = False,
) -> dict[str, Any]:
    import time

    import cv2
    import numpy as np

    arr = np.frombuffer(image_bytes, dtype=np.uint8)
    img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
    if img is None:
        raise ValueError("Could not decode image")

    h, w = img.shape[:2]
    model_path, infer_size = _select_model(w, h)
    session = _get_session(model_path)
    # YOLO11 models use a lower conf threshold (different confidence calibration)
    is_yolo11 = "yolo11" in model_path.stem.lower()
    conf_thresh = CONF_THRESHOLD_YOLO11 if is_yolo11 else CONF_THRESHOLD

    tile = use_tiling if use_tiling is not None else (auto_tile and _should_auto_tile(w, h))
    # YOLO11 adaptive conf: low for tiled (dense bundles have low-conf pipes),
    # high for single-frame (eliminates false positives on sparse images).
    if is_yolo11:
        conf_thresh = CONF_THRESHOLD_YOLO11 if tile else CONF_THRESHOLD_YOLO11_SINGLE
    t0 = time.perf_counter()

    if tile:
        grid = _suggest_tile_grid(w, h)
        tile_w = w / grid
        tile_h = h / grid
        all_boxes: list = []
        all_scores: list = []
        for gy in range(grid):
            for gx in range(grid):
                x1 = max(0, gx * tile_w - (tile_w * TILE_OVERLAP * (gx > 0)))
                y1 = max(0, gy * tile_h - (tile_h * TILE_OVERLAP * (gy > 0)))
                x2 = min(w, (gx + 1) * tile_w + (tile_w * TILE_OVERLAP * (gx < grid - 1)))
                y2 = min(h, (gy + 1) * tile_h + (tile_h * TILE_OVERLAP * (gy < grid - 1)))
                crop = img[int(y1) : int(y2), int(x1) : int(x2)]
                tensor, meta = _letterbox(crop, infer_size)
                out = session.run(None, {"images": tensor})[0]
                boxes, scores = _decode(out, meta, w, h, int(x1), int(y1), conf_threshold=conf_thresh)
                all_boxes.extend(boxes)
                all_scores.extend(scores)
        boxes, scores = all_boxes, all_scores
        mode = f"tiling {grid}x{grid}"
    else:
        tensor, meta = _letterbox(img, infer_size)
        out = session.run(None, {"images": tensor})[0]
        boxes, scores = _decode(out, meta, w, h, conf_threshold=conf_thresh)
        mode = "single frame"

    raw_count = len(boxes)
    keep = _nms(boxes, scores, iou_thres=select_nms_iou(len(boxes)))
    boxes = [boxes[i] for i in keep]
    scores = [scores[i] for i in keep]
    post_nms_count = len(boxes)
    boxes, scores, report = apply_detection_postprocess(
        boxes,
        scores,
        extra_outlier_filter=filter_outliers_flag,
        filter_outliers_fn=_filter_outliers,
        was_tiled=tile,
    )
    report["raw"] = raw_count
    report["after_nms"] = post_nms_count
    report["removed_by_nms"] = raw_count - post_nms_count
    report["tiling_used"] = bool(tile)

    ms = (time.perf_counter() - t0) * 1000
    detections = [
        {
            "xmin": float(b[0]),
            "ymin": float(b[1]),
            "xmax": float(b[2]),
            "ymax": float(b[3]),
            "confidence": float(s),
        }
        for b, s in zip(boxes, scores)
    ]
    return {
        "detections": detections,
        "count": len(detections),
        "width": w,
        "height": h,
        "ms": round(ms),
        "model": model_path.name,
        "mode": mode,
        "backend": f"server-{get_active_backend()}",
        "postprocess": report,
    }