Spaces:
Paused
Paused
Download apps/renderer/routes/segmentation.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 3.93 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/routes/segmentation.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/routes/segmentation.py
-
curl -L -o segmentation.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/routes/segmentation.py
3.93 kB
| """Segmentation routes: panoptic polygon extraction and bundle generation.""" | |
| import numpy as np | |
| import torch | |
| from fastapi import APIRouter, Depends, File, Form, UploadFile | |
| from config.models import ONEFORMER_MODEL_NAME | |
| from models.loader import _load_segmentation_model | |
| from services.access.policy import require_client | |
| from services.image.loading import load_uploaded_rgb_image | |
| from services.image.polygons import mask_to_polygons | |
| from services.pipeline.builder import build_segmentation_bundle | |
| from state import class_name_for_id | |
| router = APIRouter(tags=["segmentation"], dependencies=[Depends(require_client)]) | |
| def build_oneformer_polygon_response( | |
| contents: bytes, | |
| *, | |
| threshold: float = 0.5, | |
| mask_threshold: float = 0.5, | |
| min_area: float = 32.0, | |
| simplify_epsilon: float = 2.0, | |
| ) -> dict: | |
| img, img_np = load_uploaded_rgb_image(contents) | |
| h, w = img_np.shape[:2] | |
| threshold = float(np.clip(threshold, 0.0, 1.0)) | |
| mask_threshold = float(np.clip(mask_threshold, 0.0, 1.0)) | |
| min_area = max(0.0, float(min_area)) | |
| simplify_epsilon = max(0.0, float(simplify_epsilon)) | |
| _load_segmentation_model() | |
| import state as _state | |
| inputs = _state.seg_processor( | |
| images=img, | |
| task_inputs=["panoptic"], | |
| return_tensors="pt", | |
| ).to(_state.device) | |
| with _state.gpu_inference(): | |
| with torch.no_grad(): | |
| outputs = _state.seg_model(**inputs) | |
| result = _state.seg_processor.post_process_panoptic_segmentation( | |
| outputs, | |
| threshold=threshold, | |
| mask_threshold=mask_threshold, | |
| target_sizes=[(h, w)], | |
| )[0] | |
| segmentation = result.get("segmentation") | |
| if segmentation is None: | |
| return { | |
| "model": ONEFORMER_MODEL_NAME, | |
| "task": "panoptic", | |
| "width": int(w), | |
| "height": int(h), | |
| "segments": [], | |
| } | |
| if isinstance(segmentation, torch.Tensor): | |
| segment_map = segmentation.cpu().numpy() | |
| else: | |
| segment_map = np.asarray(segmentation) | |
| segments = [] | |
| for segment_info in result.get("segments_info", []): | |
| segment_id = int(segment_info["id"]) | |
| label_id = int(segment_info["label_id"]) | |
| mask = segment_map == segment_id | |
| polygons = mask_to_polygons(mask, min_area, simplify_epsilon) | |
| if not polygons: | |
| continue | |
| score = segment_info.get("score") | |
| segments.append({ | |
| "id": segment_id, | |
| "labelId": label_id, | |
| "label": class_name_for_id(label_id), | |
| "confidence": float(score) if score is not None else None, | |
| "wasFused": bool(segment_info.get("was_fused", False)), | |
| "pixelArea": int(mask.sum()), | |
| "polygons": polygons, | |
| }) | |
| segments.sort(key=lambda item: item["pixelArea"], reverse=True) | |
| return { | |
| "model": ONEFORMER_MODEL_NAME, | |
| "task": "panoptic", | |
| "width": int(w), | |
| "height": int(h), | |
| "threshold": threshold, | |
| "maskThreshold": mask_threshold, | |
| "minArea": min_area, | |
| "simplifyEpsilon": simplify_epsilon, | |
| "segmentCount": len(segments), | |
| "segments": segments, | |
| } | |
| async def oneformer_polygons( | |
| file: UploadFile = File(...), | |
| threshold: float = Form(0.5), | |
| mask_threshold: float = Form(0.5), | |
| min_area: float = Form(32.0), | |
| simplify_epsilon: float = Form(2.0), | |
| ): | |
| contents = await file.read() | |
| return build_oneformer_polygon_response( | |
| contents, | |
| threshold=threshold, | |
| mask_threshold=mask_threshold, | |
| min_area=min_area, | |
| simplify_epsilon=simplify_epsilon, | |
| ) | |
| async def segment(file: UploadFile = File(...)): | |
| contents = await file.read() | |
| bundle = build_segmentation_bundle(contents) | |
| bundle.pop("enhanceContext", None) | |
| return bundle | |