Spaces:
Sleeping
Sleeping
Download analysis/nn.py from DmitryPlant/plants-analysis-api: direct link, hf CLI and curl.
- Browser
- Download file 4.94 kB
-
https://huggingface.co/spaces/DmitryPlant/plants-analysis-api/resolve/main/analysis/nn.py
- Command line
-
hf download hf://spaces/DmitryPlant/plants-analysis-api/analysis/nn.py
-
curl -L -o nn.py https://huggingface.co/spaces/DmitryPlant/plants-analysis-api/resolve/main/analysis/nn.py
4.94 kB
| """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 | |
| 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 | |