File size: 6,186 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
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
import os
from contextlib import asynccontextmanager
from typing import Any

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field

from analysis.encoding import bgr_to_png_b64, img_b64_to_bgr
from analysis.params import AnalysisParams
from analysis.pipeline import run
from analysis.scoring import (
    MATCH_FRAC_DEFAULT,
    MATCHER_FIXED_PX,
    MATCHER_RELATIVE_RADIUS,
    MIN_CONTOUR_POINTS,
    Center,
    MatcherKind,
    match,
)

#: Loading torch plus the checkpoint costs several seconds. On the deployed
#: Space that belongs in startup (see Dockerfile); locally and in tests it would
#: just make every run slower, so it is opt-in.
PRELOAD_NN = os.getenv("PRELOAD_NN") == "1"


@asynccontextmanager
async def lifespan(_: FastAPI):
    if PRELOAD_NN:
        from analysis.nn import warm_up

        warm_up()
    yield


app = FastAPI(title="SegmentLab API", lifespan=lifespan)

_allowed_origins = [
    o.strip() for o in os.getenv("ALLOWED_ORIGINS", "").split(",") if o.strip()
] or ["http://localhost:3000"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=_allowed_origins,
    allow_methods=["GET", "POST"],
    allow_headers=["Content-Type"],
)


class GTBundle(BaseModel):
    center: tuple[float, float]
    #: Needed by the relative matcher, which sizes its tolerance from the object.
    contour: list[tuple[float, float]] = Field(default_factory=list)


class GroundTruth(BaseModel):
    bundles: list[GTBundle]


class MatcherSpec(BaseModel):
    """How a prediction is judged to have landed on a ground-truth object."""

    matcher_kind: MatcherKind = MATCHER_RELATIVE_RADIUS
    matcher_param: float = MATCH_FRAC_DEFAULT
    #: Deprecated flat pixel tolerance. When sent it wins, so clients written
    #: before the matcher union keep their exact previous behaviour.
    match_radius: float | None = None

    def resolved(self) -> tuple[MatcherKind, float]:
        if self.match_radius is not None:
            return MATCHER_FIXED_PX, self.match_radius
        return self.matcher_kind, self.matcher_param


def _scored(

    pred_centers: list[Center], ground_truth: GroundTruth, spec: MatcherSpec

) -> dict[str, Any]:
    """Score predictions against ground truth, refusing to guess on bad input."""
    kind, param = spec.resolved()
    bundles = [gb.model_dump() for gb in ground_truth.bundles]
    usable = [b for b in bundles if len(b["contour"]) >= MIN_CONTOUR_POINTS]
    if kind == MATCHER_RELATIVE_RADIUS and bundles and not usable:
        raise HTTPException(
            status_code=400,
            detail="matcher 'relative_radius' needs ground-truth contours; "
                   "send them, or use matcher_kind 'fixed_px'",
        )
    return match(pred_centers, bundles, kind, param)


class AnalyzeRequest(MatcherSpec):
    image_b64: str
    params: dict[str, Any] = Field(default_factory=dict)
    return_stages: list[str] = Field(
        default_factory=lambda: ["mask", "normalized", "binary",
                                  "cleaned", "distance", "markers", "final"]
    )
    ground_truth: GroundTruth | None = None


@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}


@app.post("/analyze")
def analyze(req: AnalyzeRequest) -> dict[str, Any]:
    try:
        img = img_b64_to_bgr(req.image_b64)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=f"decode failed: {e}") from e

    try:
        params = AnalysisParams(**req.params)
    except TypeError as e:
        raise HTTPException(status_code=400, detail=f"bad params: {e}") from e

    result = run(img, params)

    response: dict[str, Any] = {
        "bundles": [
            {"id": b.id, "area": b.area, "center": list(b.center), "contour": b.contour}
            for b in result.bundles
        ],
        "stages": {
            name: bgr_to_png_b64(arr)
            for name, arr in result.stages.items()
            if name in req.return_stages
        },
        "timing_ms": {k: round(v, 1) for k, v in result.timings_ms.items()},
        "thresholds_used": result.thresholds_used,
    }

    if req.ground_truth is not None:
        response["score"] = _scored(
            [tuple(b.center) for b in result.bundles], req.ground_truth, req
        )
        response["matcher"] = dict(zip(("kind", "param"), req.resolved()))
        response["timing_ms"]["score"] = 0.0

    return response


class AnalyzeNNRequest(MatcherSpec):
    image_b64: str
    conf: float = 0.25
    ground_truth: GroundTruth | None = None


@app.post("/analyze_nn")
def analyze_nn(req: AnalyzeNNRequest) -> dict[str, Any]:
    try:
        img = img_b64_to_bgr(req.image_b64)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=f"decode failed: {e}") from e

    from analysis.nn import model_info, run_nn  # lazy: keeps torch out of startup

    info = model_info()
    bundles, dt_ms = run_nn(img, conf=req.conf)

    response: dict[str, Any] = {
        "bundles": bundles,
        "stages": {},
        "timing_ms": {"nn": round(dt_ms, 1)},
        # Echoed from the checkpoint, not hardcoded: a report that names the
        # wrong model or the wrong resolution is worse than one that names none.
        "thresholds_used": {
            "model": info.name,
            "imgsz": info.imgsz,
            "conf": req.conf,
        },
    }
    if req.ground_truth is not None:
        response["score"] = _scored(
            [tuple(b["center"]) for b in bundles], req.ground_truth, req
        )
        response["matcher"] = dict(zip(("kind", "param"), req.resolved()))
    return response


class ScoreRequest(MatcherSpec):
    run_bundles: list[GTBundle]
    gt_bundles: list[GTBundle]


@app.post("/score")
def score_only(req: ScoreRequest) -> dict[str, Any]:
    return _scored(
        [tuple(b.center) for b in req.run_bundles],
        GroundTruth(bundles=req.gt_bundles),
        req,
    )