Spaces:
Paused
Paused
github-actions[bot] commited on
Commit ·
b267904
1
Parent(s): 3e7c41b
Automated Deploy: d0d19f6f197e1cd3365a1722cd51ab754638c1b1
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 +20 -2
- scripts/export_onnx.py +104 -0
- services/jobs/conversion.py +47 -13
- services/lighting/intrinsic.py +0 -2
- services/lighting/reflection.py +1 -1
- services/lighting/shading.py +5 -58
- services/pipeline/builder.py +85 -31
- services/pipeline/bundle_assembly.py +1 -3
- services/pipeline/inference_utils.py +44 -0
- services/pipeline/preview_builder.py +130 -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,5 +1,6 @@
|
|
| 1 |
"""Viz2D conversion and job management routes."""
|
| 2 |
|
|
|
|
| 3 |
import uuid
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
from pathlib import Path
|
|
@@ -21,13 +22,19 @@ router = APIRouter(prefix="/viz2d", tags=["viz2d"])
|
|
| 21 |
|
| 22 |
@router.post("/convert")
|
| 23 |
async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
|
|
|
|
|
|
|
| 24 |
if file.content_type and not file.content_type.startswith("image/"):
|
| 25 |
bad_request("Upload must be a JPG or PNG image.")
|
| 26 |
|
| 27 |
contents = await file.read()
|
| 28 |
if not contents:
|
| 29 |
bad_request("Upload must not be empty.")
|
|
|
|
|
|
|
|
|
|
| 30 |
normalized_contents = normalize_room_upload(contents)
|
|
|
|
| 31 |
|
| 32 |
job_id = uuid.uuid4().hex
|
| 33 |
original_filename = file.filename
|
|
@@ -36,6 +43,13 @@ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile =
|
|
| 36 |
upload_path = UPLOAD_DIR / f"{job_id}{ext}"
|
| 37 |
upload_path.write_bytes(normalized_contents)
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
job = {
|
| 40 |
"id": job_id,
|
| 41 |
"status": JobStatus.QUEUED,
|
|
@@ -96,15 +110,19 @@ async def viz2d_job_debug_asset(job_id: str, asset_name: str):
|
|
| 96 |
@router.get("/jobs/{job_id}/file")
|
| 97 |
async def viz2d_job_file(job_id: str):
|
| 98 |
job = read_job(job_id)
|
| 99 |
-
if job.get("status")
|
| 100 |
conflict("Job is not completed yet.")
|
| 101 |
binary_bundle_path = JOB_DIR / f"{job_id}.vizbundle"
|
| 102 |
if not binary_bundle_path.exists():
|
| 103 |
not_found("Job output not found.")
|
|
|
|
| 104 |
return Response(
|
| 105 |
content=binary_bundle_path.read_bytes(),
|
| 106 |
media_type="application/zip",
|
| 107 |
-
headers={
|
|
|
|
|
|
|
|
|
|
| 108 |
)
|
| 109 |
|
| 110 |
|
|
|
|
| 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
|
|
|
|
| 22 |
|
| 23 |
@router.post("/convert")
|
| 24 |
async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
|
| 25 |
+
t_upload_start = time.perf_counter()
|
| 26 |
+
|
| 27 |
if file.content_type and not file.content_type.startswith("image/"):
|
| 28 |
bad_request("Upload must be a JPG or PNG image.")
|
| 29 |
|
| 30 |
contents = await file.read()
|
| 31 |
if not contents:
|
| 32 |
bad_request("Upload must not be empty.")
|
| 33 |
+
t_read = time.perf_counter() - t_upload_start
|
| 34 |
+
|
| 35 |
+
t0 = time.perf_counter()
|
| 36 |
normalized_contents = normalize_room_upload(contents)
|
| 37 |
+
t_normalize = time.perf_counter() - t0
|
| 38 |
|
| 39 |
job_id = uuid.uuid4().hex
|
| 40 |
original_filename = file.filename
|
|
|
|
| 43 |
upload_path = UPLOAD_DIR / f"{job_id}{ext}"
|
| 44 |
upload_path.write_bytes(normalized_contents)
|
| 45 |
|
| 46 |
+
size_kb = len(contents) / 1024
|
| 47 |
+
print(
|
| 48 |
+
f"\n[JOB {job_id[:8]}] Upload received: {original_filename} ({size_kb:.0f} KB)"
|
| 49 |
+
f" | read={t_read:.2f}s | normalize={t_normalize:.2f}s",
|
| 50 |
+
flush=True,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
job = {
|
| 54 |
"id": job_id,
|
| 55 |
"status": JobStatus.QUEUED,
|
|
|
|
| 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") not in (JobStatus.COMPLETED, JobStatus.PREVIEW_READY):
|
| 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 |
+
is_preview = job.get("status") == JobStatus.PREVIEW_READY
|
| 119 |
return Response(
|
| 120 |
content=binary_bundle_path.read_bytes(),
|
| 121 |
media_type="application/zip",
|
| 122 |
+
headers={
|
| 123 |
+
"Content-Disposition": 'attachment; filename="visualizer.vizbundle"',
|
| 124 |
+
"X-Bundle-Quality": "preview" if is_preview else "full",
|
| 125 |
+
},
|
| 126 |
)
|
| 127 |
|
| 128 |
|
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)
|
|
@@ -138,7 +172,7 @@ def run_conversion_task(job_id: str, upload_path: Path):
|
|
| 138 |
job["models"] = bundle.get("models")
|
| 139 |
job["outputFormat"] = "split-vizbundle"
|
| 140 |
write_job(job)
|
| 141 |
-
print(f"[
|
| 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)
|
|
|
|
| 172 |
job["models"] = bundle.get("models")
|
| 173 |
job["outputFormat"] = "split-vizbundle"
|
| 174 |
write_job(job)
|
| 175 |
+
print(f"\n[JOB {job_id[:8]}] HD conversion completed in {elapsed_ms / 1000:.2f}s\n", flush=True)
|
| 176 |
except Exception as exc:
|
| 177 |
print(f"Background conversion failed: {exc}", flush=True)
|
| 178 |
if debug is not None:
|
services/lighting/intrinsic.py
CHANGED
|
@@ -21,7 +21,6 @@ from services.lighting.luminance import (
|
|
| 21 |
)
|
| 22 |
from services.lighting.shading import (
|
| 23 |
build_luminance_lighting_maps,
|
| 24 |
-
compute_color_tint,
|
| 25 |
preserve_observed_lighting,
|
| 26 |
smooth_relative_lighting,
|
| 27 |
suppress_replaced_material_lighting,
|
|
@@ -192,7 +191,6 @@ def build_intrinsic_lighting_maps(
|
|
| 192 |
smoothed,
|
| 193 |
replaced_material_mask,
|
| 194 |
),
|
| 195 |
-
"colorTint": compute_color_tint(img_np, surface_mask),
|
| 196 |
}
|
| 197 |
except Exception as exc:
|
| 198 |
print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
|
|
|
|
| 21 |
)
|
| 22 |
from services.lighting.shading import (
|
| 23 |
build_luminance_lighting_maps,
|
|
|
|
| 24 |
preserve_observed_lighting,
|
| 25 |
smooth_relative_lighting,
|
| 26 |
suppress_replaced_material_lighting,
|
|
|
|
| 191 |
smoothed,
|
| 192 |
replaced_material_mask,
|
| 193 |
),
|
|
|
|
| 194 |
}
|
| 195 |
except Exception as exc:
|
| 196 |
print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
|
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 |
|
|
@@ -144,62 +144,9 @@ def build_luminance_lighting_maps(
|
|
| 144 |
None,
|
| 145 |
replaced_material_mask,
|
| 146 |
),
|
| 147 |
-
"colorTint": compute_color_tint(img_np, mask),
|
| 148 |
}
|
| 149 |
|
| 150 |
|
| 151 |
-
# ---------------------------------------------------------------------------
|
| 152 |
-
# Color temperature tint
|
| 153 |
-
# ---------------------------------------------------------------------------
|
| 154 |
-
|
| 155 |
-
def compute_color_tint(
|
| 156 |
-
img_np: np.ndarray,
|
| 157 |
-
surface_mask: np.ndarray,
|
| 158 |
-
) -> list[float] | None:
|
| 159 |
-
"""Extract the scene's color cast over the floor region as an RGB tint.
|
| 160 |
-
|
| 161 |
-
The tint is the ratio of each channel's median to the overall luminance
|
| 162 |
-
median, capturing warm/cool lighting without material albedo. Applied as
|
| 163 |
-
a per-pixel multiplicative tint in the frontend shader so the replacement
|
| 164 |
-
tile inherits the room's color temperature.
|
| 165 |
-
"""
|
| 166 |
-
if not surface_mask.any():
|
| 167 |
-
return None
|
| 168 |
-
|
| 169 |
-
mask = surface_mask > 0
|
| 170 |
-
linear = np.clip(img_np.astype(np.float32) / 255.0, 0.0, 1.0)
|
| 171 |
-
linear = np.where(
|
| 172 |
-
linear <= 0.04045,
|
| 173 |
-
linear / 12.92,
|
| 174 |
-
np.power((linear + 0.055) / 1.055, 2.4),
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
luminance = (
|
| 178 |
-
linear[:, :, 0] * 0.2126
|
| 179 |
-
+ linear[:, :, 1] * 0.7152
|
| 180 |
-
+ linear[:, :, 2] * 0.0722
|
| 181 |
-
)
|
| 182 |
-
lum_values = luminance[mask]
|
| 183 |
-
lum_values = lum_values[np.isfinite(lum_values) & (lum_values > 1e-4)]
|
| 184 |
-
if lum_values.size < 256:
|
| 185 |
-
return None
|
| 186 |
-
|
| 187 |
-
median_lum = float(np.median(lum_values))
|
| 188 |
-
if median_lum < 1e-4:
|
| 189 |
-
return None
|
| 190 |
-
|
| 191 |
-
tint = []
|
| 192 |
-
for ch in range(3):
|
| 193 |
-
ch_values = linear[:, :, ch][mask]
|
| 194 |
-
ch_values = ch_values[np.isfinite(ch_values)]
|
| 195 |
-
if ch_values.size < 256:
|
| 196 |
-
tint.append(1.0)
|
| 197 |
-
else:
|
| 198 |
-
median_ch = float(np.median(ch_values))
|
| 199 |
-
tint.append(round(np.clip(median_ch / median_lum, 0.7, 1.4), 4))
|
| 200 |
-
return tint
|
| 201 |
-
|
| 202 |
-
|
| 203 |
# ---------------------------------------------------------------------------
|
| 204 |
# Statistics
|
| 205 |
# ---------------------------------------------------------------------------
|
|
@@ -240,6 +187,6 @@ def preserve_observed_lighting(
|
|
| 240 |
fused[highlight_pixels],
|
| 241 |
observed_relative[highlight_pixels],
|
| 242 |
)
|
| 243 |
-
fused = np.clip(fused, SHADE_MAP_MIN, 1.
|
| 244 |
fused[surface_mask == 0] = 1.0
|
| 245 |
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 |
|
|
|
|
| 144 |
None,
|
| 145 |
replaced_material_mask,
|
| 146 |
),
|
|
|
|
| 147 |
}
|
| 148 |
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
# ---------------------------------------------------------------------------
|
| 151 |
# Statistics
|
| 152 |
# ---------------------------------------------------------------------------
|
|
|
|
| 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
|
|
@@ -48,30 +48,62 @@ _DEFAULT_MAPPING_META = {
|
|
| 48 |
def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None, progress_callback=None):
|
| 49 |
t_start = time.perf_counter()
|
| 50 |
d = debug # shorthand
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
t0 = time.perf_counter()
|
| 53 |
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 54 |
img_np = np.array(img)
|
| 55 |
h, w = img_np.shape[:2]
|
| 56 |
min_floor_area = max(1200, int(w * h * 0.015))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
el = (time.perf_counter() - t0) * 1000
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
| 59 |
if d:
|
| 60 |
debug_stages.record_source_image(d, img_np, w, h, min_floor_area, el)
|
| 61 |
|
| 62 |
-
# --- Segmentation ---
|
| 63 |
if progress_callback:
|
| 64 |
progress_callback(PipelinePhase.SEGMENTATION, 0)
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
el = (time.perf_counter() - t0) * 1000
|
| 68 |
-
print(f"[TIMING] Floor segmentation took {el / 1000:.3f} seconds", flush=True)
|
| 69 |
if d:
|
| 70 |
debug_stages.record_segmentation(d, img_np, seg_map, state.segmentation_backend, w, h, el)
|
|
|
|
| 71 |
if progress_callback:
|
| 72 |
progress_callback(PipelinePhase.SEGMENTATION, 100)
|
|
|
|
| 73 |
|
| 74 |
-
# --- Floor masking ---
|
| 75 |
if progress_callback:
|
| 76 |
progress_callback(PipelinePhase.MASKING, 0)
|
| 77 |
t0 = time.perf_counter()
|
|
@@ -84,31 +116,18 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 84 |
seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0))
|
| 85 |
floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK
|
| 86 |
cleaned = floor_mask.copy()
|
| 87 |
-
|
| 88 |
el = (time.perf_counter() - t0) * 1000
|
| 89 |
-
|
| 90 |
if d:
|
| 91 |
debug_stages.record_floor_mask(d, img_np, raw_primary, cleaned, floor_mask, floor_mask_source, sam_metadata, el)
|
| 92 |
if progress_callback:
|
| 93 |
progress_callback(PipelinePhase.MASKING, 100)
|
| 94 |
|
| 95 |
-
# --- Geometry ---
|
| 96 |
-
if progress_callback:
|
| 97 |
-
progress_callback(PipelinePhase.GEOMETRY, 0)
|
| 98 |
-
t0 = time.perf_counter()
|
| 99 |
-
geometry = estimate_scene_geometry(img, img_np, w, h)
|
| 100 |
-
depth = geometry.get("depth")
|
| 101 |
-
el = (time.perf_counter() - t0) * 1000
|
| 102 |
-
print(f"[TIMING] Geometry estimation ({geometry.get('provider')}) took {el / 1000:.3f} seconds", flush=True)
|
| 103 |
-
if d:
|
| 104 |
-
debug_stages.record_geometry(d, depth, floor_mask, geometry, el)
|
| 105 |
-
if progress_callback:
|
| 106 |
-
progress_callback(PipelinePhase.GEOMETRY, 55)
|
| 107 |
-
|
| 108 |
t0 = time.perf_counter()
|
| 109 |
homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
|
| 110 |
el = (time.perf_counter() - t0) * 1000
|
| 111 |
-
|
| 112 |
if d:
|
| 113 |
debug_stages.record_plane(d, img_np, plane, homography, el)
|
| 114 |
if progress_callback:
|
|
@@ -123,7 +142,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 123 |
occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
|
| 124 |
occlusion_indices = mask_to_indices(occlusion_mask)
|
| 125 |
el = (time.perf_counter() - t0) * 1000
|
| 126 |
-
|
| 127 |
if d:
|
| 128 |
debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)
|
| 129 |
|
|
@@ -136,7 +155,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 136 |
mapping_metadata = surface_mapping["metadata"] if surface_mapping is not None else {
|
| 137 |
**_DEFAULT_MAPPING_META, "surfaceUvTotalPixels": int(len(surface_indices))}
|
| 138 |
el = (time.perf_counter() - t0) * 1000
|
| 139 |
-
|
| 140 |
if d:
|
| 141 |
debug_stages.record_surface_mapping(d, h, w, surface_indices, surface_mapping, use_surface_uv, mapping_metadata, el)
|
| 142 |
if progress_callback:
|
|
@@ -160,13 +179,11 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 160 |
lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
|
| 161 |
if lighting_maps and lighting_maps.get("shadeMap") is not None:
|
| 162 |
lighting_source = "luminance"
|
| 163 |
-
color_tint = None
|
| 164 |
if lighting_maps:
|
| 165 |
shade_map, showroom_shade_map, reflection_map = lighting_maps.get("shadeMap"), lighting_maps.get("showroomShadeMap"), lighting_maps.get("reflectionMap")
|
| 166 |
-
color_tint = lighting_maps.get("colorTint")
|
| 167 |
shade_statistics = lighting_map_statistics(shade_map, surface_mask)
|
| 168 |
el = (time.perf_counter() - t0) * 1000
|
| 169 |
-
|
| 170 |
if d:
|
| 171 |
debug_stages.record_lighting(d, shade_map, showroom_shade_map, reflection_map, surface_mask, lighting_source, el)
|
| 172 |
|
|
@@ -196,7 +213,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 196 |
surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None,
|
| 197 |
)
|
| 198 |
el = (time.perf_counter() - t0) * 1000
|
| 199 |
-
|
| 200 |
if d:
|
| 201 |
debug_stages.record_direction(d, img_np, floor_direction, el)
|
| 202 |
if progress_callback:
|
|
@@ -205,6 +222,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 205 |
# --- Package segments ---
|
| 206 |
if progress_callback:
|
| 207 |
progress_callback(PipelinePhase.PACKAGING, 0)
|
|
|
|
| 208 |
models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
|
| 209 |
segments = []
|
| 210 |
if len(surface_indices) >= min_floor_area:
|
|
@@ -213,7 +231,6 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 213 |
homography=homography, plane=plane, surface_mapping=surface_mapping,
|
| 214 |
use_surface_uv=use_surface_uv, shade_map=shade_map,
|
| 215 |
showroom_shade_map=showroom_shade_map, reflection_map=reflection_map,
|
| 216 |
-
color_tint=color_tint,
|
| 217 |
floor_mask=floor_mask, surface_mask=surface_mask,
|
| 218 |
replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask,
|
| 219 |
floor_direction=floor_direction, sam_metadata=sam_metadata,
|
|
@@ -229,9 +246,46 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
|
|
| 229 |
|
| 230 |
if progress_callback:
|
| 231 |
progress_callback(PipelinePhase.PACKAGING, 100)
|
|
|
|
| 232 |
total_elapsed = time.perf_counter() - t_start
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
| 234 |
if d:
|
| 235 |
d.complete(total_elapsed * 1000)
|
| 236 |
return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
|
| 237 |
"modelName": models["segmentation"]["name"], "models": models}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
|
|
|
| 48 |
def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None, progress_callback=None):
|
| 49 |
t_start = time.perf_counter()
|
| 50 |
d = debug # shorthand
|
| 51 |
+
stage_times: list[tuple[str, float, str]] = [] # (stage_name, seconds, detail)
|
| 52 |
+
|
| 53 |
+
def _log_stage(name: str, t0: float, detail: str = ""):
|
| 54 |
+
elapsed = time.perf_counter() - t0
|
| 55 |
+
stage_times.append((name, elapsed, detail))
|
| 56 |
|
| 57 |
t0 = time.perf_counter()
|
| 58 |
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 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 |
+
# --- Floor masking (SAM2 removed — morphological cleanup only) ---
|
| 107 |
if progress_callback:
|
| 108 |
progress_callback(PipelinePhase.MASKING, 0)
|
| 109 |
t0 = time.perf_counter()
|
|
|
|
| 116 |
seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0))
|
| 117 |
floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK
|
| 118 |
cleaned = floor_mask.copy()
|
| 119 |
+
sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "removed"}
|
| 120 |
el = (time.perf_counter() - t0) * 1000
|
| 121 |
+
_log_stage("Floor Masking", t0, f"source={floor_mask_source}")
|
| 122 |
if d:
|
| 123 |
debug_stages.record_floor_mask(d, img_np, raw_primary, cleaned, floor_mask, floor_mask_source, sam_metadata, el)
|
| 124 |
if progress_callback:
|
| 125 |
progress_callback(PipelinePhase.MASKING, 100)
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
t0 = time.perf_counter()
|
| 128 |
homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
|
| 129 |
el = (time.perf_counter() - t0) * 1000
|
| 130 |
+
_log_stage("Plane Fitting", t0)
|
| 131 |
if d:
|
| 132 |
debug_stages.record_plane(d, img_np, plane, homography, el)
|
| 133 |
if progress_callback:
|
|
|
|
| 142 |
occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
|
| 143 |
occlusion_indices = mask_to_indices(occlusion_mask)
|
| 144 |
el = (time.perf_counter() - t0) * 1000
|
| 145 |
+
_log_stage("Surface Masking", t0)
|
| 146 |
if d:
|
| 147 |
debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)
|
| 148 |
|
|
|
|
| 155 |
mapping_metadata = surface_mapping["metadata"] if surface_mapping is not None else {
|
| 156 |
**_DEFAULT_MAPPING_META, "surfaceUvTotalPixels": int(len(surface_indices))}
|
| 157 |
el = (time.perf_counter() - t0) * 1000
|
| 158 |
+
_log_stage("UV Mapping", t0, f"uv={'yes' if use_surface_uv else 'no'}")
|
| 159 |
if d:
|
| 160 |
debug_stages.record_surface_mapping(d, h, w, surface_indices, surface_mapping, use_surface_uv, mapping_metadata, el)
|
| 161 |
if progress_callback:
|
|
|
|
| 179 |
lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
|
| 180 |
if lighting_maps and lighting_maps.get("shadeMap") is not None:
|
| 181 |
lighting_source = "luminance"
|
|
|
|
| 182 |
if lighting_maps:
|
| 183 |
shade_map, showroom_shade_map, reflection_map = lighting_maps.get("shadeMap"), lighting_maps.get("showroomShadeMap"), lighting_maps.get("reflectionMap")
|
|
|
|
| 184 |
shade_statistics = lighting_map_statistics(shade_map, surface_mask)
|
| 185 |
el = (time.perf_counter() - t0) * 1000
|
| 186 |
+
_log_stage("Lighting", t0, f"source={lighting_source}")
|
| 187 |
if d:
|
| 188 |
debug_stages.record_lighting(d, shade_map, showroom_shade_map, reflection_map, surface_mask, lighting_source, el)
|
| 189 |
|
|
|
|
| 213 |
surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None,
|
| 214 |
)
|
| 215 |
el = (time.perf_counter() - t0) * 1000
|
| 216 |
+
_log_stage("Floor Direction", t0, f"method={floor_direction.get('directionMethod')}")
|
| 217 |
if d:
|
| 218 |
debug_stages.record_direction(d, img_np, floor_direction, el)
|
| 219 |
if progress_callback:
|
|
|
|
| 222 |
# --- Package segments ---
|
| 223 |
if progress_callback:
|
| 224 |
progress_callback(PipelinePhase.PACKAGING, 0)
|
| 225 |
+
t0 = time.perf_counter()
|
| 226 |
models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
|
| 227 |
segments = []
|
| 228 |
if len(surface_indices) >= min_floor_area:
|
|
|
|
| 231 |
homography=homography, plane=plane, surface_mapping=surface_mapping,
|
| 232 |
use_surface_uv=use_surface_uv, shade_map=shade_map,
|
| 233 |
showroom_shade_map=showroom_shade_map, reflection_map=reflection_map,
|
|
|
|
| 234 |
floor_mask=floor_mask, surface_mask=surface_mask,
|
| 235 |
replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask,
|
| 236 |
floor_direction=floor_direction, sam_metadata=sam_metadata,
|
|
|
|
| 246 |
|
| 247 |
if progress_callback:
|
| 248 |
progress_callback(PipelinePhase.PACKAGING, 100)
|
| 249 |
+
_log_stage("Packaging", t0, f"segments={len(segments)}")
|
| 250 |
total_elapsed = time.perf_counter() - t_start
|
| 251 |
+
|
| 252 |
+
# ── Print clean timing summary ──
|
| 253 |
+
_print_pipeline_summary(stage_times, total_elapsed, w, h)
|
| 254 |
+
|
| 255 |
if d:
|
| 256 |
d.complete(total_elapsed * 1000)
|
| 257 |
return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
|
| 258 |
"modelName": models["segmentation"]["name"], "models": models}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _print_pipeline_summary(
|
| 262 |
+
stage_times: list[tuple[str, float, str]],
|
| 263 |
+
total_elapsed: float,
|
| 264 |
+
w: int,
|
| 265 |
+
h: int,
|
| 266 |
+
):
|
| 267 |
+
"""Print a formatted pipeline timing summary to stdout."""
|
| 268 |
+
sep = "─" * 60
|
| 269 |
+
lines = [
|
| 270 |
+
"",
|
| 271 |
+
f"┌{sep}┐",
|
| 272 |
+
f"│ {'PIPELINE TIMING REPORT':^58} │",
|
| 273 |
+
f"│ {'Image: ' + f'{w}x{h}':^58} │",
|
| 274 |
+
f"├{'─' * 30}┬{'─' * 14}┬{'─' * 14}┤",
|
| 275 |
+
f"│ {'Stage':<28} │ {'Time':>12} │ {'% Total':>12} │",
|
| 276 |
+
f"├{'─' * 30}┼{'─' * 14}┼{'─' * 14}┤",
|
| 277 |
+
]
|
| 278 |
+
for name, elapsed, detail in stage_times:
|
| 279 |
+
pct = (elapsed / total_elapsed * 100) if total_elapsed > 0 else 0
|
| 280 |
+
time_str = f"{elapsed:.2f}s"
|
| 281 |
+
pct_str = f"{pct:.1f}%"
|
| 282 |
+
label = f"{name} ({detail})" if detail else name
|
| 283 |
+
if len(label) > 28:
|
| 284 |
+
label = label[:27] + "\u2026"
|
| 285 |
+
lines.append(f"│ {label:<28} │ {time_str:>12} │ {pct_str:>12} │")
|
| 286 |
+
lines.append(f"├{'─' * 30}┼{'─' * 14}┼{'─' * 14}┤")
|
| 287 |
+
total_str = f"{total_elapsed:.2f}s"
|
| 288 |
+
lines.append(f"│ {'TOTAL':.<28} │ {total_str:>12} │ {'100%':>12} │")
|
| 289 |
+
lines.append(f"└{'─' * 30}┴{'─' * 14}┴{'─' * 14}┘")
|
| 290 |
+
lines.append("")
|
| 291 |
+
print("\n".join(lines), flush=True)
|
services/pipeline/bundle_assembly.py
CHANGED
|
@@ -39,7 +39,6 @@ def build_floor_segment(
|
|
| 39 |
shade_map: np.ndarray | None,
|
| 40 |
showroom_shade_map: np.ndarray | None,
|
| 41 |
reflection_map: np.ndarray | None,
|
| 42 |
-
color_tint: list[float] | None = None,
|
| 43 |
floor_mask: np.ndarray,
|
| 44 |
surface_mask: np.ndarray,
|
| 45 |
replaced_material_mask: np.ndarray,
|
|
@@ -75,7 +74,6 @@ def build_floor_segment(
|
|
| 75 |
"shadeMap": encode_b64(shade_map),
|
| 76 |
"showroomShadeMap": encode_b64(showroom_shade_map),
|
| 77 |
"reflectionMap": encode_b64(reflection_map),
|
| 78 |
-
"colorTint": color_tint,
|
| 79 |
"metadata": {
|
| 80 |
"segmenter": segmenter_metadata_name(),
|
| 81 |
"segmentationModel": models["segmentation"]["name"],
|
|
@@ -109,7 +107,7 @@ def build_floor_segment(
|
|
| 109 |
"showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX],
|
| 110 |
"renderPresetDefaults": {
|
| 111 |
"preset": "realistic",
|
| 112 |
-
"shadingStrength":
|
| 113 |
"reflectionTransfer": True,
|
| 114 |
"edgeFeatherPixels": 2,
|
| 115 |
},
|
|
|
|
| 39 |
shade_map: np.ndarray | None,
|
| 40 |
showroom_shade_map: np.ndarray | None,
|
| 41 |
reflection_map: np.ndarray | None,
|
|
|
|
| 42 |
floor_mask: np.ndarray,
|
| 43 |
surface_mask: np.ndarray,
|
| 44 |
replaced_material_mask: np.ndarray,
|
|
|
|
| 74 |
"shadeMap": encode_b64(shade_map),
|
| 75 |
"showroomShadeMap": encode_b64(showroom_shade_map),
|
| 76 |
"reflectionMap": encode_b64(reflection_map),
|
|
|
|
| 77 |
"metadata": {
|
| 78 |
"segmenter": segmenter_metadata_name(),
|
| 79 |
"segmentationModel": models["segmentation"]["name"],
|
|
|
|
| 107 |
"showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX],
|
| 108 |
"renderPresetDefaults": {
|
| 109 |
"preset": "realistic",
|
| 110 |
+
"shadingStrength": 0.30,
|
| 111 |
"reflectionTransfer": True,
|
| 112 |
"edgeFeatherPixels": 2,
|
| 113 |
},
|
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/preview_builder.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
floor_direction = find_floor_direction(img_np, surface_mask, wall_mask=wall_mask)
|
| 98 |
+
|
| 99 |
+
# Package
|
| 100 |
+
sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "preview"}
|
| 101 |
+
mapping_metadata = {"surfaceUvEnabled": False, "textureMappingMode": "regularized-floor-plane"}
|
| 102 |
+
models = {
|
| 103 |
+
"segmentation": {"backend": state.segmentation_backend, "name": "oneformer-preview"},
|
| 104 |
+
"geometry": {"provider": GeometryProvider.HOMOGRAPHY, "name": None},
|
| 105 |
+
"depth": {"enabled": False, "name": None},
|
| 106 |
+
"intrinsic": {"enabled": False, "name": None},
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
segments = []
|
| 110 |
+
if len(surface_indices) >= min_floor_area:
|
| 111 |
+
segments.append(build_floor_segment(
|
| 112 |
+
surface_indices=surface_indices, occlusion_indices=occlusion_indices,
|
| 113 |
+
homography=homography, plane=plane, surface_mapping=None,
|
| 114 |
+
use_surface_uv=False, shade_map=shade_map,
|
| 115 |
+
showroom_shade_map=showroom_shade_map, reflection_map=reflection_map,
|
| 116 |
+
floor_mask=floor_mask, surface_mask=surface_mask,
|
| 117 |
+
replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask,
|
| 118 |
+
floor_direction=floor_direction, sam_metadata=sam_metadata,
|
| 119 |
+
edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
|
| 120 |
+
shade_statistics=shade_statistics, lighting_source="luminance",
|
| 121 |
+
intrinsic_lighting_used=False, models=models, depth=None, geometry=geometry))
|
| 122 |
+
if not segments:
|
| 123 |
+
segments = build_fallback_segments(seg_map, None, models)
|
| 124 |
+
|
| 125 |
+
total_elapsed = time.perf_counter() - t_start
|
| 126 |
+
print(f"[PREVIEW] Built in {total_elapsed:.2f}s ({w}x{h}, inference@{PREVIEW_MAX_DIM}px)", flush=True)
|
| 127 |
+
|
| 128 |
+
return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
|
| 129 |
+
"modelName": models["segmentation"]["name"], "models": models,
|
| 130 |
+
"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"
|