github-actions[bot] commited on
Commit ·
1003449
1
Parent(s): 532466c
Automated Deploy: 0ebb69f0b27758b94dc8d7f04680c5e456ea2dd8
Browse files- .gitignore +3 -0
- config/lighting.py +2 -2
- config/runtime.py +10 -0
- enums.py +1 -0
- models/depth.py +60 -13
- models/loader.py +7 -0
- models/onnx_loader.py +69 -0
- models/segmentation.py +54 -5
- routes/viz2d.py +29 -3
- scripts/export_onnx.py +104 -0
- services/jobs/conversion.py +48 -13
- services/lighting/reflection.py +1 -1
- services/lighting/shading.py +5 -5
- services/pipeline/builder.py +81 -24
- services/pipeline/bundle_assembly.py +12 -9
- services/pipeline/inference_utils.py +44 -0
- services/pipeline/packaging.py +8 -2
- services/pipeline/preview_builder.py +139 -0
- state.py +4 -0
- visualizer.gpu.toml +1 -0
- visualizer.hf.toml +2 -1
- visualizer.local.toml +1 -0
.gitignore
CHANGED
|
@@ -20,6 +20,9 @@ build/
|
|
| 20 |
.cache/
|
| 21 |
~/.cache/huggingface/
|
| 22 |
|
|
|
|
|
|
|
|
|
|
| 23 |
# Environment variables
|
| 24 |
.env
|
| 25 |
.env.local
|
|
|
|
| 20 |
.cache/
|
| 21 |
~/.cache/huggingface/
|
| 22 |
|
| 23 |
+
# ONNX exported models
|
| 24 |
+
onnx_models/
|
| 25 |
+
|
| 26 |
# Environment variables
|
| 27 |
.env
|
| 28 |
.env.local
|
config/lighting.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
LIGHTING_TRANSFER_VERSION = 4
|
| 2 |
|
| 3 |
-
SHADE_MAP_MIN = 0.
|
| 4 |
-
SHADE_MAP_MAX = 1.
|
| 5 |
SHOWROOM_SHADE_MAP_MIN = 0.85
|
| 6 |
SHOWROOM_SHADE_MAP_MAX = 1.12
|
| 7 |
SHADE_MAP_ENCODING = "linear-relative"
|
|
|
|
| 1 |
LIGHTING_TRANSFER_VERSION = 4
|
| 2 |
|
| 3 |
+
SHADE_MAP_MIN = 0.15
|
| 4 |
+
SHADE_MAP_MAX = 1.10
|
| 5 |
SHOWROOM_SHADE_MAP_MIN = 0.85
|
| 6 |
SHOWROOM_SHADE_MAP_MAX = 1.12
|
| 7 |
SHADE_MAP_ENCODING = "linear-relative"
|
config/runtime.py
CHANGED
|
@@ -11,6 +11,12 @@ ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "e
|
|
| 11 |
ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
|
| 12 |
WARM_START_MODELS = config_bool("WARM_START_MODELS", "runtime", "warm_start_models", "1")
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
BUNDLE_IMAGE_FORMAT = str(config_value(
|
| 15 |
"BUNDLE_IMAGE_FORMAT", "runtime", "bundle_image_format", "jpeg",
|
| 16 |
)).lower()
|
|
@@ -23,6 +29,10 @@ ROOM_UPLOAD_MAX_DIMENSION = max(720, int(config_value(
|
|
| 23 |
"ROOM_UPLOAD_MAX_DIMENSION", "runtime", "room_upload_max_dimension", "1920",
|
| 24 |
)))
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
ROOM_UPLOAD_JPEG_QUALITY = min(95, max(50, int(config_value(
|
| 27 |
"ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85",
|
| 28 |
))))
|
|
|
|
| 11 |
ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
|
| 12 |
WARM_START_MODELS = config_bool("WARM_START_MODELS", "runtime", "warm_start_models", "1")
|
| 13 |
|
| 14 |
+
ENABLE_ONNX_INFERENCE = config_bool("ENABLE_ONNX_INFERENCE", "runtime", "enable_onnx_inference", "0")
|
| 15 |
+
|
| 16 |
+
ONNX_MODEL_DIR = str(config_value(
|
| 17 |
+
"ONNX_MODEL_DIR", "runtime", "onnx_model_dir", "onnx_models",
|
| 18 |
+
))
|
| 19 |
+
|
| 20 |
BUNDLE_IMAGE_FORMAT = str(config_value(
|
| 21 |
"BUNDLE_IMAGE_FORMAT", "runtime", "bundle_image_format", "jpeg",
|
| 22 |
)).lower()
|
|
|
|
| 29 |
"ROOM_UPLOAD_MAX_DIMENSION", "runtime", "room_upload_max_dimension", "1920",
|
| 30 |
)))
|
| 31 |
|
| 32 |
+
INFERENCE_MAX_DIMENSION = max(512, int(config_value(
|
| 33 |
+
"INFERENCE_MAX_DIMENSION", "runtime", "inference_max_dimension", "1024",
|
| 34 |
+
)))
|
| 35 |
+
|
| 36 |
ROOM_UPLOAD_JPEG_QUALITY = min(95, max(50, int(config_value(
|
| 37 |
"ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85",
|
| 38 |
))))
|
enums.py
CHANGED
|
@@ -6,6 +6,7 @@ from enum import StrEnum
|
|
| 6 |
class JobStatus(StrEnum):
|
| 7 |
QUEUED = "QUEUED"
|
| 8 |
PROCESSING = "PROCESSING"
|
|
|
|
| 9 |
COMPLETED = "COMPLETED"
|
| 10 |
FAILED = "FAILED"
|
| 11 |
|
|
|
|
| 6 |
class JobStatus(StrEnum):
|
| 7 |
QUEUED = "QUEUED"
|
| 8 |
PROCESSING = "PROCESSING"
|
| 9 |
+
PREVIEW_READY = "PREVIEW_READY"
|
| 10 |
COMPLETED = "COMPLETED"
|
| 11 |
FAILED = "FAILED"
|
| 12 |
|
models/depth.py
CHANGED
|
@@ -7,23 +7,68 @@ from PIL import Image
|
|
| 7 |
|
| 8 |
import state
|
| 9 |
from config.models import DEPTH_MODEL_NAME, GEOMETRY_MODEL, MOGE_MODEL_NAME
|
| 10 |
-
from config.runtime import ENABLE_DEPTH_ESTIMATION, ENABLE_MOGE_GEOMETRY
|
| 11 |
from models.loader import _load_depth_model, _load_moge_model
|
| 12 |
from enums import GeometryProvider
|
| 13 |
from utils import to_numpy
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def estimate_depth(img: Image.Image, width: int, height: int):
|
| 17 |
if not ENABLE_DEPTH_ESTIMATION:
|
| 18 |
return None
|
| 19 |
|
| 20 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
if not _load_depth_model():
|
| 22 |
return None
|
| 23 |
|
| 24 |
inputs = state.depth_processor(images=img, return_tensors="pt").to(state.device)
|
|
|
|
| 25 |
with torch.no_grad():
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
depth = torch.nn.functional.interpolate(
|
| 28 |
outputs.predicted_depth.unsqueeze(1),
|
| 29 |
size=(height, width),
|
|
@@ -42,7 +87,8 @@ def estimate_depth(img: Image.Image, width: int, height: int):
|
|
| 42 |
return None
|
| 43 |
|
| 44 |
|
| 45 |
-
def estimate_moge_geometry(img_np: np.ndarray):
|
|
|
|
| 46 |
if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda":
|
| 47 |
return None
|
| 48 |
|
|
@@ -61,17 +107,18 @@ def estimate_moge_geometry(img_np: np.ndarray):
|
|
| 61 |
intrinsics = to_numpy(output.get("intrinsics"))
|
| 62 |
if points is None or points.ndim != 3 or points.shape[2] != 3:
|
| 63 |
raise RuntimeError("MoGe did not return an HxWx3 point map.")
|
| 64 |
-
|
| 65 |
-
if
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
| 72 |
valid_mask = cv2.resize(
|
| 73 |
valid_mask.astype(np.uint8),
|
| 74 |
-
(
|
| 75 |
interpolation=cv2.INTER_NEAREST,
|
| 76 |
).astype(bool)
|
| 77 |
if depth is None:
|
|
@@ -100,7 +147,7 @@ def estimate_moge_geometry(img_np: np.ndarray):
|
|
| 100 |
|
| 101 |
|
| 102 |
def estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int):
|
| 103 |
-
geometry = estimate_moge_geometry(img_np)
|
| 104 |
if geometry is not None:
|
| 105 |
return geometry
|
| 106 |
|
|
|
|
| 7 |
|
| 8 |
import state
|
| 9 |
from config.models import DEPTH_MODEL_NAME, GEOMETRY_MODEL, MOGE_MODEL_NAME
|
| 10 |
+
from config.runtime import ENABLE_DEPTH_ESTIMATION, ENABLE_MOGE_GEOMETRY, ENABLE_ONNX_INFERENCE
|
| 11 |
from models.loader import _load_depth_model, _load_moge_model
|
| 12 |
from enums import GeometryProvider
|
| 13 |
from utils import to_numpy
|
| 14 |
|
| 15 |
|
| 16 |
+
def _estimate_depth_onnx(img: Image.Image, width: int, height: int) -> np.ndarray | None:
|
| 17 |
+
"""Try running depth estimation via ONNX Runtime. Returns None if unavailable."""
|
| 18 |
+
if not ENABLE_ONNX_INFERENCE:
|
| 19 |
+
return None
|
| 20 |
+
from models.onnx_loader import load_depth_onnx_session
|
| 21 |
+
session = load_depth_onnx_session()
|
| 22 |
+
if session is None:
|
| 23 |
+
return None
|
| 24 |
+
|
| 25 |
+
if state.depth_processor is None:
|
| 26 |
+
_load_depth_model()
|
| 27 |
+
|
| 28 |
+
inputs = state.depth_processor(images=img, return_tensors="np")
|
| 29 |
+
input_feed = {k: v for k, v in inputs.items() if k in [inp.name for inp in session.get_inputs()]}
|
| 30 |
+
outputs = session.run(None, input_feed)
|
| 31 |
+
|
| 32 |
+
# outputs[0] is predicted_depth — interpolate to target size
|
| 33 |
+
depth_tensor = torch.from_numpy(outputs[0])
|
| 34 |
+
if depth_tensor.ndim == 2:
|
| 35 |
+
depth_tensor = depth_tensor.unsqueeze(0).unsqueeze(0)
|
| 36 |
+
elif depth_tensor.ndim == 3:
|
| 37 |
+
depth_tensor = depth_tensor.unsqueeze(1)
|
| 38 |
+
depth = torch.nn.functional.interpolate(
|
| 39 |
+
depth_tensor, size=(height, width), mode="bicubic", align_corners=False,
|
| 40 |
+
).squeeze().numpy()
|
| 41 |
+
return depth
|
| 42 |
+
|
| 43 |
+
|
| 44 |
def estimate_depth(img: Image.Image, width: int, height: int):
|
| 45 |
if not ENABLE_DEPTH_ESTIMATION:
|
| 46 |
return None
|
| 47 |
|
| 48 |
try:
|
| 49 |
+
# Try ONNX first
|
| 50 |
+
depth = _estimate_depth_onnx(img, width, height)
|
| 51 |
+
if depth is not None:
|
| 52 |
+
depth = cv2.GaussianBlur(depth.astype(np.float32), (0, 0), sigmaX=3)
|
| 53 |
+
if "metric" in DEPTH_MODEL_NAME.lower():
|
| 54 |
+
return depth
|
| 55 |
+
depth_min, depth_max = float(np.min(depth)), float(np.max(depth))
|
| 56 |
+
if depth_max - depth_min < 1e-6:
|
| 57 |
+
return None
|
| 58 |
+
return (depth - depth_min) / (depth_max - depth_min)
|
| 59 |
+
|
| 60 |
+
# Fallback to PyTorch
|
| 61 |
if not _load_depth_model():
|
| 62 |
return None
|
| 63 |
|
| 64 |
inputs = state.depth_processor(images=img, return_tensors="pt").to(state.device)
|
| 65 |
+
use_autocast = state.device.type == "cuda"
|
| 66 |
with torch.no_grad():
|
| 67 |
+
if use_autocast:
|
| 68 |
+
with torch.autocast(device_type="cuda", dtype=torch.float16):
|
| 69 |
+
outputs = state.depth_model(**inputs)
|
| 70 |
+
else:
|
| 71 |
+
outputs = state.depth_model(**inputs)
|
| 72 |
depth = torch.nn.functional.interpolate(
|
| 73 |
outputs.predicted_depth.unsqueeze(1),
|
| 74 |
size=(height, width),
|
|
|
|
| 87 |
return None
|
| 88 |
|
| 89 |
|
| 90 |
+
def estimate_moge_geometry(img_np: np.ndarray, target_h: int | None = None, target_w: int | None = None):
|
| 91 |
+
"""Run MoGe geometry on img_np, upscale outputs to target_h x target_w if provided."""
|
| 92 |
if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda":
|
| 93 |
return None
|
| 94 |
|
|
|
|
| 107 |
intrinsics = to_numpy(output.get("intrinsics"))
|
| 108 |
if points is None or points.ndim != 3 or points.shape[2] != 3:
|
| 109 |
raise RuntimeError("MoGe did not return an HxWx3 point map.")
|
| 110 |
+
out_h = target_h if target_h is not None else img_np.shape[0]
|
| 111 |
+
out_w = target_w if target_w is not None else img_np.shape[1]
|
| 112 |
+
if points.shape[:2] != (out_h, out_w):
|
| 113 |
+
points = cv2.resize(points, (out_w, out_h), interpolation=cv2.INTER_LINEAR)
|
| 114 |
+
if depth is not None and depth.shape[:2] != (out_h, out_w):
|
| 115 |
+
depth = cv2.resize(depth, (out_w, out_h), interpolation=cv2.INTER_LINEAR)
|
| 116 |
+
if normals is not None and normals.shape[:2] != (out_h, out_w):
|
| 117 |
+
normals = cv2.resize(normals, (out_w, out_h), interpolation=cv2.INTER_LINEAR)
|
| 118 |
+
if valid_mask is not None and valid_mask.shape[:2] != (out_h, out_w):
|
| 119 |
valid_mask = cv2.resize(
|
| 120 |
valid_mask.astype(np.uint8),
|
| 121 |
+
(out_w, out_h),
|
| 122 |
interpolation=cv2.INTER_NEAREST,
|
| 123 |
).astype(bool)
|
| 124 |
if depth is None:
|
|
|
|
| 147 |
|
| 148 |
|
| 149 |
def estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int):
|
| 150 |
+
geometry = estimate_moge_geometry(img_np, target_h=height, target_w=width)
|
| 151 |
if geometry is not None:
|
| 152 |
return geometry
|
| 153 |
|
models/loader.py
CHANGED
|
@@ -129,6 +129,13 @@ def warm_start_models():
|
|
| 129 |
t_start = time.perf_counter()
|
| 130 |
print(f"Warm-starting visualizer models on {state.device} ...", flush=True)
|
| 131 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
_load_segmentation_model()
|
| 133 |
|
| 134 |
moge_loaded = False
|
|
|
|
| 129 |
t_start = time.perf_counter()
|
| 130 |
print(f"Warm-starting visualizer models on {state.device} ...", flush=True)
|
| 131 |
|
| 132 |
+
# Try ONNX sessions first
|
| 133 |
+
from config.runtime import ENABLE_ONNX_INFERENCE
|
| 134 |
+
if ENABLE_ONNX_INFERENCE:
|
| 135 |
+
from models.onnx_loader import load_seg_onnx_session, load_depth_onnx_session
|
| 136 |
+
load_seg_onnx_session()
|
| 137 |
+
load_depth_onnx_session()
|
| 138 |
+
|
| 139 |
_load_segmentation_model()
|
| 140 |
|
| 141 |
moge_loaded = False
|
models/onnx_loader.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ONNX Runtime model loading for accelerated inference."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import state
|
| 6 |
+
from config.runtime import ENABLE_ONNX_INFERENCE, ONNX_MODEL_DIR
|
| 7 |
+
|
| 8 |
+
ONNX_DIR = Path(ONNX_MODEL_DIR)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _ort_providers() -> list[str]:
|
| 12 |
+
"""Return available ONNX Runtime execution providers, preferring GPU."""
|
| 13 |
+
providers = []
|
| 14 |
+
if state.device.type == "cuda":
|
| 15 |
+
providers.append("CUDAExecutionProvider")
|
| 16 |
+
providers.append("CPUExecutionProvider")
|
| 17 |
+
return providers
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_seg_onnx_session():
|
| 21 |
+
"""Load the OneFormer ONNX session if available."""
|
| 22 |
+
if not ENABLE_ONNX_INFERENCE:
|
| 23 |
+
return None
|
| 24 |
+
if state.seg_onnx_session is not None:
|
| 25 |
+
return state.seg_onnx_session
|
| 26 |
+
|
| 27 |
+
model_path = ONNX_DIR / "oneformer_seg.onnx"
|
| 28 |
+
if not model_path.exists():
|
| 29 |
+
print(f"ONNX segmentation model not found at {model_path}, falling back to PyTorch.", flush=True)
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import onnxruntime as ort
|
| 34 |
+
sess_options = ort.SessionOptions()
|
| 35 |
+
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 36 |
+
state.seg_onnx_session = ort.InferenceSession(
|
| 37 |
+
str(model_path), sess_options, providers=_ort_providers(),
|
| 38 |
+
)
|
| 39 |
+
print(f"ONNX segmentation model loaded from {model_path}", flush=True)
|
| 40 |
+
return state.seg_onnx_session
|
| 41 |
+
except Exception as exc:
|
| 42 |
+
print(f"Failed to load ONNX segmentation model ({exc}), falling back to PyTorch.", flush=True)
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_depth_onnx_session():
|
| 47 |
+
"""Load the Depth-Anything ONNX session if available."""
|
| 48 |
+
if not ENABLE_ONNX_INFERENCE:
|
| 49 |
+
return None
|
| 50 |
+
if state.depth_onnx_session is not None:
|
| 51 |
+
return state.depth_onnx_session
|
| 52 |
+
|
| 53 |
+
model_path = ONNX_DIR / "depth_anything.onnx"
|
| 54 |
+
if not model_path.exists():
|
| 55 |
+
print(f"ONNX depth model not found at {model_path}, falling back to PyTorch.", flush=True)
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
import onnxruntime as ort
|
| 60 |
+
sess_options = ort.SessionOptions()
|
| 61 |
+
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 62 |
+
state.depth_onnx_session = ort.InferenceSession(
|
| 63 |
+
str(model_path), sess_options, providers=_ort_providers(),
|
| 64 |
+
)
|
| 65 |
+
print(f"ONNX depth model loaded from {model_path}", flush=True)
|
| 66 |
+
return state.depth_onnx_session
|
| 67 |
+
except Exception as exc:
|
| 68 |
+
print(f"Failed to load ONNX depth model ({exc}), falling back to PyTorch.", flush=True)
|
| 69 |
+
return None
|
models/segmentation.py
CHANGED
|
@@ -11,25 +11,74 @@ from config.models import (
|
|
| 11 |
MOGE_MODEL_NAME,
|
| 12 |
ONEFORMER_MODEL_NAME,
|
| 13 |
)
|
| 14 |
-
from config.runtime import ENABLE_INTRINSIC_SHADING
|
| 15 |
from models.loader import _load_segmentation_model
|
| 16 |
from enums import GeometryProvider
|
| 17 |
|
| 18 |
|
| 19 |
-
def
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
_load_segmentation_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
h, w = img_np.shape[:2]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
inputs = state.seg_processor(
|
| 24 |
images=img,
|
| 25 |
task_inputs=["semantic"],
|
| 26 |
return_tensors="pt",
|
| 27 |
).to(state.device)
|
|
|
|
| 28 |
with torch.no_grad():
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
result = state.seg_processor.post_process_semantic_segmentation(
|
| 31 |
outputs,
|
| 32 |
-
target_sizes=[(
|
| 33 |
)[0]
|
| 34 |
return result.cpu().numpy().astype(np.uint8)
|
| 35 |
|
|
|
|
| 11 |
MOGE_MODEL_NAME,
|
| 12 |
ONEFORMER_MODEL_NAME,
|
| 13 |
)
|
| 14 |
+
from config.runtime import ENABLE_INTRINSIC_SHADING, ENABLE_ONNX_INFERENCE
|
| 15 |
from models.loader import _load_segmentation_model
|
| 16 |
from enums import GeometryProvider
|
| 17 |
|
| 18 |
|
| 19 |
+
def _run_segmentation_onnx(img: Image.Image, img_np: np.ndarray, out_h: int, out_w: int) -> np.ndarray | None:
|
| 20 |
+
"""Try running segmentation via ONNX Runtime. Returns None if unavailable."""
|
| 21 |
+
if not ENABLE_ONNX_INFERENCE:
|
| 22 |
+
return None
|
| 23 |
+
from models.onnx_loader import load_seg_onnx_session
|
| 24 |
+
session = load_seg_onnx_session()
|
| 25 |
+
if session is None:
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
if state.seg_processor is None:
|
| 29 |
_load_segmentation_model()
|
| 30 |
+
|
| 31 |
+
inputs = state.seg_processor(images=img, task_inputs=["semantic"], return_tensors="np")
|
| 32 |
+
input_feed = {k: v for k, v in inputs.items() if k in [inp.name for inp in session.get_inputs()]}
|
| 33 |
+
outputs = session.run(None, input_feed)
|
| 34 |
+
|
| 35 |
+
# Post-process: outputs[1] is masks_queries_logits — take argmax over class queries
|
| 36 |
+
class_queries = torch.from_numpy(outputs[0])
|
| 37 |
+
mask_queries = torch.from_numpy(outputs[1])
|
| 38 |
+
|
| 39 |
+
# Replicate HuggingFace post-processing
|
| 40 |
+
masks = torch.nn.functional.interpolate(
|
| 41 |
+
mask_queries, size=(out_h, out_w), mode="bilinear", align_corners=False,
|
| 42 |
+
)
|
| 43 |
+
# masks shape: [batch, num_queries, H, W], class_queries: [batch, num_queries, num_classes+1]
|
| 44 |
+
seg_map = torch.einsum("bqc,bqhw->bchw", class_queries.softmax(-1)[..., :-1], masks.sigmoid())
|
| 45 |
+
seg_map = seg_map[0].argmax(0)
|
| 46 |
+
return seg_map.numpy().astype(np.uint8)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def run_segmentation(img: Image.Image, img_np: np.ndarray, target_h: int | None = None, target_w: int | None = None):
|
| 50 |
+
"""Run segmentation on the given image.
|
| 51 |
+
|
| 52 |
+
If target_h/target_w are provided, post-process outputs at that resolution
|
| 53 |
+
(used when inference runs on a downscaled image but masks are needed at original size).
|
| 54 |
+
"""
|
| 55 |
h, w = img_np.shape[:2]
|
| 56 |
+
out_h = target_h if target_h is not None else h
|
| 57 |
+
out_w = target_w if target_w is not None else w
|
| 58 |
+
|
| 59 |
+
# Try ONNX first
|
| 60 |
+
result = _run_segmentation_onnx(img, img_np, out_h, out_w)
|
| 61 |
+
if result is not None:
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
# Fallback to PyTorch
|
| 65 |
+
if state.seg_model is None:
|
| 66 |
+
_load_segmentation_model()
|
| 67 |
inputs = state.seg_processor(
|
| 68 |
images=img,
|
| 69 |
task_inputs=["semantic"],
|
| 70 |
return_tensors="pt",
|
| 71 |
).to(state.device)
|
| 72 |
+
use_autocast = state.device.type == "cuda"
|
| 73 |
with torch.no_grad():
|
| 74 |
+
if use_autocast:
|
| 75 |
+
with torch.autocast(device_type="cuda", dtype=torch.float16):
|
| 76 |
+
outputs = state.seg_model(**inputs)
|
| 77 |
+
else:
|
| 78 |
+
outputs = state.seg_model(**inputs)
|
| 79 |
result = state.seg_processor.post_process_semantic_segmentation(
|
| 80 |
outputs,
|
| 81 |
+
target_sizes=[(out_h, out_w)],
|
| 82 |
)[0]
|
| 83 |
return result.cpu().numpy().astype(np.uint8)
|
| 84 |
|
routes/viz2d.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
"""Viz2D conversion and job management routes."""
|
| 2 |
|
|
|
|
| 3 |
import time
|
| 4 |
import uuid
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
from pathlib import Path
|
| 7 |
|
| 8 |
-
from fastapi import APIRouter, BackgroundTasks, File, Response, UploadFile
|
| 9 |
|
| 10 |
from config.paths import JOB_DIR, UPLOAD_DIR
|
| 11 |
from config.runtime import CONVERSION_TARGET_MS, DEBUG_ARTIFACTS_ENABLED
|
|
@@ -71,6 +72,27 @@ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile =
|
|
| 71 |
return job
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
@router.get("/jobs/{job_id}")
|
| 75 |
async def viz2d_job_status(job_id: str):
|
| 76 |
return read_job(job_id)
|
|
@@ -110,15 +132,19 @@ async def viz2d_job_debug_asset(job_id: str, asset_name: str):
|
|
| 110 |
@router.get("/jobs/{job_id}/file")
|
| 111 |
async def viz2d_job_file(job_id: str):
|
| 112 |
job = read_job(job_id)
|
| 113 |
-
if job.get("status")
|
| 114 |
conflict("Job is not completed yet.")
|
| 115 |
binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle"
|
| 116 |
if not binary_bundle_path.exists():
|
| 117 |
not_found("Job output not found.")
|
|
|
|
| 118 |
return Response(
|
| 119 |
content=binary_bundle_path.read_bytes(),
|
| 120 |
media_type="application/zip",
|
| 121 |
-
headers={
|
|
|
|
|
|
|
|
|
|
| 122 |
)
|
| 123 |
|
| 124 |
|
|
|
|
| 1 |
"""Viz2D conversion and job management routes."""
|
| 2 |
|
| 3 |
+
import json
|
| 4 |
import time
|
| 5 |
import uuid
|
| 6 |
from datetime import datetime, timezone
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
+
from fastapi import APIRouter, BackgroundTasks, File, Query, Response, UploadFile
|
| 10 |
|
| 11 |
from config.paths import JOB_DIR, UPLOAD_DIR
|
| 12 |
from config.runtime import CONVERSION_TARGET_MS, DEBUG_ARTIFACTS_ENABLED
|
|
|
|
| 72 |
return job
|
| 73 |
|
| 74 |
|
| 75 |
+
@router.get("/jobs")
|
| 76 |
+
async def viz2d_list_jobs(
|
| 77 |
+
status: str | None = Query(None, description="Filter by status: COMPLETED, FAILED, PROCESSING"),
|
| 78 |
+
limit: int = Query(50, ge=1, le=200),
|
| 79 |
+
offset: int = Query(0, ge=0),
|
| 80 |
+
):
|
| 81 |
+
"""List all jobs, newest first."""
|
| 82 |
+
job_files = sorted(JOB_DIR.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
|
| 83 |
+
jobs = []
|
| 84 |
+
for path in job_files:
|
| 85 |
+
try:
|
| 86 |
+
job = json.loads(path.read_text())
|
| 87 |
+
except (json.JSONDecodeError, OSError):
|
| 88 |
+
continue
|
| 89 |
+
if status and job.get("status") != status:
|
| 90 |
+
continue
|
| 91 |
+
jobs.append(job)
|
| 92 |
+
total = len(jobs)
|
| 93 |
+
return {"total": total, "offset": offset, "limit": limit, "jobs": jobs[offset : offset + limit]}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
@router.get("/jobs/{job_id}")
|
| 97 |
async def viz2d_job_status(job_id: str):
|
| 98 |
return read_job(job_id)
|
|
|
|
| 132 |
@router.get("/jobs/{job_id}/file")
|
| 133 |
async def viz2d_job_file(job_id: str):
|
| 134 |
job = read_job(job_id)
|
| 135 |
+
if job.get("status") not in (JobStatus.COMPLETED, JobStatus.PREVIEW_READY):
|
| 136 |
conflict("Job is not completed yet.")
|
| 137 |
binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle"
|
| 138 |
if not binary_bundle_path.exists():
|
| 139 |
not_found("Job output not found.")
|
| 140 |
+
is_preview = job.get("status") == JobStatus.PREVIEW_READY
|
| 141 |
return Response(
|
| 142 |
content=binary_bundle_path.read_bytes(),
|
| 143 |
media_type="application/zip",
|
| 144 |
+
headers={
|
| 145 |
+
"Content-Disposition": 'attachment; filename="visualizer.vizbundle"',
|
| 146 |
+
"X-Bundle-Quality": "preview" if is_preview else "full",
|
| 147 |
+
},
|
| 148 |
)
|
| 149 |
|
| 150 |
|
scripts/export_onnx.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export PyTorch models to ONNX format for accelerated inference.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
python scripts/export_onnx.py --model seg # export segmentation model
|
| 5 |
+
python scripts/export_onnx.py --model depth # export depth model
|
| 6 |
+
python scripts/export_onnx.py --model all # export both
|
| 7 |
+
|
| 8 |
+
Models are saved to the onnx_models/ directory.
|
| 9 |
+
Set VISUALIZER_CONFIG env var to use the correct model names from your TOML config.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
# Add parent dir to path so we can import project modules
|
| 17 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from PIL import Image
|
| 22 |
+
|
| 23 |
+
ONNX_DIR = Path(__file__).resolve().parent.parent / "onnx_models"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def export_segmentation():
|
| 27 |
+
from config.models import ONEFORMER_MODEL_NAME
|
| 28 |
+
from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation
|
| 29 |
+
|
| 30 |
+
print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...")
|
| 31 |
+
processor = OneFormerProcessor.from_pretrained(ONEFORMER_MODEL_NAME)
|
| 32 |
+
model = OneFormerForUniversalSegmentation.from_pretrained(ONEFORMER_MODEL_NAME)
|
| 33 |
+
model.eval()
|
| 34 |
+
|
| 35 |
+
# Create dummy input (1024x1024 RGB)
|
| 36 |
+
dummy_image = Image.fromarray(np.random.randint(0, 255, (1024, 1024, 3), dtype=np.uint8))
|
| 37 |
+
inputs = processor(images=dummy_image, task_inputs=["semantic"], return_tensors="pt")
|
| 38 |
+
|
| 39 |
+
output_path = ONNX_DIR / "oneformer_seg.onnx"
|
| 40 |
+
ONNX_DIR.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
|
| 42 |
+
print(f"Exporting to {output_path} ...")
|
| 43 |
+
input_names = list(inputs.keys())
|
| 44 |
+
torch.onnx.export(
|
| 45 |
+
model,
|
| 46 |
+
tuple(inputs[k] for k in input_names),
|
| 47 |
+
str(output_path),
|
| 48 |
+
input_names=input_names,
|
| 49 |
+
output_names=["class_queries_logits", "masks_queries_logits"],
|
| 50 |
+
dynamic_axes={
|
| 51 |
+
name: {0: "batch", 2: "height", 3: "width"} if inputs[name].ndim == 4
|
| 52 |
+
else {0: "batch"} for name in input_names
|
| 53 |
+
},
|
| 54 |
+
opset_version=17,
|
| 55 |
+
do_constant_folding=True,
|
| 56 |
+
)
|
| 57 |
+
print(f"Segmentation model exported: {output_path} ({output_path.stat().st_size / 1e6:.1f} MB)")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def export_depth():
|
| 61 |
+
from config.models import DEPTH_MODEL_NAME
|
| 62 |
+
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
|
| 63 |
+
|
| 64 |
+
print(f"Loading Depth model: {DEPTH_MODEL_NAME} ...")
|
| 65 |
+
processor = AutoImageProcessor.from_pretrained(DEPTH_MODEL_NAME)
|
| 66 |
+
model = AutoModelForDepthEstimation.from_pretrained(DEPTH_MODEL_NAME)
|
| 67 |
+
model.eval()
|
| 68 |
+
|
| 69 |
+
# Create dummy input (1024x768 RGB)
|
| 70 |
+
dummy_image = Image.fromarray(np.random.randint(0, 255, (768, 1024, 3), dtype=np.uint8))
|
| 71 |
+
inputs = processor(images=dummy_image, return_tensors="pt")
|
| 72 |
+
|
| 73 |
+
output_path = ONNX_DIR / "depth_anything.onnx"
|
| 74 |
+
ONNX_DIR.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
|
| 76 |
+
print(f"Exporting to {output_path} ...")
|
| 77 |
+
input_names = list(inputs.keys())
|
| 78 |
+
torch.onnx.export(
|
| 79 |
+
model,
|
| 80 |
+
tuple(inputs[k] for k in input_names),
|
| 81 |
+
str(output_path),
|
| 82 |
+
input_names=input_names,
|
| 83 |
+
output_names=["predicted_depth"],
|
| 84 |
+
dynamic_axes={
|
| 85 |
+
name: {0: "batch", 2: "height", 3: "width"} if inputs[name].ndim == 4
|
| 86 |
+
else {0: "batch"} for name in input_names
|
| 87 |
+
},
|
| 88 |
+
opset_version=17,
|
| 89 |
+
do_constant_folding=True,
|
| 90 |
+
)
|
| 91 |
+
print(f"Depth model exported: {output_path} ({output_path.stat().st_size / 1e6:.1f} MB)")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
parser = argparse.ArgumentParser(description="Export models to ONNX")
|
| 96 |
+
parser.add_argument("--model", choices=["seg", "depth", "all"], required=True)
|
| 97 |
+
args = parser.parse_args()
|
| 98 |
+
|
| 99 |
+
if args.model in ("seg", "all"):
|
| 100 |
+
export_segmentation()
|
| 101 |
+
if args.model in ("depth", "all"):
|
| 102 |
+
export_depth()
|
| 103 |
+
|
| 104 |
+
print("\nDone! Enable ONNX inference by setting enable_onnx_inference = true in your TOML config.")
|
services/jobs/conversion.py
CHANGED
|
@@ -65,9 +65,13 @@ def weighted_conversion_progress(completed_phases: set[str], phase: str, phase_p
|
|
| 65 |
def run_conversion_task(job_id: str, upload_path: Path):
|
| 66 |
# Deferred imports to avoid circular dependencies with pipeline modules
|
| 67 |
from services.debug.capture import PipelineDebugCapture
|
|
|
|
| 68 |
|
| 69 |
debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
|
| 70 |
estimate_ms = estimate_conversion_ms()
|
|
|
|
|
|
|
|
|
|
| 71 |
try:
|
| 72 |
update_conversion_job(
|
| 73 |
job_id,
|
|
@@ -79,16 +83,49 @@ def run_conversion_task(job_id: str, upload_path: Path):
|
|
| 79 |
estimatedTotalMs=estimate_ms,
|
| 80 |
estimatedRemainingMs=estimate_ms,
|
| 81 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
with CONVERSION_GPU_LOCK:
|
| 83 |
t_start = time.perf_counter()
|
| 84 |
update_conversion_job(
|
| 85 |
job_id,
|
| 86 |
status=JobStatus.PROCESSING,
|
| 87 |
phase=PipelinePhase.SEGMENTATION,
|
| 88 |
-
progress=
|
| 89 |
phase_progress=0,
|
| 90 |
-
message="Analyzing floor\u2026",
|
| 91 |
-
startedAt=datetime.now(timezone.utc).isoformat(),
|
| 92 |
estimatedTotalMs=estimate_ms,
|
| 93 |
estimatedRemainingMs=estimate_ms,
|
| 94 |
)
|
|
@@ -99,27 +136,24 @@ def run_conversion_task(job_id: str, upload_path: Path):
|
|
| 99 |
completed_phases.add(phase)
|
| 100 |
elapsed_ms = (time.perf_counter() - t_start) * 1000
|
| 101 |
remaining_ms = max(0, estimate_ms - elapsed_ms)
|
|
|
|
|
|
|
|
|
|
| 102 |
update_conversion_job(
|
| 103 |
job_id,
|
| 104 |
phase=phase,
|
| 105 |
-
progress=
|
| 106 |
phase_progress=round(phase_progress),
|
| 107 |
-
message=f"
|
| 108 |
estimatedRemainingMs=round(remaining_ms),
|
| 109 |
)
|
| 110 |
|
| 111 |
-
# Deferred import to avoid circular dependencies
|
| 112 |
from services.pipeline.builder import build_segmentation_bundle
|
| 113 |
-
from services.pipeline.packaging import build_manifest_segmentation_bundle
|
| 114 |
|
| 115 |
-
image_bytes = upload_path.read_bytes()
|
| 116 |
bundle = build_segmentation_bundle(image_bytes, debug=debug, progress_callback=report_stage)
|
| 117 |
report_stage(PipelinePhase.PACKAGING, 25)
|
| 118 |
binary_bundle = build_manifest_segmentation_bundle(
|
| 119 |
-
bundle,
|
| 120 |
-
job_id,
|
| 121 |
-
image_url=f"/uploads/{upload_path.name}",
|
| 122 |
-
include_image=False,
|
| 123 |
)
|
| 124 |
(JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle)
|
| 125 |
report_stage(PipelinePhase.PACKAGING, 100)
|
|
@@ -136,9 +170,10 @@ def run_conversion_task(job_id: str, upload_path: Path):
|
|
| 136 |
job["durationMs"] = round(elapsed_ms)
|
| 137 |
job["modelName"] = bundle.get("modelName")
|
| 138 |
job["models"] = bundle.get("models")
|
|
|
|
| 139 |
job["outputFormat"] = "split-vizbundle"
|
| 140 |
write_job(job)
|
| 141 |
-
print(f"\n[JOB {job_id[:8]}]
|
| 142 |
except Exception as exc:
|
| 143 |
print(f"Background conversion failed: {exc}", flush=True)
|
| 144 |
if debug is not None:
|
|
|
|
| 65 |
def run_conversion_task(job_id: str, upload_path: Path):
|
| 66 |
# Deferred imports to avoid circular dependencies with pipeline modules
|
| 67 |
from services.debug.capture import PipelineDebugCapture
|
| 68 |
+
from services.pipeline.packaging import build_manifest_segmentation_bundle
|
| 69 |
|
| 70 |
debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
|
| 71 |
estimate_ms = estimate_conversion_ms()
|
| 72 |
+
image_bytes = upload_path.read_bytes()
|
| 73 |
+
image_url = f"/uploads/{upload_path.name}"
|
| 74 |
+
|
| 75 |
try:
|
| 76 |
update_conversion_job(
|
| 77 |
job_id,
|
|
|
|
| 83 |
estimatedTotalMs=estimate_ms,
|
| 84 |
estimatedRemainingMs=estimate_ms,
|
| 85 |
)
|
| 86 |
+
|
| 87 |
+
# ── Phase 1: Fast preview (outside GPU lock if possible) ──
|
| 88 |
+
try:
|
| 89 |
+
from services.pipeline.preview_builder import build_preview_bundle
|
| 90 |
+
|
| 91 |
+
t_preview = time.perf_counter()
|
| 92 |
+
update_conversion_job(
|
| 93 |
+
job_id,
|
| 94 |
+
status=JobStatus.PROCESSING,
|
| 95 |
+
phase=PipelinePhase.SEGMENTATION,
|
| 96 |
+
progress=0,
|
| 97 |
+
message="Quick preview\u2026",
|
| 98 |
+
startedAt=datetime.now(timezone.utc).isoformat(),
|
| 99 |
+
)
|
| 100 |
+
preview_bundle = build_preview_bundle(image_bytes)
|
| 101 |
+
preview_binary = build_manifest_segmentation_bundle(
|
| 102 |
+
preview_bundle, job_id, image_url=image_url, include_image=False,
|
| 103 |
+
)
|
| 104 |
+
(JOB_DIR / f"{job_id}.vizbundle").write_bytes(preview_binary)
|
| 105 |
+
|
| 106 |
+
preview_ms = (time.perf_counter() - t_preview) * 1000
|
| 107 |
+
job = read_job(job_id)
|
| 108 |
+
job["status"] = JobStatus.PREVIEW_READY
|
| 109 |
+
job["phase"] = "preview-ready"
|
| 110 |
+
job["progress"] = 40
|
| 111 |
+
job["message"] = "Preview ready \u2014 enhancing quality\u2026"
|
| 112 |
+
job["previewDurationMs"] = round(preview_ms)
|
| 113 |
+
job["outputFormat"] = "split-vizbundle"
|
| 114 |
+
write_job(job)
|
| 115 |
+
print(f"[JOB {job_id[:8]}] Preview ready in {preview_ms / 1000:.2f}s", flush=True)
|
| 116 |
+
except Exception as preview_exc:
|
| 117 |
+
print(f"[JOB {job_id[:8]}] Preview failed ({preview_exc}), continuing with full pipeline.", flush=True)
|
| 118 |
+
|
| 119 |
+
# ── Phase 2: Full HD pipeline ──
|
| 120 |
with CONVERSION_GPU_LOCK:
|
| 121 |
t_start = time.perf_counter()
|
| 122 |
update_conversion_job(
|
| 123 |
job_id,
|
| 124 |
status=JobStatus.PROCESSING,
|
| 125 |
phase=PipelinePhase.SEGMENTATION,
|
| 126 |
+
progress=40,
|
| 127 |
phase_progress=0,
|
| 128 |
+
message="Analyzing floor (HD)\u2026",
|
|
|
|
| 129 |
estimatedTotalMs=estimate_ms,
|
| 130 |
estimatedRemainingMs=estimate_ms,
|
| 131 |
)
|
|
|
|
| 136 |
completed_phases.add(phase)
|
| 137 |
elapsed_ms = (time.perf_counter() - t_start) * 1000
|
| 138 |
remaining_ms = max(0, estimate_ms - elapsed_ms)
|
| 139 |
+
base_progress = 40 # preview accounts for 0-40%
|
| 140 |
+
hd_progress = weighted_conversion_progress(completed_phases, phase, phase_progress)
|
| 141 |
+
overall = base_progress + round(hd_progress * 0.6) # HD is 40-100%
|
| 142 |
update_conversion_job(
|
| 143 |
job_id,
|
| 144 |
phase=phase,
|
| 145 |
+
progress=overall,
|
| 146 |
phase_progress=round(phase_progress),
|
| 147 |
+
message=f"Enhancing {phase.replace('-', ' ')}\u2026",
|
| 148 |
estimatedRemainingMs=round(remaining_ms),
|
| 149 |
)
|
| 150 |
|
|
|
|
| 151 |
from services.pipeline.builder import build_segmentation_bundle
|
|
|
|
| 152 |
|
|
|
|
| 153 |
bundle = build_segmentation_bundle(image_bytes, debug=debug, progress_callback=report_stage)
|
| 154 |
report_stage(PipelinePhase.PACKAGING, 25)
|
| 155 |
binary_bundle = build_manifest_segmentation_bundle(
|
| 156 |
+
bundle, job_id, image_url=image_url, include_image=False,
|
|
|
|
|
|
|
|
|
|
| 157 |
)
|
| 158 |
(JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle)
|
| 159 |
report_stage(PipelinePhase.PACKAGING, 100)
|
|
|
|
| 170 |
job["durationMs"] = round(elapsed_ms)
|
| 171 |
job["modelName"] = bundle.get("modelName")
|
| 172 |
job["models"] = bundle.get("models")
|
| 173 |
+
job["pipelineStages"] = bundle.get("pipelineStages")
|
| 174 |
job["outputFormat"] = "split-vizbundle"
|
| 175 |
write_job(job)
|
| 176 |
+
print(f"\n[JOB {job_id[:8]}] HD conversion completed in {elapsed_ms / 1000:.2f}s\n", flush=True)
|
| 177 |
except Exception as exc:
|
| 178 |
print(f"Background conversion failed: {exc}", flush=True)
|
| 179 |
if debug is not None:
|
services/lighting/reflection.py
CHANGED
|
@@ -93,7 +93,7 @@ def build_reflection_map(
|
|
| 93 |
if min(h, w) > 120:
|
| 94 |
sigma = max(0.6, min(h, w) / 520.0)
|
| 95 |
reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 96 |
-
reflection = np.clip(reflection, REFLECTION_MAP_MIN, min(REFLECTION_MAP_MAX, 0.
|
| 97 |
reflection[~reflection_surface] = 0.0
|
| 98 |
if float(np.max(np.abs(reflection[mask > 0]))) < 0.025:
|
| 99 |
return None
|
|
|
|
| 93 |
if min(h, w) > 120:
|
| 94 |
sigma = max(0.6, min(h, w) / 520.0)
|
| 95 |
reflection = cv2.GaussianBlur(reflection, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 96 |
+
reflection = np.clip(reflection, REFLECTION_MAP_MIN, min(REFLECTION_MAP_MAX, 0.20))
|
| 97 |
reflection[~reflection_surface] = 0.0
|
| 98 |
if float(np.max(np.abs(reflection[mask > 0]))) < 0.025:
|
| 99 |
return None
|
services/lighting/shading.py
CHANGED
|
@@ -41,12 +41,12 @@ def smooth_relative_lighting(relative_shading: np.ndarray, surface_mask: np.ndar
|
|
| 41 |
|
| 42 |
local_contrast = local / np.maximum(broad, 1e-4)
|
| 43 |
local_log = np.log(np.maximum(local_contrast, 1e-4))
|
| 44 |
-
local_log = np.clip(local_log, np.log(0.
|
| 45 |
-
combined = broad_relative * np.exp(local_log * 0.
|
| 46 |
normalized = normalize_relative_field(combined, surface_mask)
|
| 47 |
if normalized is None:
|
| 48 |
return None
|
| 49 |
-
normalized = np.clip(normalized, SHADE_MAP_MIN, 1.
|
| 50 |
normalized[surface_mask == 0] = 1.0
|
| 51 |
return normalized
|
| 52 |
|
|
@@ -91,7 +91,7 @@ def suppress_replaced_material_lighting(
|
|
| 91 |
sigma = max(8.0, min(surface_mask.shape[:2]) / 48.0)
|
| 92 |
extrapolated = masked_gaussian_blur(extrapolated, surface_mask, sigma)
|
| 93 |
output[replacement] = extrapolated[replacement]
|
| 94 |
-
output = np.clip(output, SHADE_MAP_MIN, 1.
|
| 95 |
output[surface_mask == 0] = 1.0
|
| 96 |
return output
|
| 97 |
|
|
@@ -187,6 +187,6 @@ def preserve_observed_lighting(
|
|
| 187 |
fused[highlight_pixels],
|
| 188 |
observed_relative[highlight_pixels],
|
| 189 |
)
|
| 190 |
-
fused = np.clip(fused, SHADE_MAP_MIN, 1.
|
| 191 |
fused[surface_mask == 0] = 1.0
|
| 192 |
return fused
|
|
|
|
| 41 |
|
| 42 |
local_contrast = local / np.maximum(broad, 1e-4)
|
| 43 |
local_log = np.log(np.maximum(local_contrast, 1e-4))
|
| 44 |
+
local_log = np.clip(local_log, np.log(0.50), np.log(1.08))
|
| 45 |
+
combined = broad_relative * np.exp(local_log * 0.35)
|
| 46 |
normalized = normalize_relative_field(combined, surface_mask)
|
| 47 |
if normalized is None:
|
| 48 |
return None
|
| 49 |
+
normalized = np.clip(normalized, SHADE_MAP_MIN, 1.08)
|
| 50 |
normalized[surface_mask == 0] = 1.0
|
| 51 |
return normalized
|
| 52 |
|
|
|
|
| 91 |
sigma = max(8.0, min(surface_mask.shape[:2]) / 48.0)
|
| 92 |
extrapolated = masked_gaussian_blur(extrapolated, surface_mask, sigma)
|
| 93 |
output[replacement] = extrapolated[replacement]
|
| 94 |
+
output = np.clip(output, SHADE_MAP_MIN, 1.08)
|
| 95 |
output[surface_mask == 0] = 1.0
|
| 96 |
return output
|
| 97 |
|
|
|
|
| 187 |
fused[highlight_pixels],
|
| 188 |
observed_relative[highlight_pixels],
|
| 189 |
)
|
| 190 |
+
fused = np.clip(fused, SHADE_MAP_MIN, 1.20)
|
| 191 |
fused[surface_mask == 0] = 1.0
|
| 192 |
return fused
|
services/pipeline/builder.py
CHANGED
|
@@ -17,7 +17,6 @@ from services.debug.capture import PipelineDebugCapture
|
|
| 17 |
from services.direction.analysis import floor_direction_geometry_inputs
|
| 18 |
from services.floor.edge_coverage import scaled_odd_kernel_size
|
| 19 |
from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
|
| 20 |
-
from services.floor.sam_refinement import refine_floor_mask_with_sam2
|
| 21 |
from services.floor.detection import estimate_floor_plane
|
| 22 |
from services.geometry.uv_mapping import build_surface_uv_mapping
|
| 23 |
from services.lighting.intrinsic import build_intrinsic_lighting_maps
|
|
@@ -25,6 +24,7 @@ from services.lighting.shading import build_luminance_lighting_maps, lighting_ma
|
|
| 25 |
from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask
|
| 26 |
from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment, build_wall_segment
|
| 27 |
from services.pipeline import debug_stages
|
|
|
|
| 28 |
from services.wall.components import wall_surface_components
|
| 29 |
from direction_finder import find_floor_direction
|
| 30 |
import state
|
|
@@ -59,28 +59,59 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 59 |
img_np = np.array(img)
|
| 60 |
h, w = img_np.shape[:2]
|
| 61 |
min_floor_area = max(1200, int(w * h * 0.015))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
el = (time.perf_counter() - t0) * 1000
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
| 64 |
if d:
|
| 65 |
debug_stages.record_source_image(d, img_np, w, h, min_floor_area, el)
|
| 66 |
|
| 67 |
-
# --- Segmentation ---
|
| 68 |
if progress_callback:
|
| 69 |
progress_callback(PipelinePhase.SEGMENTATION, 0)
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
el = (time.perf_counter() - t0) * 1000
|
| 73 |
-
_log_stage("Segmentation", t0)
|
| 74 |
if d:
|
| 75 |
debug_stages.record_segmentation(d, img_np, seg_map, state.segmentation_backend, w, h, el)
|
|
|
|
| 76 |
if progress_callback:
|
| 77 |
progress_callback(PipelinePhase.SEGMENTATION, 100)
|
|
|
|
| 78 |
|
| 79 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
if progress_callback:
|
| 81 |
progress_callback(PipelinePhase.MASKING, 0)
|
| 82 |
t0 = time.perf_counter()
|
| 83 |
-
pixels_b64 = encode_bundle_image_data_url(img_np)
|
| 84 |
raw_primary = seg_class_mask(seg_map, class_ids(PRIMARY_FLOOR_CLASSES))
|
| 85 |
floor_mask = clean_floor_mask(wall_subtract(raw_primary.copy(), seg_map, dilation=0))
|
| 86 |
floor_mask_source = FloorMaskSource.PRIMARY_FLOOR
|
|
@@ -89,7 +120,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 89 |
seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0))
|
| 90 |
floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK
|
| 91 |
cleaned = floor_mask.copy()
|
| 92 |
-
|
| 93 |
el = (time.perf_counter() - t0) * 1000
|
| 94 |
_log_stage("Floor Masking", t0, f"source={floor_mask_source}")
|
| 95 |
if d:
|
|
@@ -97,19 +128,6 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 97 |
if progress_callback:
|
| 98 |
progress_callback(PipelinePhase.MASKING, 100)
|
| 99 |
|
| 100 |
-
# --- Geometry ---
|
| 101 |
-
if progress_callback:
|
| 102 |
-
progress_callback(PipelinePhase.GEOMETRY, 0)
|
| 103 |
-
t0 = time.perf_counter()
|
| 104 |
-
geometry = estimate_scene_geometry(img, img_np, w, h)
|
| 105 |
-
depth = geometry.get("depth")
|
| 106 |
-
el = (time.perf_counter() - t0) * 1000
|
| 107 |
-
_log_stage("Geometry", t0, f"provider={geometry.get('provider')}")
|
| 108 |
-
if d:
|
| 109 |
-
debug_stages.record_geometry(d, depth, floor_mask, geometry, el)
|
| 110 |
-
if progress_callback:
|
| 111 |
-
progress_callback(PipelinePhase.GEOMETRY, 55)
|
| 112 |
-
|
| 113 |
t0 = time.perf_counter()
|
| 114 |
homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
|
| 115 |
el = (time.perf_counter() - t0) * 1000
|
|
@@ -176,6 +194,22 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 176 |
wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
|
| 177 |
wall_components, wall_protected_mask = (
|
| 178 |
wall_surface_components(seg_map, min_floor_area, geometry) if ENABLE_WALL_SEGMENTS else ([], np.zeros_like(wall_mask)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
if progress_callback:
|
| 180 |
progress_callback(PipelinePhase.LIGHTING, 100)
|
| 181 |
|
|
@@ -205,6 +239,15 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 205 |
if progress_callback:
|
| 206 |
progress_callback(PipelinePhase.DIRECTION, 100)
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
# --- Package segments ---
|
| 209 |
if progress_callback:
|
| 210 |
progress_callback(PipelinePhase.PACKAGING, 0)
|
|
@@ -224,7 +267,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 224 |
shade_statistics=shade_statistics, lighting_source=lighting_source,
|
| 225 |
intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
|
| 226 |
for wi, (_, cm) in enumerate(wall_components):
|
| 227 |
-
ws = build_wall_segment(
|
|
|
|
|
|
|
|
|
|
| 228 |
if ws:
|
| 229 |
segments.append(ws)
|
| 230 |
if not segments:
|
|
@@ -240,8 +286,19 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 240 |
|
| 241 |
if d:
|
| 242 |
d.complete(total_elapsed * 1000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
|
| 244 |
-
"modelName": models["segmentation"]["name"], "models": models
|
|
|
|
| 245 |
|
| 246 |
|
| 247 |
def _print_pipeline_summary(
|
|
|
|
| 17 |
from services.direction.analysis import floor_direction_geometry_inputs
|
| 18 |
from services.floor.edge_coverage import scaled_odd_kernel_size
|
| 19 |
from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
|
|
|
|
| 20 |
from services.floor.detection import estimate_floor_plane
|
| 21 |
from services.geometry.uv_mapping import build_surface_uv_mapping
|
| 22 |
from services.lighting.intrinsic import build_intrinsic_lighting_maps
|
|
|
|
| 24 |
from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask
|
| 25 |
from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment, build_wall_segment
|
| 26 |
from services.pipeline import debug_stages
|
| 27 |
+
from services.pipeline.inference_utils import downscale_for_inference
|
| 28 |
from services.wall.components import wall_surface_components
|
| 29 |
from direction_finder import find_floor_direction
|
| 30 |
import state
|
|
|
|
| 59 |
img_np = np.array(img)
|
| 60 |
h, w = img_np.shape[:2]
|
| 61 |
min_floor_area = max(1200, int(w * h * 0.015))
|
| 62 |
+
|
| 63 |
+
# Downscale for faster inference — masks/depth are output at full resolution
|
| 64 |
+
inf_img, inf_np, inf_scale = downscale_for_inference(img, img_np)
|
| 65 |
+
inf_h, inf_w = inf_np.shape[:2]
|
| 66 |
el = (time.perf_counter() - t0) * 1000
|
| 67 |
+
if inf_scale < 1.0:
|
| 68 |
+
_log_stage("Image Loading", t0, f"{w}x{h} (inference@{inf_w}x{inf_h})")
|
| 69 |
+
else:
|
| 70 |
+
_log_stage("Image Loading", t0, f"{w}x{h}")
|
| 71 |
if d:
|
| 72 |
debug_stages.record_source_image(d, img_np, w, h, min_floor_area, el)
|
| 73 |
|
| 74 |
+
# --- Segmentation + Geometry (parallel on CPU, sequential on single GPU) ---
|
| 75 |
if progress_callback:
|
| 76 |
progress_callback(PipelinePhase.SEGMENTATION, 0)
|
| 77 |
+
|
| 78 |
+
use_parallel = state.device.type == "cpu"
|
| 79 |
+
if use_parallel:
|
| 80 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 81 |
+
t0 = time.perf_counter()
|
| 82 |
+
with ThreadPoolExecutor(max_workers=2) as pool:
|
| 83 |
+
seg_future = pool.submit(run_segmentation, inf_img, inf_np, h, w)
|
| 84 |
+
geo_future = pool.submit(estimate_scene_geometry, inf_img, inf_np, w, h)
|
| 85 |
+
seg_map = seg_future.result()
|
| 86 |
+
geometry = geo_future.result()
|
| 87 |
+
t_seg_geo = time.perf_counter() - t0
|
| 88 |
+
_log_stage("Segmentation+Geometry (parallel)", t0)
|
| 89 |
+
else:
|
| 90 |
+
t0 = time.perf_counter()
|
| 91 |
+
seg_map = run_segmentation(inf_img, inf_np, target_h=h, target_w=w)
|
| 92 |
+
_log_stage("Segmentation", t0)
|
| 93 |
+
t0 = time.perf_counter()
|
| 94 |
+
geometry = estimate_scene_geometry(inf_img, inf_np, w, h)
|
| 95 |
+
_log_stage("Geometry", t0, f"provider={geometry.get('provider')}")
|
| 96 |
+
|
| 97 |
+
depth = geometry.get("depth")
|
| 98 |
el = (time.perf_counter() - t0) * 1000
|
|
|
|
| 99 |
if d:
|
| 100 |
debug_stages.record_segmentation(d, img_np, seg_map, state.segmentation_backend, w, h, el)
|
| 101 |
+
debug_stages.record_geometry(d, depth, None, geometry, el)
|
| 102 |
if progress_callback:
|
| 103 |
progress_callback(PipelinePhase.SEGMENTATION, 100)
|
| 104 |
+
progress_callback(PipelinePhase.GEOMETRY, 55)
|
| 105 |
|
| 106 |
+
# --- Encode room image in background (overlaps with masking + later stages) ---
|
| 107 |
+
from concurrent.futures import ThreadPoolExecutor as _TP
|
| 108 |
+
_img_pool = _TP(max_workers=1)
|
| 109 |
+
_pixels_b64_future = _img_pool.submit(encode_bundle_image_data_url, img_np)
|
| 110 |
+
|
| 111 |
+
# --- Floor masking (SAM2 removed — morphological cleanup only) ---
|
| 112 |
if progress_callback:
|
| 113 |
progress_callback(PipelinePhase.MASKING, 0)
|
| 114 |
t0 = time.perf_counter()
|
|
|
|
| 115 |
raw_primary = seg_class_mask(seg_map, class_ids(PRIMARY_FLOOR_CLASSES))
|
| 116 |
floor_mask = clean_floor_mask(wall_subtract(raw_primary.copy(), seg_map, dilation=0))
|
| 117 |
floor_mask_source = FloorMaskSource.PRIMARY_FLOOR
|
|
|
|
| 120 |
seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0))
|
| 121 |
floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK
|
| 122 |
cleaned = floor_mask.copy()
|
| 123 |
+
sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "removed"}
|
| 124 |
el = (time.perf_counter() - t0) * 1000
|
| 125 |
_log_stage("Floor Masking", t0, f"source={floor_mask_source}")
|
| 126 |
if d:
|
|
|
|
| 128 |
if progress_callback:
|
| 129 |
progress_callback(PipelinePhase.MASKING, 100)
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
t0 = time.perf_counter()
|
| 132 |
homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
|
| 133 |
el = (time.perf_counter() - t0) * 1000
|
|
|
|
| 194 |
wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
|
| 195 |
wall_components, wall_protected_mask = (
|
| 196 |
wall_surface_components(seg_map, min_floor_area, geometry) if ENABLE_WALL_SEGMENTS else ([], np.zeros_like(wall_mask)))
|
| 197 |
+
|
| 198 |
+
# --- Pre-compute wall lighting in parallel with floor direction ---
|
| 199 |
+
# Wall lighting was previously computed inside build_wall_segment (in the
|
| 200 |
+
# "Packaging" phase), adding ~5s for large images. Moving it here lets it
|
| 201 |
+
# overlap with floor-direction detection.
|
| 202 |
+
from concurrent.futures import ThreadPoolExecutor, Future
|
| 203 |
+
|
| 204 |
+
def _compute_wall_lighting(component_mask):
|
| 205 |
+
return build_luminance_lighting_maps(img_np, component_mask)
|
| 206 |
+
|
| 207 |
+
wall_lighting_futures: list[Future] = []
|
| 208 |
+
wall_executor = ThreadPoolExecutor(max_workers=max(1, len(wall_components))) if wall_components else None
|
| 209 |
+
if wall_executor:
|
| 210 |
+
for _, cm in wall_components:
|
| 211 |
+
wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))
|
| 212 |
+
|
| 213 |
if progress_callback:
|
| 214 |
progress_callback(PipelinePhase.LIGHTING, 100)
|
| 215 |
|
|
|
|
| 239 |
if progress_callback:
|
| 240 |
progress_callback(PipelinePhase.DIRECTION, 100)
|
| 241 |
|
| 242 |
+
# Collect pre-computed wall lighting results
|
| 243 |
+
wall_lighting_results: list[dict | None] = []
|
| 244 |
+
if wall_executor:
|
| 245 |
+
for fut in wall_lighting_futures:
|
| 246 |
+
wall_lighting_results.append(fut.result())
|
| 247 |
+
wall_executor.shutdown(wait=False)
|
| 248 |
+
else:
|
| 249 |
+
wall_lighting_results = [None] * len(wall_components)
|
| 250 |
+
|
| 251 |
# --- Package segments ---
|
| 252 |
if progress_callback:
|
| 253 |
progress_callback(PipelinePhase.PACKAGING, 0)
|
|
|
|
| 267 |
shade_statistics=shade_statistics, lighting_source=lighting_source,
|
| 268 |
intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
|
| 269 |
for wi, (_, cm) in enumerate(wall_components):
|
| 270 |
+
ws = build_wall_segment(
|
| 271 |
+
wi, cm, wall_protected_mask, geometry, img_np, wall_components, models,
|
| 272 |
+
precomputed_lighting=wall_lighting_results[wi] if wi < len(wall_lighting_results) else None,
|
| 273 |
+
)
|
| 274 |
if ws:
|
| 275 |
segments.append(ws)
|
| 276 |
if not segments:
|
|
|
|
| 286 |
|
| 287 |
if d:
|
| 288 |
d.complete(total_elapsed * 1000)
|
| 289 |
+
pixels_b64 = _pixels_b64_future.result()
|
| 290 |
+
_img_pool.shutdown(wait=False)
|
| 291 |
+
pipeline_stages = [
|
| 292 |
+
{"name": name, "elapsed_s": round(elapsed, 3), "detail": detail}
|
| 293 |
+
for name, elapsed, detail in stage_times
|
| 294 |
+
]
|
| 295 |
+
pipeline_stages.append({
|
| 296 |
+
"name": "TOTAL", "elapsed_s": round(total_elapsed, 3), "detail": f"{w}x{h}",
|
| 297 |
+
})
|
| 298 |
+
|
| 299 |
return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
|
| 300 |
+
"modelName": models["segmentation"]["name"], "models": models,
|
| 301 |
+
"pipelineStages": pipeline_stages}
|
| 302 |
|
| 303 |
|
| 304 |
def _print_pipeline_summary(
|
services/pipeline/bundle_assembly.py
CHANGED
|
@@ -62,18 +62,20 @@ def build_floor_segment(
|
|
| 62 |
"homography": homography,
|
| 63 |
"floorTransform": plane.get("floorTransform") if plane else None,
|
| 64 |
"plane": plane,
|
|
|
|
|
|
|
| 65 |
"surfaceUv": (
|
| 66 |
-
|
| 67 |
if use_surface_uv else None
|
| 68 |
),
|
| 69 |
"surfacePlaneIds": (
|
| 70 |
-
|
| 71 |
if use_surface_uv else None
|
| 72 |
),
|
| 73 |
"surfacePlanes": surface_mapping["planes"] if surface_mapping is not None else None,
|
| 74 |
-
"shadeMap":
|
| 75 |
-
"showroomShadeMap":
|
| 76 |
-
"reflectionMap":
|
| 77 |
"metadata": {
|
| 78 |
"segmenter": segmenter_metadata_name(),
|
| 79 |
"segmentationModel": models["segmentation"]["name"],
|
|
@@ -132,11 +134,12 @@ def build_wall_segment(
|
|
| 132 |
img_np: np.ndarray,
|
| 133 |
wall_components: list,
|
| 134 |
models: dict,
|
|
|
|
| 135 |
) -> dict | None:
|
| 136 |
wall_homography, wall_plane = estimate_wall_plane(component_mask, geometry)
|
| 137 |
if wall_homography is None or wall_plane is None:
|
| 138 |
return None
|
| 139 |
-
wall_lighting_maps = build_luminance_lighting_maps(img_np, component_mask)
|
| 140 |
wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
|
| 141 |
wall_occlusion_indices = np.flatnonzero(wall_protected_mask.ravel()).astype(np.uint32)
|
| 142 |
wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
|
|
@@ -155,9 +158,9 @@ def build_wall_segment(
|
|
| 155 |
"surfaceUv": None,
|
| 156 |
"surfacePlaneIds": None,
|
| 157 |
"surfacePlanes": None,
|
| 158 |
-
"shadeMap":
|
| 159 |
-
"showroomShadeMap":
|
| 160 |
-
"reflectionMap":
|
| 161 |
"metadata": {
|
| 162 |
"segmenter": segmenter_metadata_name(),
|
| 163 |
"segmentationModel": models["segmentation"]["name"],
|
|
|
|
| 62 |
"homography": homography,
|
| 63 |
"floorTransform": plane.get("floorTransform") if plane else None,
|
| 64 |
"plane": plane,
|
| 65 |
+
# Pass raw numpy arrays for lazy assets — packaging writes them directly
|
| 66 |
+
# to disk, avoiding the costly base64 encode/decode round-trip.
|
| 67 |
"surfaceUv": (
|
| 68 |
+
surface_mapping["uv"].astype(np.float32)
|
| 69 |
if use_surface_uv else None
|
| 70 |
),
|
| 71 |
"surfacePlaneIds": (
|
| 72 |
+
surface_mapping["planeIds"].astype(np.uint8)
|
| 73 |
if use_surface_uv else None
|
| 74 |
),
|
| 75 |
"surfacePlanes": surface_mapping["planes"] if surface_mapping is not None else None,
|
| 76 |
+
"shadeMap": shade_map,
|
| 77 |
+
"showroomShadeMap": showroom_shade_map,
|
| 78 |
+
"reflectionMap": reflection_map,
|
| 79 |
"metadata": {
|
| 80 |
"segmenter": segmenter_metadata_name(),
|
| 81 |
"segmentationModel": models["segmentation"]["name"],
|
|
|
|
| 134 |
img_np: np.ndarray,
|
| 135 |
wall_components: list,
|
| 136 |
models: dict,
|
| 137 |
+
precomputed_lighting: dict | None = None,
|
| 138 |
) -> dict | None:
|
| 139 |
wall_homography, wall_plane = estimate_wall_plane(component_mask, geometry)
|
| 140 |
if wall_homography is None or wall_plane is None:
|
| 141 |
return None
|
| 142 |
+
wall_lighting_maps = precomputed_lighting if precomputed_lighting is not None else build_luminance_lighting_maps(img_np, component_mask)
|
| 143 |
wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
|
| 144 |
wall_occlusion_indices = np.flatnonzero(wall_protected_mask.ravel()).astype(np.uint32)
|
| 145 |
wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
|
|
|
|
| 158 |
"surfaceUv": None,
|
| 159 |
"surfacePlaneIds": None,
|
| 160 |
"surfacePlanes": None,
|
| 161 |
+
"shadeMap": wall_shade_map,
|
| 162 |
+
"showroomShadeMap": wall_showroom,
|
| 163 |
+
"reflectionMap": wall_reflection,
|
| 164 |
"metadata": {
|
| 165 |
"segmenter": segmenter_metadata_name(),
|
| 166 |
"segmentationModel": models["segmentation"]["name"],
|
services/pipeline/inference_utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helpers for downscaling images before inference and upscaling results back."""
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
from config.runtime import INFERENCE_MAX_DIMENSION
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def downscale_for_inference(
|
| 11 |
+
img: Image.Image,
|
| 12 |
+
img_np: np.ndarray,
|
| 13 |
+
) -> tuple[Image.Image, np.ndarray, float]:
|
| 14 |
+
"""Downscale image to INFERENCE_MAX_DIMENSION for model inference.
|
| 15 |
+
|
| 16 |
+
Returns (resized_pil, resized_np, scale_factor).
|
| 17 |
+
scale_factor is 1.0 if no resizing was needed.
|
| 18 |
+
"""
|
| 19 |
+
h, w = img_np.shape[:2]
|
| 20 |
+
largest = max(h, w)
|
| 21 |
+
if largest <= INFERENCE_MAX_DIMENSION:
|
| 22 |
+
return img, img_np, 1.0
|
| 23 |
+
|
| 24 |
+
scale = INFERENCE_MAX_DIMENSION / float(largest)
|
| 25 |
+
new_w = max(1, int(round(w * scale)))
|
| 26 |
+
new_h = max(1, int(round(h * scale)))
|
| 27 |
+
|
| 28 |
+
resized_pil = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
| 29 |
+
resized_np = np.array(resized_pil)
|
| 30 |
+
return resized_pil, resized_np, scale
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def upscale_mask(mask: np.ndarray, target_h: int, target_w: int) -> np.ndarray:
|
| 34 |
+
"""Upscale a segmentation mask back to original resolution using nearest-neighbor."""
|
| 35 |
+
if mask.shape[0] == target_h and mask.shape[1] == target_w:
|
| 36 |
+
return mask
|
| 37 |
+
return cv2.resize(mask, (target_w, target_h), interpolation=cv2.INTER_NEAREST)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def upscale_depth(depth: np.ndarray, target_h: int, target_w: int) -> np.ndarray:
|
| 41 |
+
"""Upscale a depth map back to original resolution using bicubic interpolation."""
|
| 42 |
+
if depth.shape[0] == target_h and depth.shape[1] == target_w:
|
| 43 |
+
return depth
|
| 44 |
+
return cv2.resize(depth, (target_w, target_h), interpolation=cv2.INTER_CUBIC)
|
services/pipeline/packaging.py
CHANGED
|
@@ -172,9 +172,15 @@ def build_manifest_segmentation_bundle(
|
|
| 172 |
)
|
| 173 |
for field, (filename, dtype) in lazy_asset_fields.items():
|
| 174 |
value = segment.get(field)
|
| 175 |
-
if
|
| 176 |
continue
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
asset_name = f"s{segment_index}-{filename}"
|
| 179 |
(asset_dir / asset_name).write_bytes(data)
|
| 180 |
segment_metadata[field] = {
|
|
|
|
| 172 |
)
|
| 173 |
for field, (filename, dtype) in lazy_asset_fields.items():
|
| 174 |
value = segment.get(field)
|
| 175 |
+
if value is None:
|
| 176 |
continue
|
| 177 |
+
# Accept both raw numpy arrays and base64-encoded strings
|
| 178 |
+
if isinstance(value, np.ndarray):
|
| 179 |
+
data = value.tobytes()
|
| 180 |
+
elif isinstance(value, str):
|
| 181 |
+
data = base64.b64decode(value)
|
| 182 |
+
else:
|
| 183 |
+
data = bytes(value)
|
| 184 |
asset_name = f"s{segment_index}-{filename}"
|
| 185 |
(asset_dir / asset_name).write_bytes(data)
|
| 186 |
segment_metadata[field] = {
|
services/pipeline/preview_builder.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fast preview pipeline — ~3s segmentation-only bundle for immediate user interaction.
|
| 2 |
+
|
| 3 |
+
Runs segmentation at 512px, skips depth/UV/intrinsic lighting, and uses basic
|
| 4 |
+
luminance shading. Returns a minimal vizbundle that the frontend can render
|
| 5 |
+
while the full HD pipeline runs in the background.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import io
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
import cv2
|
| 14 |
+
import numpy as np
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
from models.segmentation import run_segmentation
|
| 18 |
+
from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
|
| 19 |
+
from services.floor.detection import estimate_floor_plane
|
| 20 |
+
from services.lighting.shading import build_luminance_lighting_maps, lighting_map_statistics
|
| 21 |
+
from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask
|
| 22 |
+
from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment
|
| 23 |
+
from services.pipeline.inference_utils import downscale_for_inference
|
| 24 |
+
from direction_finder import find_floor_direction
|
| 25 |
+
import state
|
| 26 |
+
from state import FLOOR_SURFACE_CLASSES, PRIMARY_FLOOR_CLASSES, REPLACEABLE_SOFT_FLOOR_CLASSES, class_ids
|
| 27 |
+
from enums import FloorMaskSource, GeometryProvider
|
| 28 |
+
from utils import mask_to_indices, seg_class_mask
|
| 29 |
+
|
| 30 |
+
PREVIEW_MAX_DIM = 512
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _downscale_to(img: Image.Image, img_np: np.ndarray, max_dim: int):
|
| 34 |
+
"""Downscale for preview inference at a fixed small size."""
|
| 35 |
+
h, w = img_np.shape[:2]
|
| 36 |
+
largest = max(h, w)
|
| 37 |
+
if largest <= max_dim:
|
| 38 |
+
return img, img_np, 1.0
|
| 39 |
+
scale = max_dim / float(largest)
|
| 40 |
+
new_w = max(1, int(round(w * scale)))
|
| 41 |
+
new_h = max(1, int(round(h * scale)))
|
| 42 |
+
resized_pil = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
| 43 |
+
resized_np = np.array(resized_pil)
|
| 44 |
+
return resized_pil, resized_np, scale
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def build_preview_bundle(contents: bytes) -> dict:
|
| 48 |
+
"""Build a fast preview bundle (seg + basic shading, no depth/UV)."""
|
| 49 |
+
t_start = time.perf_counter()
|
| 50 |
+
|
| 51 |
+
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 52 |
+
img_np = np.array(img)
|
| 53 |
+
h, w = img_np.shape[:2]
|
| 54 |
+
min_floor_area = max(1200, int(w * h * 0.015))
|
| 55 |
+
|
| 56 |
+
# Downscale aggressively for speed
|
| 57 |
+
inf_img, inf_np, _ = _downscale_to(img, img_np, PREVIEW_MAX_DIM)
|
| 58 |
+
|
| 59 |
+
# Segmentation at 512px, output at full res
|
| 60 |
+
seg_map = run_segmentation(inf_img, inf_np, target_h=h, target_w=w)
|
| 61 |
+
|
| 62 |
+
# Floor masking (no SAM2)
|
| 63 |
+
pixels_b64 = encode_bundle_image_data_url(img_np)
|
| 64 |
+
raw_primary = seg_class_mask(seg_map, class_ids(PRIMARY_FLOOR_CLASSES))
|
| 65 |
+
floor_mask = clean_floor_mask(wall_subtract(raw_primary.copy(), seg_map, dilation=0))
|
| 66 |
+
floor_mask_source = FloorMaskSource.PRIMARY_FLOOR
|
| 67 |
+
if int(floor_mask.sum()) < min_floor_area:
|
| 68 |
+
floor_mask = clean_floor_mask(wall_subtract(
|
| 69 |
+
seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0))
|
| 70 |
+
floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK
|
| 71 |
+
|
| 72 |
+
# Homography-only plane (no depth)
|
| 73 |
+
geometry = {
|
| 74 |
+
"provider": GeometryProvider.HOMOGRAPHY,
|
| 75 |
+
"points": None, "depth": None, "normals": None,
|
| 76 |
+
"validMask": None, "intrinsics": None,
|
| 77 |
+
}
|
| 78 |
+
homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
|
| 79 |
+
|
| 80 |
+
# Surface mask
|
| 81 |
+
quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
|
| 82 |
+
surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, None, geometry, plane)
|
| 83 |
+
replaced_material_mask = (seg_class_mask(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES)).astype(bool) & (surface_mask > 0)).astype(np.uint8)
|
| 84 |
+
surface_indices = mask_to_indices(surface_mask)
|
| 85 |
+
occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
|
| 86 |
+
occlusion_indices = mask_to_indices(occlusion_mask)
|
| 87 |
+
|
| 88 |
+
# Basic luminance shading (fast, CPU-only)
|
| 89 |
+
lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
|
| 90 |
+
shade_map = lighting_maps.get("shadeMap") if lighting_maps else None
|
| 91 |
+
showroom_shade_map = lighting_maps.get("showroomShadeMap") if lighting_maps else None
|
| 92 |
+
reflection_map = lighting_maps.get("reflectionMap") if lighting_maps else None
|
| 93 |
+
shade_statistics = lighting_map_statistics(shade_map, surface_mask)
|
| 94 |
+
|
| 95 |
+
# Minimal floor direction
|
| 96 |
+
wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
|
| 97 |
+
struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}))
|
| 98 |
+
floor_direction = find_floor_direction(
|
| 99 |
+
img_np, surface_mask, wall_mask=wall_mask,
|
| 100 |
+
structure_mask=struct_mask,
|
| 101 |
+
normals_map=None, geometry_valid_mask=None,
|
| 102 |
+
intrinsics=None, floor_normal=None,
|
| 103 |
+
render_u_axis=None, render_v_axis=None,
|
| 104 |
+
render_transform=homography,
|
| 105 |
+
surface_uv=None, surface_indices=None, surface_plane_ids=None,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# Package
|
| 109 |
+
sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "preview"}
|
| 110 |
+
mapping_metadata = {"surfaceUvEnabled": False, "textureMappingMode": "regularized-floor-plane"}
|
| 111 |
+
models = {
|
| 112 |
+
"segmentation": {"backend": state.segmentation_backend, "name": "oneformer-preview"},
|
| 113 |
+
"geometry": {"provider": GeometryProvider.HOMOGRAPHY, "name": None},
|
| 114 |
+
"depth": {"enabled": False, "name": None},
|
| 115 |
+
"intrinsic": {"enabled": False, "name": None},
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
segments = []
|
| 119 |
+
if len(surface_indices) >= min_floor_area:
|
| 120 |
+
segments.append(build_floor_segment(
|
| 121 |
+
surface_indices=surface_indices, occlusion_indices=occlusion_indices,
|
| 122 |
+
homography=homography, plane=plane, surface_mapping=None,
|
| 123 |
+
use_surface_uv=False, shade_map=shade_map,
|
| 124 |
+
showroom_shade_map=showroom_shade_map, reflection_map=reflection_map,
|
| 125 |
+
floor_mask=floor_mask, surface_mask=surface_mask,
|
| 126 |
+
replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask,
|
| 127 |
+
floor_direction=floor_direction, sam_metadata=sam_metadata,
|
| 128 |
+
edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
|
| 129 |
+
shade_statistics=shade_statistics, lighting_source="luminance",
|
| 130 |
+
intrinsic_lighting_used=False, models=models, depth=None, geometry=geometry))
|
| 131 |
+
if not segments:
|
| 132 |
+
segments = build_fallback_segments(seg_map, None, models)
|
| 133 |
+
|
| 134 |
+
total_elapsed = time.perf_counter() - t_start
|
| 135 |
+
print(f"[PREVIEW] Built in {total_elapsed:.2f}s ({w}x{h}, inference@{PREVIEW_MAX_DIM}px)", flush=True)
|
| 136 |
+
|
| 137 |
+
return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
|
| 138 |
+
"modelName": models["segmentation"]["name"], "models": models,
|
| 139 |
+
"isPreview": True}
|
state.py
CHANGED
|
@@ -15,6 +15,10 @@ moge_model = None
|
|
| 15 |
sam2_predictor = None
|
| 16 |
intrinsic_models = None
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
ADE20K_CLASSES = [
|
| 19 |
"wall", "building", "sky", "floor", "tree", "ceiling", "road", "bed",
|
| 20 |
"window", "grass", "cabinet", "sidewalk", "person", "ground", "door",
|
|
|
|
| 15 |
sam2_predictor = None
|
| 16 |
intrinsic_models = None
|
| 17 |
|
| 18 |
+
# ONNX Runtime sessions (populated lazily by models/onnx_loader.py)
|
| 19 |
+
seg_onnx_session = None
|
| 20 |
+
depth_onnx_session = None
|
| 21 |
+
|
| 22 |
ADE20K_CLASSES = [
|
| 23 |
"wall", "building", "sky", "floor", "tree", "ceiling", "road", "bed",
|
| 24 |
"window", "grass", "cabinet", "sidewalk", "person", "ground", "door",
|
visualizer.gpu.toml
CHANGED
|
@@ -24,6 +24,7 @@ enable_sam_refinement = false
|
|
| 24 |
enable_floor_mask_cleanup = false
|
| 25 |
warm_start_models = true
|
| 26 |
debug_artifacts_enabled = false
|
|
|
|
| 27 |
conversion_target_ms = 30000
|
| 28 |
bundle_image_format = "jpeg"
|
| 29 |
bundle_image_quality = 92
|
|
|
|
| 24 |
enable_floor_mask_cleanup = false
|
| 25 |
warm_start_models = true
|
| 26 |
debug_artifacts_enabled = false
|
| 27 |
+
inference_max_dimension = 1024
|
| 28 |
conversion_target_ms = 30000
|
| 29 |
bundle_image_format = "jpeg"
|
| 30 |
bundle_image_quality = 92
|
visualizer.hf.toml
CHANGED
|
@@ -20,8 +20,9 @@ enable_multi_plane_surfaces = true
|
|
| 20 |
enable_wall_segments = true
|
| 21 |
enable_intrinsic_shading = true
|
| 22 |
enable_shading_transfer = true
|
| 23 |
-
enable_sam_refinement =
|
| 24 |
debug_artifacts_enabled = false
|
|
|
|
| 25 |
conversion_target_ms = 30000
|
| 26 |
data_dir = "data"
|
| 27 |
|
|
|
|
| 20 |
enable_wall_segments = true
|
| 21 |
enable_intrinsic_shading = true
|
| 22 |
enable_shading_transfer = true
|
| 23 |
+
enable_sam_refinement = false
|
| 24 |
debug_artifacts_enabled = false
|
| 25 |
+
inference_max_dimension = 1024
|
| 26 |
conversion_target_ms = 30000
|
| 27 |
data_dir = "data"
|
| 28 |
|
visualizer.local.toml
CHANGED
|
@@ -18,6 +18,7 @@ enable_intrinsic_shading = false
|
|
| 18 |
enable_shading_transfer = true
|
| 19 |
enable_sam_refinement = false
|
| 20 |
warm_start_models = true
|
|
|
|
| 21 |
bundle_image_format = "jpeg"
|
| 22 |
bundle_image_quality = 92
|
| 23 |
data_dir = "data"
|
|
|
|
| 18 |
enable_shading_transfer = true
|
| 19 |
enable_sam_refinement = false
|
| 20 |
warm_start_models = true
|
| 21 |
+
inference_max_dimension = 1024
|
| 22 |
bundle_image_format = "jpeg"
|
| 23 |
bundle_image_quality = 92
|
| 24 |
data_dir = "data"
|