"""Segmentation inference and model metadata helpers.""" import numpy as np import torch from PIL import Image import state from config.models import ( DEPTH_MODEL_NAME, INTRINSIC_MODEL_VERSION, MOGE_MODEL_NAME, ONEFORMER_MODEL_NAME, ) from config.runtime import ENABLE_INTRINSIC_SHADING, ENABLE_ONNX_INFERENCE from models.loader import _load_segmentation_model from enums import GeometryProvider def _run_segmentation_onnx(img: Image.Image, img_np: np.ndarray, out_h: int, out_w: int) -> np.ndarray | None: """Try running segmentation via ONNX Runtime. Returns None if unavailable.""" if not ENABLE_ONNX_INFERENCE: return None from models.onnx_loader import load_seg_onnx_session session = load_seg_onnx_session() if session is None: return None if state.seg_processor is None: _load_segmentation_model() inputs = state.seg_processor(images=img, task_inputs=["semantic"], return_tensors="np") input_feed = {k: v for k, v in inputs.items() if k in [inp.name for inp in session.get_inputs()]} outputs = session.run(None, input_feed) # Post-process: outputs[1] is masks_queries_logits — take argmax over class queries class_queries = torch.from_numpy(outputs[0]) mask_queries = torch.from_numpy(outputs[1]) # Replicate HuggingFace post-processing masks = torch.nn.functional.interpolate( mask_queries, size=(out_h, out_w), mode="bilinear", align_corners=False, ) # masks shape: [batch, num_queries, H, W], class_queries: [batch, num_queries, num_classes+1] seg_map = torch.einsum("bqc,bqhw->bchw", class_queries.softmax(-1)[..., :-1], masks.sigmoid()) seg_map = seg_map[0].argmax(0) return seg_map.numpy().astype(np.uint8) def run_segmentation(img: Image.Image, img_np: np.ndarray, target_h: int | None = None, target_w: int | None = None): """Run segmentation on the given image. If target_h/target_w are provided, post-process outputs at that resolution (used when inference runs on a downscaled image but masks are needed at original size). """ h, w = img_np.shape[:2] out_h = target_h if target_h is not None else h out_w = target_w if target_w is not None else w with state.gpu_inference(): return _run_segmentation_model(img, img_np, out_h, out_w) def _run_segmentation_model(img: Image.Image, img_np: np.ndarray, out_h: int, out_w: int) -> np.ndarray: # Try ONNX first result = _run_segmentation_onnx(img, img_np, out_h, out_w) if result is not None: return result # Fallback to PyTorch if state.seg_model is None: _load_segmentation_model() inputs = state.seg_processor( images=img, task_inputs=["semantic"], return_tensors="pt", ).to(state.device) use_autocast = state.device.type == "cuda" with torch.no_grad(): if use_autocast: with torch.autocast(device_type="cuda", dtype=torch.float16): outputs = state.seg_model(**inputs) else: outputs = state.seg_model(**inputs) result = state.seg_processor.post_process_semantic_segmentation( outputs, target_sizes=[(out_h, out_w)], )[0] return result.cpu().numpy().astype(np.uint8) def segmenter_metadata_name() -> str: return "oneformer-ade20k-swin-large" def active_segmentation_model_name() -> str: return ONEFORMER_MODEL_NAME def active_geometry_model_name(provider: str | None) -> str | None: if provider == GeometryProvider.MOGE_2: return MOGE_MODEL_NAME if provider and provider != GeometryProvider.HOMOGRAPHY: return DEPTH_MODEL_NAME return None def active_model_metadata( geometry: dict | None, depth: np.ndarray | None, shade_map: np.ndarray | None, intrinsic_lighting_used: bool = False, ) -> dict: geometry_provider = geometry.get("provider") if geometry else None intrinsic_enabled = ENABLE_INTRINSIC_SHADING and intrinsic_lighting_used and shade_map is not None return { "segmentation": { "backend": state.segmentation_backend, "name": active_segmentation_model_name(), }, "geometry": { "provider": geometry_provider, "name": active_geometry_model_name(geometry_provider), }, "depth": { "enabled": depth is not None, "name": DEPTH_MODEL_NAME if depth is not None else None, }, "intrinsic": { "enabled": intrinsic_enabled, "name": INTRINSIC_MODEL_VERSION if intrinsic_enabled else None, }, }