File size: 4,632 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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,
        },
    }