Spaces:
Sleeping
Sleeping
Download app.py from DmitryPlant/plants-analysis-api: direct link, hf CLI and curl.
- Browser
- Download file 6.19 kB
-
https://huggingface.co/spaces/DmitryPlant/plants-analysis-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/DmitryPlant/plants-analysis-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DmitryPlant/plants-analysis-api/resolve/main/app.py
6.19 kB
| 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" | |
| 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 | |
| def health() -> dict[str, str]: | |
| return {"status": "ok"} | |
| 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 | |
| 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] | |
| 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, | |
| ) | |