File size: 4,943 Bytes
e04bbc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""YOLO11-seg inference.



Detects vascular bundles and returns them in the SAME shape as the classic

`/analyze` pipeline β€” ``{id, area, center, contour}`` (image-pixel coords) β€” so

the frontend can render NN results identically to algorithm results.



`ultralytics`/`torch` are imported lazily (only on first NN request) so the

service starts fast and `/analyze` stays lightweight. Call :func:`warm_up` at

startup to pay that cost before a user does.

"""
import time
from dataclasses import dataclass
from pathlib import Path

import cv2
import numpy as np

_MODELS: dict[str, object] = {}
_MODEL_PATH = Path(__file__).resolve().parent.parent / "models" / "bundles.pt"

#: Used only when a checkpoint carries no training record. It is the resolution
#: the first deployed model was trained at, so old weights keep their behaviour.
IMGSZ_FALLBACK = 768


@dataclass(frozen=True)
class ModelInfo:
    """What a checkpoint says about itself."""

    name: str
    imgsz: int


def _get_model(model_path: str | Path | None = None):
    """Load (and cache) a YOLO model. Defaults to the deployed weights.



    Keyed by path so the benchmark harness can score candidate weights through

    this exact code path β€” what it measures is then what /analyze_nn serves.

    """
    key = str(model_path or _MODEL_PATH)
    if key not in _MODELS:
        from ultralytics import YOLO  # heavy import β€” lazy

        _MODELS[key] = YOLO(key)
    return _MODELS[key]


def model_info(model_path: str | Path | None = None) -> ModelInfo:
    """Read the architecture and training resolution out of the checkpoint.



    Inference at a resolution the model was not trained at costs accuracy and

    raises no error, so the weights β€” not a default in this file β€” decide. Every

    checkpoint Ultralytics writes carries ``train_args``; the deployed weights

    were trained at 768 and every candidate since at 1024.

    """
    model = _get_model(model_path)
    train_args = (getattr(model, "ckpt", None) or {}).get("train_args") or {}
    overrides = getattr(model, "overrides", None) or {}
    imgsz = train_args.get("imgsz") or overrides.get("imgsz") or IMGSZ_FALLBACK
    name = train_args.get("model") or Path(str(model_path or _MODEL_PATH)).name
    return ModelInfo(name=str(name), imgsz=int(imgsz))


def warm_up(model_path: str | Path | None = None) -> ModelInfo:
    """Import torch and load the weights now, rather than on someone's click."""
    return model_info(model_path)


def _polygon_area(pts: np.ndarray) -> float:
    x, y = pts[:, 0], pts[:, 1]
    return float(abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) / 2.0)


def run_nn(

    img_bgr: np.ndarray,

    conf: float = 0.25,

    imgsz: int | None = None,

    model_path: str | Path | None = None,

    device: str | int | None = None,

    augment: bool = False,

    retina_masks: bool = False,

    epsilon: float = 1.5,

):
    """Run segmentation; return (bundles, inference_ms).



    `imgsz` defaults to the resolution these weights were trained at, read from

    the checkpoint β€” pass it only to deliberately infer at another size.

    `augment` enables test-time augmentation (slower, usually higher recall).

    `retina_masks` decodes masks at full input resolution instead of the

    downsampled prototype grid β€” the default grid is what makes bundle outlines

    come back with blocky, straight-cut edges. `epsilon` is the polygon

    simplification tolerance in px; raise it for fewer points, lower it to keep

    contour detail. All default to current behaviour.

    """
    model = _get_model(model_path)
    resolution = imgsz if imgsz is not None else model_info(model_path).imgsz
    t0 = time.perf_counter()
    results = model.predict(
        img_bgr, imgsz=resolution, conf=conf, verbose=False,
        augment=augment, retina_masks=retina_masks,
        **({"device": device} if device is not None else {}),
    )
    dt_ms = (time.perf_counter() - t0) * 1000.0

    bundles: list[dict] = []
    r = results[0]
    if r.masks is not None:
        for i, poly in enumerate(r.masks.xy):  # poly: Nx2 float px, original coords
            if poly is None or len(poly) < 3:
                continue
            pts = np.asarray(poly, dtype=np.float32)
            # the raw mask boundary is dense β€” simplify it
            approx = cv2.approxPolyDP(pts.reshape(-1, 1, 2), epsilon, True).reshape(-1, 2)
            if len(approx) < 3:
                approx = pts
            bundles.append(
                {
                    "id": i + 1,
                    "area": int(round(_polygon_area(approx))),
                    "center": [float(approx[:, 0].mean()), float(approx[:, 1].mean())],
                    "contour": [[float(x), float(y)] for x, y in approx],
                }
            )
    return bundles, dt_ms