github-actions[bot] commited on
Commit
18196ae
·
1 Parent(s): 3e1a674

Automated Deploy: 95241fef61713656c774921da02adaf14380bc08

Browse files
config/runtime.py CHANGED
@@ -52,6 +52,13 @@ CONVERSION_TARGET_MS = max(5_000, int(config_value(
52
  "CONVERSION_TARGET_MS", "runtime", "conversion_target_ms", "30000",
53
  )))
54
 
 
 
 
 
 
 
 
55
  DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value(
56
  "DEBUG_ARTIFACTS_MAX_DIMENSION", "runtime", "debug_artifacts_max_dimension", "1600",
57
  )))
 
52
  "CONVERSION_TARGET_MS", "runtime", "conversion_target_ms", "30000",
53
  )))
54
 
55
+ # Conversions allowed in flight at once. GPU inference is serialised separately
56
+ # (state.gpu_inference), so extra slots overlap one job's CPU stages with
57
+ # another's inference; the cap bounds peak memory from full-resolution arrays.
58
+ MAX_CONCURRENT_CONVERSIONS = max(1, int(config_value(
59
+ "MAX_CONCURRENT_CONVERSIONS", "runtime", "max_concurrent_conversions", "2",
60
+ )))
61
+
62
  DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value(
63
  "DEBUG_ARTIFACTS_MAX_DIMENSION", "runtime", "debug_artifacts_max_dimension", "1600",
64
  )))
config/surface.py CHANGED
@@ -78,3 +78,46 @@ SURFACE_PLANE_NORMAL_MIN_COS = float(config_value(
78
  SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
79
  "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45",
80
  ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
79
  "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45",
80
  ))
81
+
82
+ # --- Walls -----------------------------------------------------------------
83
+ # Walls use their own plane budget so the floor keeps `max_planes` (1 on GPU)
84
+ # no matter how many walls a room has.
85
+ WALL_MAX_PLANES = max(1, int(config_value(
86
+ "WALL_MAX_PLANES", "surface_mapping", "wall_max_planes", "4",
87
+ )))
88
+
89
+ WALL_MAX_SEGMENTS = max(1, int(config_value(
90
+ "WALL_MAX_SEGMENTS", "surface_mapping", "max_walls", "6",
91
+ )))
92
+
93
+ # Long-side resolution wall discovery and plane fitting run at. Only the final
94
+ # per-wall masks and UVs are produced at full resolution.
95
+ WALL_WORK_MAX_DIMENSION = max(256, int(config_value(
96
+ "WALL_WORK_MAX_DIMENSION", "surface_mapping", "wall_work_max_dimension", "768",
97
+ )))
98
+
99
+ # A plane counts as a wall when |normal.y| (camera up component) is at most this.
100
+ WALL_MAX_NORMAL_Y = float(config_value(
101
+ "WALL_MAX_NORMAL_Y", "surface_mapping", "wall_max_normal_y", "0.45",
102
+ ))
103
+
104
+ # Planes closer than both limits are merged so one flat wall is never split.
105
+ WALL_COPLANAR_ANGLE_DEGREES = float(config_value(
106
+ "WALL_COPLANAR_ANGLE_DEGREES", "surface_mapping", "wall_coplanar_angle_degrees", "10",
107
+ ))
108
+
109
+ WALL_COPLANAR_OFFSET_METERS = float(config_value(
110
+ "WALL_COPLANAR_OFFSET_METERS", "surface_mapping", "wall_coplanar_offset_meters", "0.15",
111
+ ))
112
+
113
+ # Wall outlines are redrawn with straight edges; zig-zag within this tolerance
114
+ # (fraction of the short image side, ~6px at 1440) becomes one line. 0 disables.
115
+ WALL_EDGE_STRAIGHTEN_RATIO = max(0.0, float(config_value(
116
+ "WALL_EDGE_STRAIGHTEN_RATIO", "surface_mapping", "wall_edge_straighten_ratio", "0.004",
117
+ )))
118
+
119
+ # Minimum share of a wall's pixels that must get a ray/plane UV; below this the
120
+ # wall falls back to its contour homography.
121
+ WALL_UV_MIN_COVERAGE = float(config_value(
122
+ "WALL_UV_MIN_COVERAGE", "surface_mapping", "wall_uv_min_coverage", "0.9",
123
+ ))
models/depth.py CHANGED
@@ -147,6 +147,11 @@ def estimate_moge_geometry(img_np: np.ndarray, target_h: int | None = None, targ
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
 
147
 
148
 
149
  def estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int):
150
+ with state.gpu_inference():
151
+ return _estimate_scene_geometry(img, img_np, width, height)
152
+
153
+
154
+ def _estimate_scene_geometry(img: Image.Image, img_np: np.ndarray, width: int, height: int):
155
  geometry = estimate_moge_geometry(img_np, target_h=height, target_w=width)
156
  if geometry is not None:
157
  return geometry
models/loader.py CHANGED
@@ -161,4 +161,39 @@ def warm_start_models():
161
  if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
162
  _load_intrinsic_model()
163
 
 
 
164
  print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
162
  _load_intrinsic_model()
163
 
164
+ _warm_up_inference()
165
+
166
  print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True)
167
+
168
+
169
+ def _warm_up_inference():
170
+ """Run throwaway inference so the first real job doesn't pay CUDA kernel init.
171
+
172
+ Loading weights alone leaves kernel compilation and autocast setup for the
173
+ first request, which made post-restart jobs take 16-48s instead of ~5s.
174
+ Both orientations are warmed because inference inputs are capped at
175
+ INFERENCE_MAX_DIMENSION on the long side (portrait and landscape shapes).
176
+ """
177
+ # Deferred: models.depth / models.segmentation import from this module.
178
+ import numpy as np
179
+ from PIL import Image
180
+
181
+ from config.runtime import INFERENCE_MAX_DIMENSION
182
+ from models.depth import estimate_scene_geometry
183
+ from models.segmentation import run_segmentation
184
+
185
+ long_side = INFERENCE_MAX_DIMENSION
186
+ short_side = round(long_side * 0.75)
187
+ rng = np.random.default_rng(0)
188
+ for w, h in ((short_side, long_side), (long_side, short_side)):
189
+ t0 = time.perf_counter()
190
+ try:
191
+ img_np = rng.integers(0, 256, size=(h, w, 3), dtype=np.uint8)
192
+ img = Image.fromarray(img_np)
193
+ run_segmentation(img, img_np)
194
+ estimate_scene_geometry(img, img_np, w, h)
195
+ if state.device.type == "cuda":
196
+ torch.cuda.synchronize()
197
+ print(f"[TIMING] Warm-up inference {w}x{h} took {time.perf_counter() - t0:.3f} seconds", flush=True)
198
+ except Exception as exc:
199
+ print(f"Warm-up inference {w}x{h} skipped ({exc}); first job may be slower.", flush=True)
models/segmentation.py CHANGED
@@ -56,6 +56,11 @@ def run_segmentation(img: Image.Image, img_np: np.ndarray, target_h: int | None
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:
 
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
+ with state.gpu_inference():
60
+ return _run_segmentation_model(img, img_np, out_h, out_w)
61
+
62
+
63
+ def _run_segmentation_model(img: Image.Image, img_np: np.ndarray, out_h: int, out_w: int) -> np.ndarray:
64
  # Try ONNX first
65
  result = _run_segmentation_onnx(img, img_np, out_h, out_w)
66
  if result is not None:
routes/segmentation.py CHANGED
@@ -38,15 +38,16 @@ def build_oneformer_polygon_response(
38
  task_inputs=["panoptic"],
39
  return_tensors="pt",
40
  ).to(_state.device)
41
- with torch.no_grad():
42
- outputs = _state.seg_model(**inputs)
43
-
44
- result = _state.seg_processor.post_process_panoptic_segmentation(
45
- outputs,
46
- threshold=threshold,
47
- mask_threshold=mask_threshold,
48
- target_sizes=[(h, w)],
49
- )[0]
 
50
  segmentation = result.get("segmentation")
51
  if segmentation is None:
52
  return {
 
38
  task_inputs=["panoptic"],
39
  return_tensors="pt",
40
  ).to(_state.device)
41
+ with _state.gpu_inference():
42
+ with torch.no_grad():
43
+ outputs = _state.seg_model(**inputs)
44
+
45
+ result = _state.seg_processor.post_process_panoptic_segmentation(
46
+ outputs,
47
+ threshold=threshold,
48
+ mask_threshold=mask_threshold,
49
+ target_sizes=[(h, w)],
50
+ )[0]
51
  segmentation = result.get("segmentation")
52
  if segmentation is None:
53
  return {
routes/viz2d.py CHANGED
@@ -1,5 +1,6 @@
1
  """Viz2D conversion and job management routes."""
2
 
 
3
  import json
4
  import math
5
  import time
@@ -21,6 +22,10 @@ from enums import JobStatus
21
 
22
  router = APIRouter(prefix="/viz2d", tags=["viz2d"])
23
 
 
 
 
 
24
 
25
  @router.post("/convert")
26
  async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
@@ -60,7 +65,7 @@ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile =
60
  "phase": "queued",
61
  "progress": 0,
62
  "phaseProgress": 0,
63
- "message": "Waiting for an analysis slot\u2026",
64
  "createdAt": datetime.now(timezone.utc).isoformat(),
65
  "estimatedTotalMs": estimate_conversion_ms(),
66
  "estimatedRemainingMs": estimate_conversion_ms(),
@@ -141,8 +146,29 @@ async def viz2d_record_client_timings(job_id: str, payload: dict = Body(...)):
141
 
142
 
143
  @router.get("/jobs/{job_id}")
144
- async def viz2d_job_status(job_id: str):
145
- return read_job(job_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
 
148
  @router.get("/jobs/{job_id}/debug")
 
1
  """Viz2D conversion and job management routes."""
2
 
3
+ import asyncio
4
  import json
5
  import math
6
  import time
 
22
 
23
  router = APIRouter(prefix="/viz2d", tags=["viz2d"])
24
 
25
+ JOB_STATUS_MAX_WAIT_MS = 10_000
26
+ JOB_STATUS_WAIT_STEP_S = 0.05
27
+ JOB_TERMINAL_STATUSES = {JobStatus.COMPLETED, JobStatus.PREVIEW_READY, JobStatus.FAILED}
28
+
29
 
30
  @router.post("/convert")
31
  async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
 
65
  "phase": "queued",
66
  "progress": 0,
67
  "phaseProgress": 0,
68
+ "message": "Starting analysis\u2026",
69
  "createdAt": datetime.now(timezone.utc).isoformat(),
70
  "estimatedTotalMs": estimate_conversion_ms(),
71
  "estimatedRemainingMs": estimate_conversion_ms(),
 
146
 
147
 
148
  @router.get("/jobs/{job_id}")
149
+ async def viz2d_job_status(
150
+ job_id: str,
151
+ wait_ms: int = Query(0, alias="waitMs", ge=0, le=JOB_STATUS_MAX_WAIT_MS),
152
+ ):
153
+ """Return the job, optionally holding the request until it changes.
154
+
155
+ With waitMs the response is sent as soon as status, phase or progress
156
+ moves (or the job finishes), so clients learn of completion within one
157
+ check step instead of up to a full client-side polling interval.
158
+ """
159
+ job = read_job(job_id)
160
+ if wait_ms <= 0 or job.get("status") in JOB_TERMINAL_STATUSES:
161
+ return job
162
+ snapshot = (job.get("status"), job.get("phase"), job.get("progress"))
163
+ deadline = time.monotonic() + wait_ms / 1000
164
+ while time.monotonic() < deadline:
165
+ await asyncio.sleep(JOB_STATUS_WAIT_STEP_S)
166
+ job = read_job(job_id)
167
+ if job.get("status") in JOB_TERMINAL_STATUSES:
168
+ return job
169
+ if (job.get("status"), job.get("phase"), job.get("progress")) != snapshot:
170
+ return job
171
+ return job
172
 
173
 
174
  @router.get("/jobs/{job_id}/debug")
services/geometry/multi_plane.py CHANGED
@@ -92,7 +92,19 @@ def geometry_point_maps(mask: np.ndarray, geometry: dict | None):
92
  }
93
 
94
 
95
- def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_reliable: bool = True):
 
 
 
 
 
 
 
 
 
 
 
 
96
  if len(points) < SURFACE_MIN_PLANE_PIXELS:
97
  return []
98
 
@@ -104,7 +116,7 @@ def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_re
104
  remaining = np.ones(len(points), dtype=bool)
105
  planes = []
106
 
107
- for plane_id in range(SURFACE_MAX_PLANES):
108
  candidates = sample_indices[remaining[sample_indices]]
109
  if len(candidates) < max(300, SURFACE_MIN_PLANE_PIXELS // 6):
110
  break
 
92
  }
93
 
94
 
95
+ def fit_multi_surface_planes(
96
+ points: np.ndarray,
97
+ normals: np.ndarray,
98
+ normals_reliable: bool = True,
99
+ max_planes: int | None = None,
100
+ ):
101
+ """Sequential RANSAC plane fitting.
102
+
103
+ max_planes defaults to SURFACE_MAX_PLANES (the floor's budget); walls pass
104
+ WALL_MAX_PLANES so they can split into several planes without changing
105
+ how the floor is fitted.
106
+ """
107
+ plane_budget = SURFACE_MAX_PLANES if max_planes is None else max(1, int(max_planes))
108
  if len(points) < SURFACE_MIN_PLANE_PIXELS:
109
  return []
110
 
 
116
  remaining = np.ones(len(points), dtype=bool)
117
  planes = []
118
 
119
+ for plane_id in range(plane_budget):
120
  candidates = sample_indices[remaining[sample_indices]]
121
  if len(candidates) < max(300, SURFACE_MIN_PLANE_PIXELS // 6):
122
  break
services/geometry/plane_uv.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analytic UV mapping for a fitted plane.
2
+
3
+ Functions
4
+ ---------
5
+ upright_plane_basis - in-plane (u, v) axes with v aligned to a given "up" direction
6
+ ray_plane_uv - UV of pixels by intersecting camera rays with a plane
7
+ plane_to_image_transform - exact 3x3 pixel -> plane-UV homography for a plane
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import numpy as np
13
+
14
+ # Hits farther than this (metres) are near-horizon rays and are rejected.
15
+ MAX_RAY_DISTANCE_METERS = 100.0
16
+
17
+
18
+ def upright_plane_basis(normal: np.ndarray, up: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
19
+ """Return unit (u, v) axes spanning the plane, with v following `up`.
20
+
21
+ For walls `up` is the floor normal, so textures stay upright even when the
22
+ camera is tilted. Falls back to the camera's +Y axis when `up` is (nearly)
23
+ parallel to the plane normal.
24
+ """
25
+ normal = np.asarray(normal, dtype=np.float32)
26
+ normal = normal / max(float(np.linalg.norm(normal)), 1e-6)
27
+ for reference in (np.asarray(up, dtype=np.float32), np.array([0.0, 1.0, 0.0], dtype=np.float32)):
28
+ v_axis = reference - normal * float(reference @ normal)
29
+ length = float(np.linalg.norm(v_axis))
30
+ if length > 1e-4:
31
+ v_axis = v_axis / length
32
+ u_axis = np.cross(v_axis, normal)
33
+ u_axis = u_axis / max(float(np.linalg.norm(u_axis)), 1e-6)
34
+ return u_axis.astype(np.float32), v_axis.astype(np.float32)
35
+ raise ValueError("Cannot build a plane basis: normal is degenerate.")
36
+
37
+
38
+ def ray_plane_uv(
39
+ flat_indices: np.ndarray,
40
+ image_width: int,
41
+ intrinsics: np.ndarray,
42
+ origin: np.ndarray,
43
+ normal: np.ndarray,
44
+ u_axis: np.ndarray,
45
+ v_axis: np.ndarray,
46
+ ) -> tuple[np.ndarray, np.ndarray]:
47
+ """UV (metres, relative to `origin`) where each pixel's camera ray meets the plane.
48
+
49
+ Uses the pinhole convention of services.geometry.camera.backproject_depth,
50
+ so results agree with depth-derived 3D points. Returns (uv, hit): uv is
51
+ float32 (N, 2) with NaN where the ray misses the plane in front of the
52
+ camera, and hit is the matching boolean mask.
53
+ """
54
+ flat = np.asarray(flat_indices, dtype=np.int64)
55
+ xs = (flat % image_width).astype(np.float32)
56
+ ys = (flat // image_width).astype(np.float32)
57
+ fx = max(float(intrinsics[0, 0]), 1e-6)
58
+ fy = max(float(intrinsics[1, 1]), 1e-6)
59
+ rays = np.column_stack((
60
+ (xs - float(intrinsics[0, 2])) / fx,
61
+ (ys - float(intrinsics[1, 2])) / fy,
62
+ np.ones_like(xs),
63
+ ))
64
+
65
+ normal = np.asarray(normal, dtype=np.float32)
66
+ origin = np.asarray(origin, dtype=np.float32)
67
+ denom = rays @ normal
68
+ with np.errstate(divide="ignore", invalid="ignore"):
69
+ distance = np.where(np.abs(denom) > 1e-6, float(origin @ normal) / denom, np.nan)
70
+ hit = np.isfinite(distance) & (distance > 0) & (distance < MAX_RAY_DISTANCE_METERS)
71
+
72
+ uv = np.full((len(flat), 2), np.nan, dtype=np.float32)
73
+ if hit.any():
74
+ delta = rays[hit] * distance[hit, None] - origin
75
+ uv[hit, 0] = delta @ np.asarray(u_axis, dtype=np.float32)
76
+ uv[hit, 1] = delta @ np.asarray(v_axis, dtype=np.float32)
77
+ return uv, hit
78
+
79
+
80
+ def plane_to_image_transform(
81
+ intrinsics: np.ndarray,
82
+ origin: np.ndarray,
83
+ normal: np.ndarray,
84
+ u_axis: np.ndarray,
85
+ v_axis: np.ndarray,
86
+ ) -> np.ndarray:
87
+ """3x3 homography H with (u, v, w) = H @ (x, y, 1) giving the same UV as ray_plane_uv.
88
+
89
+ Intersecting ray r with the plane gives u = [(n.o)(u.r) - (o.u)(n.r)] / (n.r),
90
+ and likewise for v, which is projective in r and so in the pixel. A flat
91
+ wall therefore needs 9 numbers instead of a per-pixel UV array. Same
92
+ row-major, integer-pixel convention as fit_metric_floor_transform.
93
+ """
94
+ normal = np.asarray(normal, dtype=np.float64)
95
+ origin = np.asarray(origin, dtype=np.float64)
96
+ u_axis = np.asarray(u_axis, dtype=np.float64)
97
+ v_axis = np.asarray(v_axis, dtype=np.float64)
98
+ offset = float(normal @ origin)
99
+ ray_to_uv = np.vstack((
100
+ offset * u_axis - float(origin @ u_axis) * normal,
101
+ offset * v_axis - float(origin @ v_axis) * normal,
102
+ normal,
103
+ ))
104
+ transform = ray_to_uv @ np.linalg.inv(np.asarray(intrinsics, dtype=np.float64))
105
+ return transform / transform[2, 2] if abs(transform[2, 2]) > 1e-12 else transform
services/image/polygons.py CHANGED
@@ -36,3 +36,92 @@ def mask_to_polygons(
36
 
37
  polygons.sort(key=lambda item: item["area"], reverse=True)
38
  return polygons
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  polygons.sort(key=lambda item: item["area"], reverse=True)
38
  return polygons
39
+
40
+
41
+ # Sub-pixel precision used when filling straightened polygons (cv2 `shift` bits).
42
+ _FILL_SHIFT = 4
43
+
44
+
45
+ def straighten_mask_edges(mask: np.ndarray, tolerance: float, min_area: float = 0.0) -> np.ndarray:
46
+ """Redraw a binary mask so its boundaries are straight lines.
47
+
48
+ Each boundary (outer edges and holes such as door or window cut-outs) is
49
+ split where it really changes direction (Douglas-Peucker, `tolerance` px),
50
+ every run is replaced by its least-squares line, and corners are placed
51
+ where neighbouring lines meet. Pixel-level zig-zag within `tolerance`
52
+ therefore becomes one straight edge through the middle of the wobble.
53
+ Boundaries enclosing less than `min_area` px are dropped (specks vanish,
54
+ pinholes are filled).
55
+ """
56
+ mask_u8 = (mask > 0).astype(np.uint8)
57
+ if tolerance <= 0 or not mask_u8.any():
58
+ return mask_u8
59
+ contours, hierarchy = cv2.findContours(mask_u8, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
60
+ if hierarchy is None:
61
+ return mask_u8
62
+
63
+ depths = _contour_depths(hierarchy[0][:, 3])
64
+ scale = float(1 << _FILL_SHIFT)
65
+ out = np.zeros_like(mask_u8)
66
+ for index in np.argsort(depths, kind="stable"):
67
+ contour = contours[index]
68
+ if abs(cv2.contourArea(contour)) < min_area:
69
+ continue
70
+ polygon = np.round(_straight_polygon(contour.reshape(-1, 2), tolerance) * scale).astype(np.int32)
71
+ if len(polygon) < 3:
72
+ continue
73
+ if depths[index] % 2 == 0:
74
+ cv2.fillPoly(out, [polygon], 1, lineType=cv2.LINE_8, shift=_FILL_SHIFT)
75
+ else:
76
+ # A hole's contour runs through the mask pixels bordering it, so
77
+ # redraw that edge line after clearing to keep the mask flush with it.
78
+ cv2.fillPoly(out, [polygon], 0, lineType=cv2.LINE_8, shift=_FILL_SHIFT)
79
+ cv2.polylines(out, [polygon], True, 1, lineType=cv2.LINE_8, shift=_FILL_SHIFT)
80
+ return out
81
+
82
+
83
+ def _contour_depths(parents: np.ndarray) -> np.ndarray:
84
+ """Nesting depth of each contour from cv2 RETR_TREE parent indices (0 = outer)."""
85
+ depths = np.zeros(len(parents), dtype=np.int32)
86
+ for index in range(len(parents)):
87
+ parent = parents[index]
88
+ while parent >= 0:
89
+ depths[index] += 1
90
+ parent = parents[parent]
91
+ return depths
92
+
93
+
94
+ def _straight_polygon(points: np.ndarray, tolerance: float) -> np.ndarray:
95
+ """Polygon whose edges are the best-fit lines of the contour's straight runs."""
96
+ approx = cv2.approxPolyDP(points.reshape(-1, 1, 2), tolerance, True).reshape(-1, 2)
97
+ if len(approx) < 3:
98
+ return approx.astype(np.float32)
99
+
100
+ position = {(int(x), int(y)): i for i, (x, y) in enumerate(points)}
101
+ anchors = sorted(position[(int(x), int(y))] for x, y in approx)
102
+ count = len(points)
103
+ lines = []
104
+ for k, start in enumerate(anchors):
105
+ end = anchors[(k + 1) % len(anchors)]
106
+ run = points[start:end + 1] if end > start else np.concatenate((points[start:], points[:end + 1]))
107
+ vx, vy, x0, y0 = cv2.fitLine(run.astype(np.float32), cv2.DIST_L2, 0, 0.01, 0.01).ravel()
108
+ lines.append((np.array([x0, y0], np.float64), np.array([vx, vy], np.float64)))
109
+
110
+ vertices = []
111
+ for k, anchor in enumerate(anchors):
112
+ corner = _line_intersection(lines[k - 1], lines[k])
113
+ original = points[anchor % count].astype(np.float64)
114
+ # Near-parallel neighbours or a far-away intersection: keep the traced corner.
115
+ if corner is None or np.linalg.norm(corner - original) > 2.0 * tolerance:
116
+ corner = original
117
+ vertices.append(corner)
118
+ return np.asarray(vertices, dtype=np.float32)
119
+
120
+
121
+ def _line_intersection(first, second) -> np.ndarray | None:
122
+ (p1, d1), (p2, d2) = first, second
123
+ denom = d1[0] * d2[1] - d1[1] * d2[0]
124
+ if abs(denom) < 1e-3:
125
+ return None
126
+ t = ((p2[0] - p1[0]) * d2[1] - (p2[1] - p1[1]) * d2[0]) / denom
127
+ return p1 + t * d1
services/jobs/conversion.py CHANGED
@@ -2,14 +2,15 @@
2
 
3
  import time
4
  import threading
 
5
  from datetime import datetime, timezone
6
  from pathlib import Path
7
 
8
  from fastapi import HTTPException
9
 
10
  from config.paths import JOB_DIR
11
- from config.runtime import DEBUG_ARTIFACTS_ENABLED
12
- from services.jobs.store import read_job, write_job
13
  from services.jobs.timing import estimate_conversion_ms, record_conversion_ms
14
  from enums import JobStatus, PipelinePhase
15
 
@@ -23,7 +24,19 @@ CONVERSION_STAGE_WEIGHTS = {
23
  PipelinePhase.PACKAGING: 0.11,
24
  }
25
  CONVERSION_STAGE_ORDER = tuple(CONVERSION_STAGE_WEIGHTS)
26
- CONVERSION_GPU_LOCK = threading.Lock()
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
 
29
  def update_conversion_job(
@@ -49,7 +62,7 @@ def update_conversion_job(
49
  if message is not None:
50
  job["message"] = message
51
  job.update(values)
52
- write_job(job)
53
 
54
 
55
  def weighted_conversion_progress(completed_phases: set[str], phase: str, phase_progress: float) -> int:
@@ -75,7 +88,7 @@ def run_conversion_task(job_id: str, upload_path: Path):
75
  input_read_ms = (time.perf_counter() - t_read) * 1000
76
  image_url = f"/uploads/{upload_path.name}"
77
 
78
- try:
79
  update_conversion_job(
80
  job_id,
81
  status=JobStatus.QUEUED,
@@ -87,11 +100,12 @@ def run_conversion_task(job_id: str, upload_path: Path):
87
  estimatedRemainingMs=estimate_ms,
88
  )
89
 
 
90
  # Run one authoritative HD pass. The former preview repeated
91
  # segmentation and full-resolution CPU work, then was normally missed
92
  # before the status returned to PROCESSING.
93
  gpu_wait_started = time.perf_counter()
94
- with CONVERSION_GPU_LOCK:
95
  gpu_queue_wait_ms = (time.perf_counter() - gpu_wait_started) * 1000
96
  t_start = time.perf_counter()
97
  update_conversion_job(
@@ -124,7 +138,9 @@ def run_conversion_task(job_id: str, upload_path: Path):
124
 
125
  from services.pipeline.builder import build_segmentation_bundle
126
 
127
- bundle = build_segmentation_bundle(image_bytes, debug=debug, progress_callback=report_stage)
 
 
128
  report_stage(PipelinePhase.PACKAGING, 25)
129
  serialization_started = time.perf_counter()
130
  binary_bundle = build_manifest_segmentation_bundle(
@@ -189,3 +205,5 @@ def run_conversion_task(job_id: str, upload_path: Path):
189
  write_job(job)
190
  except Exception:
191
  pass
 
 
 
2
 
3
  import time
4
  import threading
5
+ from contextlib import contextmanager
6
  from datetime import datetime, timezone
7
  from pathlib import Path
8
 
9
  from fastapi import HTTPException
10
 
11
  from config.paths import JOB_DIR
12
+ from config.runtime import DEBUG_ARTIFACTS_ENABLED, MAX_CONCURRENT_CONVERSIONS
13
+ from services.jobs.store import read_job, release_live_job, write_job
14
  from services.jobs.timing import estimate_conversion_ms, record_conversion_ms
15
  from enums import JobStatus, PipelinePhase
16
 
 
24
  PipelinePhase.PACKAGING: 0.11,
25
  }
26
  CONVERSION_STAGE_ORDER = tuple(CONVERSION_STAGE_WEIGHTS)
27
+ CONVERSION_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_CONVERSIONS)
28
+
29
+
30
+ @contextmanager
31
+ def conversion_slot(on_wait):
32
+ """Hold a conversion slot; call on_wait only if the job must actually queue."""
33
+ if not CONVERSION_SLOTS.acquire(blocking=False):
34
+ on_wait()
35
+ CONVERSION_SLOTS.acquire()
36
+ try:
37
+ yield
38
+ finally:
39
+ CONVERSION_SLOTS.release()
40
 
41
 
42
  def update_conversion_job(
 
62
  if message is not None:
63
  job["message"] = message
64
  job.update(values)
65
+ write_job(job, durable=False)
66
 
67
 
68
  def weighted_conversion_progress(completed_phases: set[str], phase: str, phase_progress: float) -> int:
 
88
  input_read_ms = (time.perf_counter() - t_read) * 1000
89
  image_url = f"/uploads/{upload_path.name}"
90
 
91
+ def announce_queued():
92
  update_conversion_job(
93
  job_id,
94
  status=JobStatus.QUEUED,
 
100
  estimatedRemainingMs=estimate_ms,
101
  )
102
 
103
+ try:
104
  # Run one authoritative HD pass. The former preview repeated
105
  # segmentation and full-resolution CPU work, then was normally missed
106
  # before the status returned to PROCESSING.
107
  gpu_wait_started = time.perf_counter()
108
+ with conversion_slot(announce_queued):
109
  gpu_queue_wait_ms = (time.perf_counter() - gpu_wait_started) * 1000
110
  t_start = time.perf_counter()
111
  update_conversion_job(
 
138
 
139
  from services.pipeline.builder import build_segmentation_bundle
140
 
141
+ bundle = build_segmentation_bundle(
142
+ image_bytes, debug=debug, progress_callback=report_stage, include_pixels=False,
143
+ )
144
  report_stage(PipelinePhase.PACKAGING, 25)
145
  serialization_started = time.perf_counter()
146
  binary_bundle = build_manifest_segmentation_bundle(
 
205
  write_job(job)
206
  except Exception:
207
  pass
208
+ finally:
209
+ release_live_job(job_id)
services/jobs/store.py CHANGED
@@ -1,7 +1,16 @@
1
- """Job persistence: read / write JSON job files."""
2
 
 
 
 
 
 
 
 
 
3
  import json
4
  import os
 
5
  from pathlib import Path
6
 
7
  from fastapi import HTTPException
@@ -9,20 +18,40 @@ from fastapi import HTTPException
9
  from config.paths import JOB_DIR
10
  from errors import not_found
11
 
 
 
 
12
 
13
  def job_path(job_id: str) -> Path:
14
  return JOB_DIR / f"{job_id}.json"
15
 
16
 
17
  def read_job(job_id: str):
 
 
 
 
18
  path = job_path(job_id)
19
  if not path.exists():
20
  not_found("Job not found.")
21
  return json.loads(path.read_text())
22
 
23
 
24
- def write_job(job: dict):
25
- path = job_path(job["id"])
26
- temporary = path.with_suffix(f"{path.suffix}.{os.getpid()}.tmp")
 
 
 
 
 
 
 
27
  temporary.write_text(json.dumps(job, separators=(",", ":")))
28
  temporary.replace(path)
 
 
 
 
 
 
 
1
+ """Job persistence: read / write JSON job files.
2
 
3
+ Jobs that are being converted also have a live in-memory copy. Progress
4
+ updates only touch that copy, because rewriting the JSON file ~16 times per
5
+ job occasionally stalled on the pod's disk and added 5-9s of untimed
6
+ "Pipeline Overhead". The file is still written when a job is created and when
7
+ it finishes, and every read prefers the live copy so status checks stay current.
8
+ """
9
+
10
+ import copy
11
  import json
12
  import os
13
+ import threading
14
  from pathlib import Path
15
 
16
  from fastapi import HTTPException
 
18
  from config.paths import JOB_DIR
19
  from errors import not_found
20
 
21
+ _live_jobs: dict[str, dict] = {}
22
+ _live_jobs_lock = threading.Lock()
23
+
24
 
25
  def job_path(job_id: str) -> Path:
26
  return JOB_DIR / f"{job_id}.json"
27
 
28
 
29
  def read_job(job_id: str):
30
+ with _live_jobs_lock:
31
+ live = _live_jobs.get(job_id)
32
+ if live is not None:
33
+ return copy.deepcopy(live)
34
  path = job_path(job_id)
35
  if not path.exists():
36
  not_found("Job not found.")
37
  return json.loads(path.read_text())
38
 
39
 
40
+ def write_job(job: dict, *, durable: bool = True):
41
+ """Store a job. durable=False keeps the update in memory only (live progress)."""
42
+ job_id = job["id"]
43
+ with _live_jobs_lock:
44
+ if not durable or job_id in _live_jobs:
45
+ _live_jobs[job_id] = copy.deepcopy(job)
46
+ if not durable:
47
+ return
48
+ path = job_path(job_id)
49
+ temporary = path.with_suffix(f"{path.suffix}.{os.getpid()}.{threading.get_ident()}.tmp")
50
  temporary.write_text(json.dumps(job, separators=(",", ":")))
51
  temporary.replace(path)
52
+
53
+
54
+ def release_live_job(job_id: str):
55
+ """Drop the in-memory copy once the job's final state is on disk."""
56
+ with _live_jobs_lock:
57
+ _live_jobs.pop(job_id, None)
services/lighting/intrinsic.py CHANGED
@@ -9,7 +9,7 @@ from config.lighting import (
9
  SHADE_MAP_MIN,
10
  )
11
  from config.runtime import ENABLE_INTRINSIC_SHADING
12
- from state import intrinsic_models, device
13
  from enums import IntrinsicAlignment
14
  from utils import to_numpy
15
  from services.lighting.luminance import (
@@ -146,7 +146,8 @@ def build_intrinsic_lighting_maps(
146
  try:
147
  img_float = img_np.astype(np.float32) / 255.0
148
  from intrinsic.pipeline import run_pipeline
149
- results = run_pipeline(intrinsic_models, img_float, device=str(device))
 
150
  shading = extract_intrinsic_shading(results)
151
  if shading is None:
152
  return None
 
9
  SHADE_MAP_MIN,
10
  )
11
  from config.runtime import ENABLE_INTRINSIC_SHADING
12
+ from state import intrinsic_models, device, gpu_inference
13
  from enums import IntrinsicAlignment
14
  from utils import to_numpy
15
  from services.lighting.luminance import (
 
146
  try:
147
  img_float = img_np.astype(np.float32) / 255.0
148
  from intrinsic.pipeline import run_pipeline
149
+ with gpu_inference():
150
+ results = run_pipeline(intrinsic_models, img_float, device=str(device))
151
  shading = extract_intrinsic_shading(results)
152
  if shading is None:
153
  return None
services/pipeline/builder.py CHANGED
@@ -17,7 +17,7 @@ from config.runtime import (
17
  )
18
  from models.depth import estimate_scene_geometry
19
  from models.loader import _load_intrinsic_model
20
- from models.segmentation import active_model_metadata, run_segmentation
21
  from services.debug.capture import PipelineDebugCapture
22
  from services.direction.analysis import floor_direction_geometry_inputs
23
  from services.floor.edge_coverage import scaled_odd_kernel_size
@@ -32,10 +32,10 @@ from services.lighting.shading import (
32
  lighting_map_statistics,
33
  )
34
  from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask
35
- from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment, build_wall_segment
36
  from services.pipeline import debug_stages
37
  from services.pipeline.inference_utils import downscale_for_inference
38
- from services.wall.components import wall_surface_components
39
  from direction_finder import find_floor_direction
40
  import state
41
  from state import FLOOR_SURFACE_CLASSES, PRIMARY_FLOOR_CLASSES, REPLACEABLE_SOFT_FLOOR_CLASSES, class_ids
@@ -55,7 +55,12 @@ _DEFAULT_MAPPING_META = {
55
  }
56
 
57
 
58
- def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None, progress_callback=None):
 
 
 
 
 
59
  t_start = time.perf_counter()
60
  d = debug # shorthand
61
  stage_times: list[tuple[str, float, str]] = [] # (stage_name, seconds, detail)
@@ -64,6 +69,24 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
64
  elapsed = time.perf_counter() - t0
65
  stage_times.append((name, elapsed, detail))
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  t0 = time.perf_counter()
68
  img = Image.open(io.BytesIO(contents)).convert("RGB")
69
  img_np = np.array(img)
@@ -113,10 +136,28 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
113
  progress_callback(PipelinePhase.SEGMENTATION, 100)
114
  progress_callback(PipelinePhase.GEOMETRY, 55)
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  # --- Encode room image in background (overlaps with masking + later stages) ---
117
- from concurrent.futures import ThreadPoolExecutor as _TP
118
- _img_pool = _TP(max_workers=1)
119
- _pixels_b64_future = _img_pool.submit(encode_bundle_image_data_url, img_np)
 
 
 
 
 
120
 
121
  # --- Floor masking (SAM2 removed — morphological cleanup only) ---
122
  if progress_callback:
@@ -249,29 +290,6 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
249
  # The semantic wall mask remains useful as a structural cue for floor
250
  # direction, even when wall surfaces are not emitted in the bundle.
251
  wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
252
- wall_components = []
253
- wall_protected_mask = None
254
- if ENABLE_WALL_SEGMENTS:
255
- t0 = time.perf_counter()
256
- wall_components, wall_protected_mask = wall_surface_components(
257
- seg_map, min_floor_area, geometry,
258
- )
259
- _log_stage("Wall Discovery", t0, f"components={len(wall_components)}")
260
-
261
- # --- Pre-compute wall lighting in parallel with floor direction ---
262
- # Wall lighting was previously computed inside build_wall_segment (in the
263
- # "Packaging" phase), adding ~5s for large images. Moving it here lets it
264
- # overlap with floor-direction detection.
265
- from concurrent.futures import ThreadPoolExecutor, Future
266
-
267
- def _compute_wall_lighting(component_mask):
268
- return build_luminance_lighting_maps(img_np, component_mask)
269
-
270
- wall_lighting_futures: list[Future] = []
271
- wall_executor = ThreadPoolExecutor(max_workers=max(1, len(wall_components))) if wall_components else None
272
- if wall_executor:
273
- for _, cm in wall_components:
274
- wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))
275
 
276
  if progress_callback:
277
  progress_callback(PipelinePhase.LIGHTING, 100)
@@ -309,16 +327,7 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
309
  if progress_callback:
310
  progress_callback(PipelinePhase.DIRECTION, 100)
311
 
312
- # Collect pre-computed wall lighting results
313
- wall_lighting_results: list[dict | None] = []
314
- if wall_executor:
315
- t0 = time.perf_counter()
316
- for fut in wall_lighting_futures:
317
- wall_lighting_results.append(fut.result())
318
- wall_executor.shutdown(wait=False)
319
- _log_stage("Wall Lighting Wait", t0, f"components={len(wall_components)}")
320
- else:
321
- wall_lighting_results = [None] * len(wall_components)
322
 
323
  # --- Package segments ---
324
  if progress_callback:
@@ -338,23 +347,22 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
338
  edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
339
  shade_statistics=shade_statistics, lighting_source=lighting_source,
340
  intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
341
- for wi, (_, cm) in enumerate(wall_components):
342
- ws = build_wall_segment(
343
- wi, cm, wall_protected_mask, geometry, img_np, wall_components, models,
344
- precomputed_lighting=wall_lighting_results[wi] if wi < len(wall_lighting_results) else None,
345
- )
346
- if ws:
347
- segments.append(ws)
348
  if not segments:
349
  segments = build_fallback_segments(seg_map, depth, models)
350
 
 
351
  if progress_callback:
352
  progress_callback(PipelinePhase.PACKAGING, 100)
353
- _log_stage("Packaging", t0, f"segments={len(segments)}")
354
- t0 = time.perf_counter()
355
- pixels_b64 = _pixels_b64_future.result()
356
- _img_pool.shutdown(wait=False)
357
- _log_stage("Image Encoding Wait", t0)
 
 
 
 
358
 
359
  total_elapsed = time.perf_counter() - t_start
360
  accounted_elapsed = sum(elapsed for _, elapsed, _ in stage_times)
@@ -384,6 +392,30 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
384
  "pipelineStages": pipeline_stages}
385
 
386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  def _print_pipeline_summary(
388
  stage_times: list[tuple[str, float, str]],
389
  total_elapsed: float,
 
17
  )
18
  from models.depth import estimate_scene_geometry
19
  from models.loader import _load_intrinsic_model
20
+ from models.segmentation import active_model_metadata, active_segmentation_model_name, run_segmentation
21
  from services.debug.capture import PipelineDebugCapture
22
  from services.direction.analysis import floor_direction_geometry_inputs
23
  from services.floor.edge_coverage import scaled_odd_kernel_size
 
32
  lighting_map_statistics,
33
  )
34
  from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask
35
+ from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment
36
  from services.pipeline import debug_stages
37
  from services.pipeline.inference_utils import downscale_for_inference
38
+ from services.wall.pipeline import WallResult, build_wall_segments
39
  from direction_finder import find_floor_direction
40
  import state
41
  from state import FLOOR_SURFACE_CLASSES, PRIMARY_FLOOR_CLASSES, REPLACEABLE_SOFT_FLOOR_CLASSES, class_ids
 
55
  }
56
 
57
 
58
+ def build_segmentation_bundle(
59
+ contents: bytes,
60
+ debug: PipelineDebugCapture | None = None,
61
+ progress_callback=None,
62
+ include_pixels: bool = True,
63
+ ):
64
  t_start = time.perf_counter()
65
  d = debug # shorthand
66
  stage_times: list[tuple[str, float, str]] = [] # (stage_name, seconds, detail)
 
69
  elapsed = time.perf_counter() - t0
70
  stage_times.append((name, elapsed, detail))
71
 
72
+ # Time job-progress updates so they show as their own report line instead
73
+ # of hiding inside "Pipeline Overhead". Every call below sits between
74
+ # timed stages, never inside one, so nothing is counted twice.
75
+ progress_elapsed = 0.0
76
+ progress_calls = 0
77
+ report_progress = progress_callback
78
+
79
+ def progress_callback(phase, phase_progress):
80
+ nonlocal progress_elapsed, progress_calls
81
+ if report_progress is None:
82
+ return
83
+ started = time.perf_counter()
84
+ try:
85
+ report_progress(phase, phase_progress)
86
+ finally:
87
+ progress_elapsed += time.perf_counter() - started
88
+ progress_calls += 1
89
+
90
  t0 = time.perf_counter()
91
  img = Image.open(io.BytesIO(contents)).convert("RGB")
92
  img_np = np.array(img)
 
136
  progress_callback(PipelinePhase.SEGMENTATION, 100)
137
  progress_callback(PipelinePhase.GEOMETRY, 55)
138
 
139
+ # --- Walls: one background thread, overlapping every floor stage below ---
140
+ # All wall work runs at working resolution (see services.wall.pipeline), so
141
+ # it normally finishes before the floor does and "Wall Wait" stays ~0.
142
+ wall_future = None
143
+ wall_pool = None
144
+ if ENABLE_WALL_SEGMENTS:
145
+ from concurrent.futures import ThreadPoolExecutor as _WallPool
146
+ wall_pool = _WallPool(max_workers=1, thread_name_prefix="walls")
147
+ wall_future = wall_pool.submit(
148
+ build_wall_segments, img_np, seg_map, geometry, min_floor_area,
149
+ active_segmentation_model_name(), 1,
150
+ )
151
+
152
  # --- Encode room image in background (overlaps with masking + later stages) ---
153
+ # Skipped for job conversions: the split vizbundle references the uploaded
154
+ # image by URL, so a full-resolution re-encode would be discarded.
155
+ _img_pool = None
156
+ _pixels_b64_future = None
157
+ if include_pixels:
158
+ from concurrent.futures import ThreadPoolExecutor as _TP
159
+ _img_pool = _TP(max_workers=1)
160
+ _pixels_b64_future = _img_pool.submit(encode_bundle_image_data_url, img_np)
161
 
162
  # --- Floor masking (SAM2 removed — morphological cleanup only) ---
163
  if progress_callback:
 
290
  # The semantic wall mask remains useful as a structural cue for floor
291
  # direction, even when wall surfaces are not emitted in the bundle.
292
  wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
  if progress_callback:
295
  progress_callback(PipelinePhase.LIGHTING, 100)
 
327
  if progress_callback:
328
  progress_callback(PipelinePhase.DIRECTION, 100)
329
 
330
+ walls = _collect_walls(wall_future, wall_pool, _log_stage)
 
 
 
 
 
 
 
 
 
331
 
332
  # --- Package segments ---
333
  if progress_callback:
 
347
  edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
348
  shade_statistics=shade_statistics, lighting_source=lighting_source,
349
  intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
350
+ segments.extend(walls.segments)
 
 
 
 
 
 
351
  if not segments:
352
  segments = build_fallback_segments(seg_map, depth, models)
353
 
354
+ _log_stage("Packaging", t0, f"segments={len(segments)}")
355
  if progress_callback:
356
  progress_callback(PipelinePhase.PACKAGING, 100)
357
+ pixels_b64 = None
358
+ if _pixels_b64_future is not None:
359
+ t0 = time.perf_counter()
360
+ pixels_b64 = _pixels_b64_future.result()
361
+ _img_pool.shutdown(wait=False)
362
+ _log_stage("Image Encoding Wait", t0)
363
+
364
+ if progress_calls:
365
+ stage_times.append(("Progress Updates", progress_elapsed, f"calls={progress_calls}"))
366
 
367
  total_elapsed = time.perf_counter() - t_start
368
  accounted_elapsed = sum(elapsed for _, elapsed, _ in stage_times)
 
392
  "pipelineStages": pipeline_stages}
393
 
394
 
395
+ def _collect_walls(wall_future, wall_pool, log_stage) -> WallResult:
396
+ """Wait for the background wall thread and log its cost.
397
+
398
+ "Wall Wait" is the only time walls add to the pipeline (the floor was
399
+ already done); its detail carries the walls' own (overlapped) timings.
400
+ A wall failure never fails the job: the floor ships without walls.
401
+ """
402
+ if wall_future is None:
403
+ return WallResult()
404
+ t0 = time.perf_counter()
405
+ try:
406
+ walls = wall_future.result()
407
+ except Exception as exc:
408
+ print(f"[WALLS] skipped: wall stage failed ({exc})", flush=True)
409
+ walls = WallResult()
410
+ finally:
411
+ wall_pool.shutdown(wait=False)
412
+ # Wall timings go in the detail, not as their own stages, because they
413
+ # overlapped the floor stages and would otherwise be counted twice.
414
+ log_stage("Wall Wait", t0, walls.detail)
415
+ print(f"[WALLS] {walls.detail}", flush=True)
416
+ return walls
417
+
418
+
419
  def _print_pipeline_summary(
420
  stage_times: list[tuple[str, float, str]],
421
  total_elapsed: float,
services/pipeline/bundle_assembly.py CHANGED
@@ -23,8 +23,6 @@ from config.runtime import (
23
  )
24
  from models.segmentation import segmenter_metadata_name
25
  from state import class_ids, class_name_for_id
26
- from services.lighting.shading import build_luminance_lighting_maps
27
- from services.wall.plane import estimate_wall_plane
28
  from enums import SurfaceType, TextureMappingMode
29
  from utils import encode_b64
30
 
@@ -133,59 +131,63 @@ def build_floor_segment(
133
 
134
 
135
  def build_wall_segment(
 
 
136
  wall_index: int,
137
- component_mask: np.ndarray,
138
- wall_protected_mask: np.ndarray,
139
- geometry: dict,
140
- img_np: np.ndarray,
141
- wall_components: list,
142
- models: dict,
143
- precomputed_lighting: dict | None = None,
144
- ) -> dict | None:
145
- wall_homography, wall_plane = estimate_wall_plane(component_mask, geometry)
146
- if wall_homography is None or wall_plane is None:
147
- return None
148
- wall_lighting_maps = precomputed_lighting if precomputed_lighting is not None else build_luminance_lighting_maps(img_np, component_mask)
149
- wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
150
- wall_occlusion_indices = np.flatnonzero(wall_protected_mask.ravel()).astype(np.uint32)
151
- wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
152
- wall_showroom = wall_lighting_maps.get("showroomShadeMap") if wall_lighting_maps else None
153
- wall_reflection = wall_lighting_maps.get("reflectionMap") if wall_lighting_maps else None
154
  return {
155
- "id": wall_index + 1,
156
  "className": SurfaceType.WALL,
157
  "surfaceType": SurfaceType.WALL,
158
  "mask": encode_b64(wall_indices),
159
- "occlusionMask": encode_b64(wall_occlusion_indices) if len(wall_occlusion_indices) else None,
160
- "homography": wall_homography,
161
- "floorTransform": wall_plane.get("floorTransform"),
162
- "surfaceTransform": wall_plane.get("surfaceTransform"),
163
- "plane": wall_plane,
 
 
 
 
164
  "surfaceUv": None,
165
  "surfacePlaneIds": None,
166
  "surfacePlanes": None,
167
- "shadeMap": wall_shade_map,
168
- "showroomShadeMap": wall_showroom,
169
- "reflectionMap": wall_reflection,
170
  "metadata": {
171
  "segmenter": segmenter_metadata_name(),
172
- "segmentationModel": models["segmentation"]["name"],
173
- "wallPixels": int(component_mask.sum()),
174
  "wallComponent": wall_index,
175
- "wallComponentCount": len(wall_components),
176
- "protectedPixels": int(wall_protected_mask.sum()),
177
- "shadingEnabled": wall_shade_map is not None,
178
- "reflectionTransferEnabled": wall_reflection is not None,
179
- "textureMappingMode": (
180
- TextureMappingMode.WALL_PLANE if wall_plane.get("surfaceTransform") else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY
181
- ),
182
- "geometryConfidence": wall_plane.get("geometryConfidence", 0.0),
183
- "geometryProvider": wall_plane.get("geometryProvider"),
184
- "surfaceWidthMeters": wall_plane.get("surfaceWidthMeters"),
185
- "surfaceHeightMeters": wall_plane.get("surfaceHeightMeters"),
186
  "lightingTransferVersion": LIGHTING_TRANSFER_VERSION,
187
  "shadeMapEncoding": SHADE_MAP_ENCODING,
188
  "shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX],
 
 
 
 
189
  "showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX],
190
  "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX],
191
  },
 
23
  )
24
  from models.segmentation import segmenter_metadata_name
25
  from state import class_ids, class_name_for_id
 
 
26
  from enums import SurfaceType, TextureMappingMode
27
  from utils import encode_b64
28
 
 
131
 
132
 
133
  def build_wall_segment(
134
+ *,
135
+ wall_id: int,
136
  wall_index: int,
137
+ wall_indices: np.ndarray,
138
+ homography,
139
+ plane: dict,
140
+ lighting_maps: dict | None,
141
+ segmentation_model: str,
142
+ ) -> dict:
143
+ """Bundle dict for one wall. All heavy inputs are prepared by services.wall.pipeline,
144
+ which also sets metadata["wallComponentCount"] once every wall is built."""
145
+ shade_map = lighting_maps.get("shadeMap") if lighting_maps else None
146
+ showroom_shade_map = lighting_maps.get("showroomShadeMap") if lighting_maps else None
147
+ reflection_map = lighting_maps.get("reflectionMap") if lighting_maps else None
148
+ mapping_mode = (
149
+ TextureMappingMode.WALL_PLANE if plane.get("surfaceTransform")
150
+ else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY
151
+ )
 
 
152
  return {
153
+ "id": wall_id,
154
  "className": SurfaceType.WALL,
155
  "surfaceType": SurfaceType.WALL,
156
  "mask": encode_b64(wall_indices),
157
+ # Wall masks already exclude (dilated) doors, windows and furniture, so
158
+ # a separate occlusion mask would only duplicate that cut-out.
159
+ "occlusionMask": None,
160
+ "homography": homography,
161
+ "floorTransform": plane.get("floorTransform"),
162
+ "surfaceTransform": plane.get("surfaceTransform"),
163
+ "plane": plane,
164
+ # A wall is one plane: its exact pixel -> metres mapping is the 3x3
165
+ # surfaceTransform, so no per-pixel UV arrays are shipped.
166
  "surfaceUv": None,
167
  "surfacePlaneIds": None,
168
  "surfacePlanes": None,
169
+ "shadeMap": shade_map,
170
+ "showroomShadeMap": showroom_shade_map,
171
+ "reflectionMap": reflection_map,
172
  "metadata": {
173
  "segmenter": segmenter_metadata_name(),
174
+ "segmentationModel": segmentation_model,
175
+ "wallPixels": int(len(wall_indices)),
176
  "wallComponent": wall_index,
177
+ "shadingEnabled": shade_map is not None,
178
+ "reflectionTransferEnabled": reflection_map is not None,
179
+ "textureMappingMode": mapping_mode,
180
+ "geometryConfidence": plane.get("geometryConfidence", 0.0),
181
+ "geometryProvider": plane.get("geometryProvider"),
182
+ "surfaceWidthMeters": plane.get("surfaceWidthMeters"),
183
+ "surfaceHeightMeters": plane.get("surfaceHeightMeters"),
 
 
 
 
184
  "lightingTransferVersion": LIGHTING_TRANSFER_VERSION,
185
  "shadeMapEncoding": SHADE_MAP_ENCODING,
186
  "shadeMapRange": [SHADE_MAP_MIN, SHADE_MAP_MAX],
187
+ "shadeMapSize": (
188
+ [int(shade_map.shape[1]), int(shade_map.shape[0])]
189
+ if shade_map is not None else None
190
+ ),
191
  "showroomShadeMapRange": [SHOWROOM_SHADE_MAP_MIN, SHOWROOM_SHADE_MAP_MAX],
192
  "reflectionMapRange": [REFLECTION_MAP_MIN, REFLECTION_MAP_MAX],
193
  },
services/wall/components.py CHANGED
@@ -1,92 +1,323 @@
1
- """Wall surface connected-component extraction.
2
 
3
  Functions
4
  ---------
5
- wall_surface_components - segment wall mask into independently renderable regions
 
 
 
 
 
 
6
  """
7
 
 
 
 
 
 
8
  import cv2
9
  import numpy as np
10
 
11
- from config.surface import SURFACE_MIN_PLANE_PIXELS
12
- from services.geometry.multi_plane import (
13
- assign_points_to_surface_planes,
14
- fit_multi_surface_planes,
15
- geometry_point_maps,
 
 
 
 
 
 
16
  )
17
- from services.geometry.normals import normalize_vectors
18
- from state import OCCLUDER_CLASSES, class_ids
 
 
 
 
19
  from utils import seg_class_mask
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None):
23
- """Create clean, independently renderable wall regions.
24
 
25
- Semantic wall predictions often bridge across corners and openings. Removing
26
- protected classes before connected-component analysis prevents one warped
27
- transform from being applied to several physically different walls.
28
- """
29
- wall = seg_class_mask(seg_map, class_ids({"wall"}))
30
- protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | {
31
- "door", "window", "column", "base", "railing", "ceiling",
32
- "building", "painting", "mirror", "curtain",
33
- }))
34
- radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
36
  protected = cv2.dilate(protected, kernel, iterations=1)
37
  wall[protected > 0] = 0
38
  wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel)
39
  wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
40
  wall[protected > 0] = 0
 
41
 
42
- components = []
43
- if geometry is not None:
44
- maps = geometry_point_maps(wall, geometry)
45
- if maps is not None:
46
- valid = maps["validMask"] & (wall > 0)
47
- ys, xs = np.where(valid)
48
- if len(xs) >= SURFACE_MIN_PLANE_PIXELS:
49
- points = maps["points"][ys, xs].astype(np.float32)
50
- normals = maps["normals"][ys, xs].astype(np.float32)
51
- finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1)
52
- points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite]
53
- if len(points) >= SURFACE_MIN_PLANE_PIXELS:
54
- normals_reliable = np.linalg.norm(normals, axis=1) > 1e-4
55
- if normals_reliable.sum() >= SURFACE_MIN_PLANE_PIXELS:
56
- points = points[normals_reliable]
57
- normals = normalize_vectors(normals[normals_reliable])
58
- ys, xs = ys[normals_reliable], xs[normals_reliable]
59
- planes = fit_multi_surface_planes(points, normals, True)
60
- wall_planes = [
61
- plane for plane in planes
62
- if abs(float(plane["normal"][1])) <= 0.45
63
- ]
64
- if wall_planes:
65
- assignment = assign_points_to_surface_planes(
66
- points, normals, wall_planes, True
67
- )
68
- for plane_index in range(len(wall_planes)):
69
- selected = assignment == plane_index
70
- if int(selected.sum()) < min_area:
71
- continue
72
- plane_mask = np.zeros_like(wall)
73
- plane_mask[ys[selected], xs[selected]] = 1
74
- count, labels, stats, _ = cv2.connectedComponentsWithStats(
75
- plane_mask, connectivity=8
76
- )
77
- for component_id in range(1, count):
78
- area = int(stats[component_id, cv2.CC_STAT_AREA])
79
- if area >= min_area:
80
- components.append((area, (labels == component_id).astype(np.uint8)))
81
-
82
- # Geometry can be unavailable or too noisy. In that case retain the safe
83
- # semantic connected-component fallback instead of emitting no walls.
84
- if not components:
85
- count, labels, stats, _ = cv2.connectedComponentsWithStats(wall, connectivity=8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  for component_id in range(1, count):
87
- area = int(stats[component_id, cv2.CC_STAT_AREA])
88
- if area < min_area:
89
  continue
90
- components.append((area, (labels == component_id).astype(np.uint8)))
91
- components.sort(key=lambda item: item[0], reverse=True)
92
- return components, protected
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wall discovery: split the semantic wall mask into one region per physical wall.
2
 
3
  Functions
4
  ---------
5
+ discover_wall_components - wall regions (full-res masks + fitted planes) for a room
6
+
7
+ Splitting and plane fitting run on a strided copy of the segmentation and
8
+ geometry maps (long side <= WALL_WORK_MAX_DIMENSION). Each wall's final
9
+ outline, like the floor's, comes from the full-resolution segmentation; the
10
+ low-resolution pieces only decide which wall owns each pixel. Walls use their
11
+ own plane budget (WALL_MAX_PLANES), so the floor's `max_planes` is never touched.
12
  """
13
 
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from dataclasses import dataclass
18
+
19
  import cv2
20
  import numpy as np
21
 
22
+ from config.models import DEPTH_MODEL_NAME
23
+ from config.surface import (
24
+ SURFACE_MIN_PLANE_PIXELS,
25
+ SURFACE_NORMAL_SMOOTHING_KERNEL,
26
+ WALL_COPLANAR_ANGLE_DEGREES,
27
+ WALL_COPLANAR_OFFSET_METERS,
28
+ WALL_EDGE_STRAIGHTEN_RATIO,
29
+ WALL_MAX_NORMAL_Y,
30
+ WALL_MAX_PLANES,
31
+ WALL_MAX_SEGMENTS,
32
+ WALL_WORK_MAX_DIMENSION,
33
  )
34
+ from services.geometry.camera import backproject_depth, pixel_intrinsics_from_model
35
+ from services.geometry.multi_plane import assign_points_to_surface_planes, fit_multi_surface_planes
36
+ from services.geometry.normals import compute_normals_from_points, normalize_vectors, smooth_normal_map
37
+ from services.geometry.plane_fitting import refine_plane
38
+ from services.image.polygons import straighten_mask_edges
39
+ from state import OCCLUDER_CLASSES, PRIMARY_FLOOR_CLASSES, class_ids
40
  from utils import seg_class_mask
41
 
42
+ # Classes cut out of walls before splitting; they bridge physically separate walls.
43
+ WALL_PROTECTED_CLASSES = OCCLUDER_CLASSES | {
44
+ "door", "window", "column", "base", "railing", "ceiling",
45
+ "building", "painting", "mirror", "curtain",
46
+ }
47
+ # Morphology radius as a fraction of the short image side (matches the old full-res value).
48
+ # Only used to separate walls at working resolution, never to cut the final outline.
49
+ PROTECTED_DILATION_RATIO = 0.006
50
+ # Light speck cleanup of the full-resolution outline (fraction of the short side).
51
+ OUTLINE_CLEANUP_RATIO = 0.002
52
+ # Wall ownership is taken from pieces blurred by this many working-res pixels per
53
+ # dilation radius, so the separation margin is filled and wall seams are smooth.
54
+ OWNERSHIP_SIGMA_SCALE = 1.5
55
+ OWNERSHIP_MIN_WEIGHT = 0.02
56
+ # Points sampled when refitting each wall's final plane.
57
+ PLANE_REFIT_SAMPLES = 20000
58
+ MIN_DEPTH_METERS = 0.05
59
 
 
 
60
 
61
+ @dataclass(frozen=True)
62
+ class WallPlane:
63
+ origin: np.ndarray
64
+ normal: np.ndarray
65
+
66
+
67
+ @dataclass
68
+ class WallComponent:
69
+ mask: np.ndarray # full-resolution uint8 mask
70
+ work_mask: np.ndarray # same wall at working resolution
71
+ plane: WallPlane | None
72
+ area: int # full-resolution pixel count
73
+
74
+
75
+ @dataclass
76
+ class WallDiscovery:
77
+ components: list[WallComponent]
78
+ vertical: np.ndarray # unit "up" direction (camera +Y hemisphere) from the floor
79
+ stride: int
80
+ geometry_used: bool
81
+
82
+
83
+ def discover_wall_components(seg_map: np.ndarray, geometry: dict | None, min_area: int) -> WallDiscovery:
84
+ """Find up to WALL_MAX_SEGMENTS walls, ordered left to right."""
85
+ full_h, full_w = seg_map.shape[:2]
86
+ stride = max(1, math.ceil(max(full_h, full_w) / WALL_WORK_MAX_DIMENSION))
87
+ seg_low = seg_map[::stride, ::stride]
88
+ min_area_low = max(1, min_area // (stride * stride))
89
+
90
+ wall_low = _clean_wall_mask(seg_low)
91
+ point_maps = _working_point_maps(geometry, stride, full_w, full_h)
92
+ vertical = _vertical_reference(seg_low, point_maps)
93
+
94
+ pieces: list[tuple[np.ndarray, WallPlane | None]] = []
95
+ count, labels, stats, _ = cv2.connectedComponentsWithStats(wall_low, connectivity=8)
96
+ for region_id in range(1, count):
97
+ if int(stats[region_id, cv2.CC_STAT_AREA]) < min_area_low:
98
+ continue
99
+ region = labels == region_id
100
+ pieces.extend(_split_region(region, point_maps, min_area_low))
101
+
102
+ pieces.sort(key=lambda piece: int(piece[0].sum()), reverse=True)
103
+ pieces = pieces[:WALL_MAX_SEGMENTS]
104
+ pieces.sort(key=lambda piece: float(np.nonzero(piece[0])[1].mean()))
105
+
106
+ wall_full = _full_resolution_wall_mask(seg_map)
107
+ owner = _wall_owner_map([piece for piece, _ in pieces], seg_low.shape, full_w, full_h)
108
+ tolerance = WALL_EDGE_STRAIGHTEN_RATIO * min(full_h, full_w)
109
+ claimed = np.zeros((full_h, full_w), dtype=bool)
110
+ components = []
111
+ for index, (work_mask, plane) in enumerate(pieces):
112
+ mask = ((owner == index) & wall_full).astype(np.uint8)
113
+ # Architectural edges are straight: redraw the outline as lines. Where two
114
+ # straightened walls overlap at a corner, the earlier wall keeps the pixels.
115
+ mask = straighten_mask_edges(mask, tolerance, min_area=(2.0 * tolerance) ** 2)
116
+ mask[claimed] = 0
117
+ area = int(mask.sum())
118
+ if area < min_area:
119
+ continue
120
+ claimed |= mask > 0
121
+ components.append(WallComponent(mask=mask, work_mask=work_mask.astype(np.uint8), plane=plane, area=area))
122
+
123
+ return WallDiscovery(
124
+ components=components,
125
+ vertical=vertical,
126
+ stride=stride,
127
+ geometry_used=point_maps is not None,
128
+ )
129
+
130
+
131
+ def _clean_wall_mask(seg_low: np.ndarray) -> np.ndarray:
132
+ """Working-res wall mask with protected classes cut out (with a margin, so
133
+ walls touching only across a door or column separate)."""
134
+ wall = seg_class_mask(seg_low, class_ids({"wall"}))
135
+ protected = seg_class_mask(seg_low, class_ids(WALL_PROTECTED_CLASSES))
136
+ radius = max(1, int(round(min(seg_low.shape[:2]) * PROTECTED_DILATION_RATIO)))
137
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
138
  protected = cv2.dilate(protected, kernel, iterations=1)
139
  wall[protected > 0] = 0
140
  wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel)
141
  wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
142
  wall[protected > 0] = 0
143
+ return wall
144
 
145
+
146
+ def _working_point_maps(geometry: dict | None, stride: int, full_w: int, full_h: int):
147
+ """Strided (points, normals, valid) maps, or None when there is no metric geometry."""
148
+ if geometry is None:
149
+ return None
150
+ points = geometry.get("points")
151
+ if points is not None:
152
+ points = points[::stride, ::stride].astype(np.float32, copy=False)
153
+ valid = geometry.get("validMask")
154
+ valid = valid[::stride, ::stride].astype(bool) if valid is not None else np.ones(points.shape[:2], bool)
155
+ else:
156
+ depth = geometry.get("depth")
157
+ provider = str(geometry.get("provider") or "")
158
+ if depth is None or ("metric" not in DEPTH_MODEL_NAME.lower() and "metric" not in provider.lower()):
159
+ return None
160
+ depth = depth[::stride, ::stride].astype(np.float32)
161
+ intrinsics = pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h).copy()
162
+ intrinsics[:2, :] /= stride
163
+ points = backproject_depth(depth, intrinsics)
164
+ valid = np.ones(depth.shape, bool)
165
+
166
+ valid &= np.isfinite(points).all(axis=2) & (points[:, :, 2] > MIN_DEPTH_METERS)
167
+ if not valid.any():
168
+ return None
169
+
170
+ normals = geometry.get("normals")
171
+ if normals is not None and normals.shape[:2] == (full_h, full_w):
172
+ normals = smooth_normal_map(normals[::stride, ::stride], SURFACE_NORMAL_SMOOTHING_KERNEL)
173
+ else:
174
+ normals = compute_normals_from_points(points, valid, SURFACE_NORMAL_SMOOTHING_KERNEL)
175
+ valid &= np.linalg.norm(normals, axis=2) > 1e-4
176
+ return points, normals, valid
177
+
178
+
179
+ def _vertical_reference(seg_low: np.ndarray, point_maps) -> np.ndarray:
180
+ """Room "up" axis from floor normals, oriented like camera +Y (the renderer's v)."""
181
+ fallback = np.array([0.0, 1.0, 0.0], dtype=np.float32)
182
+ if point_maps is None:
183
+ return fallback
184
+ _, normals, valid = point_maps
185
+ floor = (seg_class_mask(seg_low, class_ids(PRIMARY_FLOOR_CLASSES)) > 0) & valid
186
+ if int(floor.sum()) < SURFACE_MIN_PLANE_PIXELS // 4:
187
+ return fallback
188
+ up = np.median(normals[floor], axis=0).astype(np.float32)
189
+ length = float(np.linalg.norm(up))
190
+ if length < 1e-4:
191
+ return fallback
192
+ up /= length
193
+ return up if up[1] >= 0 else -up
194
+
195
+
196
+ def _split_region(region: np.ndarray, point_maps, min_area_low: int) -> list[tuple[np.ndarray, WallPlane | None]]:
197
+ """Split one connected wall region into per-plane pieces."""
198
+ if point_maps is None:
199
+ return [(region, None)]
200
+ points_map, normals_map, valid_map = point_maps
201
+ valid = region & valid_map
202
+ ys, xs = np.nonzero(valid)
203
+ if len(ys) < SURFACE_MIN_PLANE_PIXELS:
204
+ return [(region, None)]
205
+ points = points_map[ys, xs]
206
+ normals = normalize_vectors(normals_map[ys, xs])
207
+
208
+ planes = fit_multi_surface_planes(points, normals, True, max_planes=WALL_MAX_PLANES)
209
+ planes = _merge_coplanar([p for p in planes if abs(float(p["normal"][1])) <= WALL_MAX_NORMAL_Y])
210
+ if len(planes) <= 1:
211
+ return [(region, _refit_plane(points, normals))]
212
+
213
+ assignment = assign_points_to_surface_planes(points, normals, planes, True)
214
+ labels = np.full(region.shape, -1, dtype=np.int32)
215
+ labels[ys, xs] = assignment
216
+ _fill_unassigned(labels, region)
217
+
218
+ pieces = []
219
+ for plane_index in range(len(planes)):
220
+ count, components, stats, _ = cv2.connectedComponentsWithStats(
221
+ (labels == plane_index).astype(np.uint8), connectivity=8,
222
+ )
223
  for component_id in range(1, count):
224
+ if int(stats[component_id, cv2.CC_STAT_AREA]) < min_area_low:
 
225
  continue
226
+ piece = components == component_id
227
+ piece_valid = piece & valid_map
228
+ pieces.append((piece, _refit_plane(points_map[piece_valid], normals_map[piece_valid])))
229
+ return pieces or [(region, _refit_plane(points, normals))]
230
+
231
+
232
+ def _merge_coplanar(planes: list[dict]) -> list[dict]:
233
+ """Drop planes that describe the same flat wall as a larger plane already kept."""
234
+ min_cos = float(np.cos(np.deg2rad(WALL_COPLANAR_ANGLE_DEGREES)))
235
+ kept: list[dict] = []
236
+ for plane in sorted(planes, key=lambda p: p["inlierCount"], reverse=True):
237
+ normal = np.asarray(plane["normal"], dtype=np.float32)
238
+ origin = np.asarray(plane["origin"], dtype=np.float32)
239
+ duplicate = any(
240
+ abs(float(normal @ k["normal"])) >= min_cos
241
+ and abs(float((origin - k["origin"]) @ k["normal"])) <= WALL_COPLANAR_OFFSET_METERS
242
+ for k in kept
243
+ )
244
+ if not duplicate:
245
+ kept.append(plane)
246
+ return kept
247
+
248
+
249
+ def _fill_unassigned(labels: np.ndarray, region: np.ndarray) -> None:
250
+ """Give region pixels without valid geometry the label of their nearest labelled neighbour."""
251
+ kernel = np.ones((3, 3), np.uint8)
252
+ unassigned = region & (labels < 0)
253
+ while unassigned.any():
254
+ grown = False
255
+ for label in np.unique(labels[labels >= 0]):
256
+ reach = cv2.dilate((labels == label).astype(np.uint8), kernel) > 0
257
+ take = reach & unassigned
258
+ if take.any():
259
+ labels[take] = label
260
+ unassigned &= ~take
261
+ grown = True
262
+ if not grown:
263
+ break
264
+
265
+
266
+ def _refit_plane(points: np.ndarray, normals: np.ndarray) -> WallPlane | None:
267
+ """Least-squares plane over a wall's own points (subsampled), or None if not wall-like."""
268
+ finite = np.isfinite(points).all(axis=1)
269
+ points, normals = points[finite], normals[finite]
270
+ if len(points) < SURFACE_MIN_PLANE_PIXELS // 4:
271
+ return None
272
+ if len(points) > PLANE_REFIT_SAMPLES:
273
+ step = len(points) // PLANE_REFIT_SAMPLES
274
+ points, normals = points[::step], normals[::step]
275
+ origin, normal = refine_plane(points, normals)
276
+ if abs(float(normal[1])) > WALL_MAX_NORMAL_Y:
277
+ return None
278
+ return WallPlane(origin=origin.astype(np.float32), normal=normal.astype(np.float32))
279
+
280
+
281
+ def _full_resolution_wall_mask(seg_map: np.ndarray) -> np.ndarray:
282
+ """Wall pixels at full resolution with protected classes cut out exactly.
283
+
284
+ Mirrors the floor: the outline follows the (smoothly upsampled) semantic
285
+ boundary, with only light speck cleanup and no widened margin around
286
+ doors, ceilings or furniture.
287
+ """
288
+ wall = seg_class_mask(seg_map, class_ids({"wall"}))
289
+ protected = seg_class_mask(seg_map, class_ids(WALL_PROTECTED_CLASSES)) > 0
290
+ wall[protected] = 0
291
+ radius = max(1, int(round(min(seg_map.shape[:2]) * OUTLINE_CLEANUP_RATIO)))
292
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
293
+ wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
294
+ wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel)
295
+ wall[protected] = 0
296
+ return wall > 0
297
+
298
+
299
+ def _wall_owner_map(
300
+ pieces: list[np.ndarray],
301
+ work_shape: tuple[int, int],
302
+ full_w: int,
303
+ full_h: int,
304
+ ) -> np.ndarray:
305
+ """Full-resolution index of the wall piece each pixel belongs to (-1 for none).
306
+
307
+ Each piece is blurred at working resolution so its influence reaches across
308
+ the separation margin cut around doors; the argmax then places seams
309
+ between neighbouring walls midway and, after linear upscaling, smoothly.
310
+ """
311
+ owner = np.full((full_h, full_w), -1, dtype=np.int8)
312
+ if not pieces:
313
+ return owner
314
+ radius = max(1, int(round(min(work_shape) * PROTECTED_DILATION_RATIO)))
315
+ sigma = max(1.0, radius * OWNERSHIP_SIGMA_SCALE)
316
+ best = np.full((full_h, full_w), OWNERSHIP_MIN_WEIGHT, dtype=np.float32)
317
+ for index, piece in enumerate(pieces):
318
+ weight = cv2.GaussianBlur(piece.astype(np.float32), (0, 0), sigmaX=sigma, sigmaY=sigma)
319
+ weight = cv2.resize(weight, (full_w, full_h), interpolation=cv2.INTER_LINEAR)
320
+ wins = weight > best
321
+ best[wins] = weight[wins]
322
+ owner[wins] = index
323
+ return owner
services/wall/pipeline.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wall stage of the conversion pipeline: one bundle segment per physical wall.
2
+
3
+ Functions
4
+ ---------
5
+ build_wall_segments - discover walls and build their bundle segments
6
+
7
+ Designed to run in a background thread alongside the floor stages: all
8
+ analysis is at working resolution, and full-resolution work is limited to
9
+ each wall's own pixels (mask upscale, index encoding). Each wall's texture
10
+ mapping is an exact 3x3 plane transform, so no per-pixel UV is shipped.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import time
16
+ from dataclasses import dataclass, field
17
+
18
+ import cv2
19
+ import numpy as np
20
+
21
+ from config.runtime import ENABLE_FAST_SHADOW_TRANSFER, ENABLE_SHADING_TRANSFER
22
+ from config.surface import WALL_UV_MIN_COVERAGE
23
+ from services.geometry.camera import pixel_intrinsics_from_model
24
+ from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis
25
+ from services.lighting.shading import build_fast_shadow_lighting_maps, build_luminance_lighting_maps
26
+ from services.pipeline.bundle_assembly import build_wall_segment
27
+ from services.wall.components import WallComponent, WallDiscovery, discover_wall_components
28
+ from services.wall.plane import estimate_wall_plane
29
+
30
+ # Pixels sampled per wall to measure plane coverage and size.
31
+ MAPPING_SAMPLE_PIXELS = 20000
32
+
33
+
34
+ @dataclass
35
+ class WallResult:
36
+ segments: list[dict] = field(default_factory=list)
37
+ timings_ms: dict[str, float] = field(default_factory=dict)
38
+
39
+ @property
40
+ def detail(self) -> str:
41
+ parts = [f"walls={len(self.segments)}"]
42
+ parts += [f"{name}={ms:.0f}ms" for name, ms in self.timings_ms.items()]
43
+ return " ".join(parts)
44
+
45
+
46
+ def build_wall_segments(
47
+ img_np: np.ndarray,
48
+ seg_map: np.ndarray,
49
+ geometry: dict | None,
50
+ min_area: int,
51
+ segmentation_model: str,
52
+ first_segment_id: int = 1,
53
+ ) -> WallResult:
54
+ """Discover walls and return their bundle segments (ids start at first_segment_id)."""
55
+ result = WallResult()
56
+ started = time.perf_counter()
57
+ discovery = discover_wall_components(seg_map, geometry, min_area)
58
+ result.timings_ms["discovery"] = (time.perf_counter() - started) * 1000
59
+ if not discovery.components:
60
+ return result
61
+
62
+ started = time.perf_counter()
63
+ full_h, full_w = seg_map.shape[:2]
64
+ intrinsics = (
65
+ pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h)
66
+ if geometry is not None else None
67
+ )
68
+ work_h, work_w = discovery.components[0].work_mask.shape[:2]
69
+ work_image = cv2.resize(img_np, (work_w, work_h), interpolation=cv2.INTER_AREA)
70
+
71
+ for index, component in enumerate(discovery.components):
72
+ segment = _build_segment(
73
+ component,
74
+ discovery,
75
+ index=index,
76
+ segment_id=first_segment_id + index,
77
+ intrinsics=intrinsics,
78
+ geometry=geometry,
79
+ img_np=img_np,
80
+ work_image=work_image,
81
+ segmentation_model=segmentation_model,
82
+ )
83
+ if segment is not None:
84
+ result.segments.append(segment)
85
+ for segment in result.segments:
86
+ segment["metadata"]["wallComponentCount"] = len(result.segments)
87
+ result.timings_ms["segments"] = (time.perf_counter() - started) * 1000
88
+ return result
89
+
90
+
91
+ def _build_segment(
92
+ component: WallComponent,
93
+ discovery: WallDiscovery,
94
+ *,
95
+ index: int,
96
+ segment_id: int,
97
+ intrinsics: np.ndarray | None,
98
+ geometry: dict | None,
99
+ img_np: np.ndarray,
100
+ work_image: np.ndarray,
101
+ segmentation_model: str,
102
+ ) -> dict | None:
103
+ wall_indices = np.flatnonzero(component.mask.ravel()).astype(np.uint32)
104
+ mapping = _wall_plane_mapping(component, discovery.vertical, wall_indices, intrinsics)
105
+
106
+ # With an exact plane mapping, skip estimate_wall_plane's second RANSAC fit
107
+ # and keep only its cheap contour quad as a fallback homography.
108
+ homography, plane = estimate_wall_plane(component.mask, None if mapping else geometry)
109
+ if homography is None or plane is None:
110
+ return None
111
+ if mapping:
112
+ plane.update(mapping)
113
+ plane["geometryProvider"] = (geometry or {}).get("provider")
114
+
115
+ return build_wall_segment(
116
+ wall_id=segment_id,
117
+ wall_index=index,
118
+ wall_indices=wall_indices,
119
+ homography=homography,
120
+ plane=plane,
121
+ lighting_maps=_wall_lighting(component, img_np, work_image),
122
+ segmentation_model=segmentation_model,
123
+ )
124
+
125
+
126
+ def _wall_plane_mapping(
127
+ component: WallComponent,
128
+ vertical: np.ndarray,
129
+ wall_indices: np.ndarray,
130
+ intrinsics: np.ndarray | None,
131
+ ) -> dict | None:
132
+ """Exact metric plane mapping for the wall, or None to use the contour homography.
133
+
134
+ Coverage and the wall's size in metres are measured on a pixel sample; the
135
+ renderer gets the 3x3 surfaceTransform, which is exact for every pixel.
136
+ """
137
+ if component.plane is None or intrinsics is None or not len(wall_indices):
138
+ return None
139
+ u_axis, v_axis = upright_plane_basis(component.plane.normal, vertical)
140
+ sample = wall_indices[:: max(1, len(wall_indices) // MAPPING_SAMPLE_PIXELS)]
141
+ uv, hit = ray_plane_uv(
142
+ sample, component.mask.shape[1], intrinsics,
143
+ component.plane.origin, component.plane.normal, u_axis, v_axis,
144
+ )
145
+ coverage = float(hit.mean())
146
+ if coverage < WALL_UV_MIN_COVERAGE:
147
+ return None
148
+
149
+ uv_min = np.nanmin(uv, axis=0)
150
+ uv_max = np.nanmax(uv, axis=0)
151
+ transform = plane_to_image_transform(
152
+ intrinsics, component.plane.origin, component.plane.normal, u_axis, v_axis,
153
+ ).flatten().tolist()
154
+ return {
155
+ "floorTransform": transform,
156
+ "surfaceTransform": transform,
157
+ "surfaceUAxis": u_axis.astype(float).tolist(),
158
+ "surfaceVAxis": v_axis.astype(float).tolist(),
159
+ "planeNormal": component.plane.normal.astype(float).tolist(),
160
+ "planeOrigin": component.plane.origin.astype(float).tolist(),
161
+ "surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)),
162
+ "surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)),
163
+ # The renderer treats the transform as metric at >= 0.35 confidence.
164
+ "geometryConfidence": coverage,
165
+ }
166
+
167
+
168
+ def _wall_lighting(component: WallComponent, img_np: np.ndarray, work_image: np.ndarray) -> dict | None:
169
+ """Same lighting switches as the floor; the fast path runs at working resolution."""
170
+ if ENABLE_FAST_SHADOW_TRANSFER:
171
+ maps = build_fast_shadow_lighting_maps(work_image, component.work_mask)
172
+ if maps and maps.get("shadeMap") is not None:
173
+ return maps
174
+ if ENABLE_SHADING_TRANSFER:
175
+ return build_luminance_lighting_maps(img_np, component.mask)
176
+ return None
state.py CHANGED
@@ -1,10 +1,24 @@
1
  """Mutable global model state and semantic class definitions."""
2
 
3
  import os
 
 
 
4
  import torch
5
 
6
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
 
 
 
 
 
 
 
 
 
 
 
 
8
  # Model references (populated lazily by models/loader.py)
9
  seg_processor = None
10
  seg_model = None
 
1
  """Mutable global model state and semantic class definitions."""
2
 
3
  import os
4
+ import threading
5
+ from contextlib import nullcontext
6
+
7
  import torch
8
 
9
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
 
11
+ # Serialises model inference on the single GPU while letting the CPU-bound
12
+ # pipeline stages of concurrent jobs overlap. Re-entrant so nested calls
13
+ # (e.g. warm-up -> run_segmentation) are safe.
14
+ _gpu_inference_lock = threading.RLock()
15
+
16
+
17
+ def gpu_inference():
18
+ """Context manager guarding GPU model calls; a no-op on CPU, where the
19
+ pipeline deliberately runs segmentation and geometry in parallel."""
20
+ return _gpu_inference_lock if device.type == "cuda" else nullcontext()
21
+
22
  # Model references (populated lazily by models/loader.py)
23
  seg_processor = None
24
  seg_model = None
test_wall_segments.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wall segmentation: one segment per physical wall, floor plane budget untouched, fast.
2
+
3
+ Run from backend/floor-visualizer: python -m unittest test_wall_segments
4
+ Uses the GPU profile so the floor's max_planes (1) is the production value.
5
+ """
6
+
7
+ import base64
8
+ import os
9
+ import time
10
+ import unittest
11
+
12
+ os.environ.setdefault("VISUALIZER_CONFIG", "visualizer.gpu.toml")
13
+
14
+ import cv2 # noqa: E402
15
+ import numpy as np # noqa: E402
16
+
17
+ from config.surface import SURFACE_MAX_PLANES, WALL_MAX_PLANES # noqa: E402
18
+ from services.geometry.multi_plane import fit_multi_surface_planes # noqa: E402
19
+ from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis # noqa: E402
20
+ from services.wall.components import discover_wall_components # noqa: E402
21
+ from services.wall.pipeline import build_wall_segments # noqa: E402
22
+ from state import class_ids # noqa: E402
23
+
24
+ WIDTH, HEIGHT = 1920, 1440
25
+ FOCAL = 1400.0
26
+ INTRINSICS = np.array([[FOCAL, 0, (WIDTH - 1) / 2], [0, FOCAL, (HEIGHT - 1) / 2], [0, 0, 1]], np.float32)
27
+ FLOOR_ID = class_ids({"floor"})[0]
28
+ WALL_ID = class_ids({"wall"})[0]
29
+ CEILING_ID = class_ids({"ceiling"})[0]
30
+ DOOR_ID = class_ids({"door"})[0]
31
+ # Wall budget for the whole test run: generous for a CI CPU, well under the
32
+ # ~3s of floor CPU stages the wall thread overlaps with in production.
33
+ WALL_TIME_BUDGET_SECONDS = 1.5
34
+
35
+
36
+ def synthetic_room(walls=("left", "back", "right")):
37
+ """Camera inside a box room, OpenCV axes (x right, y down, z forward).
38
+
39
+ Returns (seg_map, geometry, labels) with MoGe-style full-res points/normals.
40
+ labels: 0 floor, 1 ceiling, 2+ walls in the order given.
41
+ """
42
+ planes = [ # (normal pointing into the room, offset d) for n.p + d = 0
43
+ (np.array([0, -1, 0], np.float32), 1.5, FLOOR_ID), # floor y = 1.5
44
+ (np.array([0, 1, 0], np.float32), 1.2, CEILING_ID), # ceiling y = -1.2
45
+ ]
46
+ wall_planes = {
47
+ "left": (np.array([1, 0, 0], np.float32), 2.2), # x = -2.2
48
+ "back": (np.array([0, 0, -1], np.float32), 5.0), # z = 5
49
+ "right": (np.array([-1, 0, 0], np.float32), 2.2), # x = 2.2
50
+ }
51
+ planes += [(wall_planes[name][0], wall_planes[name][1], WALL_ID) for name in walls]
52
+
53
+ yy, xx = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
54
+ rays = np.dstack(((xx - INTRINSICS[0, 2]) / FOCAL, (yy - INTRINSICS[1, 2]) / FOCAL, np.ones_like(xx)))
55
+ best_t = np.full((HEIGHT, WIDTH), np.inf, np.float32)
56
+ labels = np.full((HEIGHT, WIDTH), -1, np.int32)
57
+ for index, (normal, offset, _) in enumerate(planes):
58
+ with np.errstate(divide="ignore", invalid="ignore"):
59
+ t = -offset / (rays @ normal)
60
+ closer = (t > 0) & (t < best_t)
61
+ best_t[closer] = t[closer]
62
+ labels[closer] = index
63
+
64
+ valid = np.isfinite(best_t)
65
+ points = rays * np.where(valid, best_t, 0)[..., None]
66
+ seg_map = np.zeros((HEIGHT, WIDTH), np.uint8)
67
+ normals = np.zeros((HEIGHT, WIDTH, 3), np.float32)
68
+ for index, (normal, _, class_id) in enumerate(planes):
69
+ seg_map[labels == index] = class_id
70
+ normals[labels == index] = normal # into the room == facing the camera (MoGe-style)
71
+ geometry = {
72
+ "provider": "moge-2",
73
+ "points": points.astype(np.float32),
74
+ "normals": normals,
75
+ "validMask": valid,
76
+ "depth": points[..., 2].astype(np.float32),
77
+ "intrinsics": INTRINSICS,
78
+ }
79
+ return seg_map, geometry, labels
80
+
81
+
82
+ class WallSegmentTests(unittest.TestCase):
83
+ @classmethod
84
+ def setUpClass(cls):
85
+ cls.seg_map, cls.geometry, cls.labels = synthetic_room()
86
+ cls.min_area = max(1200, int(WIDTH * HEIGHT * 0.015))
87
+
88
+ def test_three_walls_become_three_ordered_segments(self):
89
+ discovery = discover_wall_components(self.seg_map, self.geometry, self.min_area)
90
+ self.assertEqual(len(discovery.components), 3)
91
+ expected_normals = ([1, 0, 0], [0, 0, 1], [1, 0, 0]) # left, back, right (up to sign)
92
+ for component, expected, true_label in zip(discovery.components, expected_normals, (2, 3, 4)):
93
+ purity = float((self.labels[component.mask > 0] == true_label).mean())
94
+ self.assertGreater(purity, 0.97, "a wall segment leaked into another wall")
95
+ plane = component.plane
96
+ assert plane is not None
97
+ self.assertGreater(abs(float(plane.normal @ np.array(expected, np.float32))), 0.98)
98
+
99
+ def test_wall_outline_reaches_the_door_frame(self):
100
+ """Walls must follow the semantic boundary like the floor: no gap band, no bleed."""
101
+ seg_map = self.seg_map.copy()
102
+ door = np.array([[1150, 520], [1330, 505], [1340, 1000], [1160, 1010]], np.int32) # slanted frame
103
+ cv2.fillPoly(seg_map, [door], int(DOOR_ID))
104
+ discovery = discover_wall_components(seg_map, self.geometry, self.min_area)
105
+ walls = np.zeros(seg_map.shape, bool)
106
+ for component in discovery.components:
107
+ walls |= component.mask > 0
108
+
109
+ door_mask = seg_map == DOOR_ID
110
+ depth_into_door = cv2.distanceTransform(door_mask.astype(np.uint8), cv2.DIST_L2, 3)
111
+ bleed = walls & door_mask
112
+ # Rasterising a straight slanted edge may touch the door's first pixel row only.
113
+ self.assertLessEqual(float(depth_into_door[bleed].max()) if bleed.any() else 0.0, 1.5,
114
+ "wall texture bled onto the door")
115
+ near_door = cv2.dilate(door_mask.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0
116
+ wall_near_door = near_door & ~door_mask & (seg_map == WALL_ID)
117
+ covered = float(walls[wall_near_door].mean())
118
+ self.assertGreater(covered, 0.97, f"only {covered:.0%} of wall pixels next to the door are textured")
119
+
120
+ def test_zigzag_door_edge_becomes_one_straight_line(self):
121
+ """A wobbly semantic boundary (as OneFormer produces) is redrawn as a straight edge."""
122
+ seg_map = self.seg_map.copy()
123
+ rng = np.random.default_rng(3)
124
+ top, bottom, edge_x = 520, 1000, 1150
125
+ for y in range(top, bottom):
126
+ wobble = int(rng.integers(-4, 5)) # +-4px zig-zag per row
127
+ seg_map[y, edge_x + wobble:1330] = DOOR_ID
128
+ discovery = discover_wall_components(seg_map, self.geometry, self.min_area)
129
+ walls = np.zeros(seg_map.shape, bool)
130
+ for component in discovery.components:
131
+ walls |= component.mask > 0
132
+
133
+ rows = np.arange(top + 40, bottom - 40) # away from the corners
134
+ window = walls[rows, edge_x - 40:edge_x + 40]
135
+ edge = edge_x - 40 + window.shape[1] - np.argmax(window[:, ::-1], axis=1) # last wall px + 1
136
+ fitted = np.polyval(np.polyfit(rows, edge, 1), rows)
137
+ self.assertLess(float(np.abs(edge - fitted).max()), 1.01, "wall edge along the door is not straight")
138
+ self.assertLess(float(np.abs(fitted - edge_x).max()), 2.5, "straight edge drifted off the true boundary")
139
+
140
+ def test_single_flat_wall_is_not_split(self):
141
+ seg_map, geometry, _ = synthetic_room(walls=("back",))
142
+ discovery = discover_wall_components(seg_map, geometry, self.min_area)
143
+ self.assertEqual(len(discovery.components), 1)
144
+
145
+ def test_floor_keeps_its_own_plane_budget(self):
146
+ self.assertEqual(SURFACE_MAX_PLANES, 1, "GPU profile floor max_planes must stay 1")
147
+ self.assertGreater(WALL_MAX_PLANES, 1)
148
+ mask = self.labels >= 2
149
+ points = self.geometry["points"][mask][::20]
150
+ normals = self.geometry["normals"][mask][::20]
151
+ self.assertLessEqual(len(fit_multi_surface_planes(points, normals, True)), 1)
152
+ self.assertGreaterEqual(len(fit_multi_surface_planes(points, normals, True, max_planes=WALL_MAX_PLANES)), 3)
153
+
154
+ def test_ray_plane_uv_matches_true_points(self):
155
+ normal = np.array([0, 0, -1], np.float32)
156
+ origin = np.array([0, 0, 5], np.float32)
157
+ u_axis, v_axis = upright_plane_basis(normal, np.array([0, 1, 0], np.float32))
158
+ flat = np.flatnonzero((self.labels == 3).ravel())[::50]
159
+ uv, hit = ray_plane_uv(flat, WIDTH, INTRINSICS, origin, normal, u_axis, v_axis)
160
+ self.assertTrue(hit.all())
161
+ true_points = self.geometry["points"].reshape(-1, 3)[flat]
162
+ true_uv = np.column_stack(((true_points - origin) @ u_axis, (true_points - origin) @ v_axis))
163
+ self.assertLess(float(np.abs(uv - true_uv).max()), 1e-3)
164
+
165
+ def test_plane_transform_equals_ray_plane_uv(self):
166
+ normal = np.array([0.6, 0.0, -0.8], np.float32)
167
+ origin = np.array([0.5, 0.2, 4.0], np.float32)
168
+ u_axis, v_axis = upright_plane_basis(normal, np.array([0, 1, 0], np.float32))
169
+ flat = np.arange(0, WIDTH * HEIGHT, 997)
170
+ uv, hit = ray_plane_uv(flat, WIDTH, INTRINSICS, origin, normal, u_axis, v_axis)
171
+ transform = plane_to_image_transform(INTRINSICS, origin, normal, u_axis, v_axis)
172
+ pixels = np.column_stack((flat % WIDTH, flat // WIDTH, np.ones(len(flat))))
173
+ mapped = pixels @ transform.T
174
+ mapped_uv = mapped[:, :2] / mapped[:, 2:3]
175
+ self.assertLess(float(np.abs(mapped_uv[hit] - uv[hit]).max()), 1e-3)
176
+
177
+ def test_wall_texture_axis_is_upright(self):
178
+ u_axis, v_axis = upright_plane_basis(np.array([1, 0, 0], np.float32), np.array([0, 1, 0], np.float32))
179
+ self.assertGreater(abs(float(v_axis[1])), 0.99)
180
+ self.assertLess(abs(float(u_axis[1])), 1e-3)
181
+
182
+ def test_segments_have_exact_plane_mapping_small_payload_and_fit_budget(self):
183
+ started = time.perf_counter()
184
+ result = build_wall_segments(
185
+ np.full((HEIGHT, WIDTH, 3), 180, np.uint8), self.seg_map, self.geometry,
186
+ self.min_area, "test-model",
187
+ )
188
+ elapsed = time.perf_counter() - started
189
+ print(f"\n[wall benchmark] {WIDTH}x{HEIGHT}: {elapsed * 1000:.0f}ms {result.detail}")
190
+ self.assertEqual([s["id"] for s in result.segments], [1, 2, 3])
191
+ points = self.geometry["points"].reshape(-1, 3)
192
+ true_labels = self.labels.ravel()
193
+ for segment, wall_label in zip(result.segments, (2, 3, 4)): # left, back, right
194
+ plane = segment["plane"]
195
+ self.assertIsNone(segment["surfaceUv"], "walls ship a 3x3 transform, not per-pixel UV")
196
+ self.assertEqual(segment["metadata"]["textureMappingMode"], "wall-plane")
197
+ self.assertGreaterEqual(plane["geometryConfidence"], 0.99)
198
+ self.assertEqual(segment["metadata"]["wallComponentCount"], 3)
199
+ # The transform reproduces the true metric position of the wall's own pixels
200
+ # (edge pixels shared with a neighbouring surface lie on that surface's plane).
201
+ flat = np.frombuffer(base64.b64decode(segment["mask"]), np.uint32)[::101]
202
+ flat = flat[true_labels[flat] == wall_label]
203
+ transform = np.asarray(segment["surfaceTransform"], np.float64).reshape(3, 3)
204
+ mapped = np.column_stack((flat % WIDTH, flat // WIDTH, np.ones(len(flat)))) @ transform.T
205
+ origin = np.asarray(plane["planeOrigin"])
206
+ true_uv = np.column_stack((
207
+ (points[flat] - origin) @ np.asarray(plane["surfaceUAxis"]),
208
+ (points[flat] - origin) @ np.asarray(plane["surfaceVAxis"]),
209
+ ))
210
+ self.assertLess(float(np.abs(mapped[:, :2] / mapped[:, 2:3] - true_uv).max()), 0.005)
211
+ shade = segment["shadeMap"]
212
+ if shade is not None:
213
+ self.assertLessEqual(max(shade.shape), 768)
214
+ self.assertLess(elapsed, WALL_TIME_BUDGET_SECONDS)
215
+
216
+
217
+ if __name__ == "__main__":
218
+ unittest.main()
visualizer.gpu.toml CHANGED
@@ -17,7 +17,7 @@ enable_depth_estimation = true
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
- enable_wall_segments = false
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
@@ -28,6 +28,7 @@ warm_start_models = true
28
  debug_artifacts_enabled = false
29
  inference_max_dimension = 1024
30
  conversion_target_ms = 30000
 
31
  bundle_image_format = "jpeg"
32
  bundle_image_quality = 92
33
  data_dir = "data"
@@ -35,6 +36,11 @@ data_dir = "data"
35
  [surface_mapping]
36
  ransac_distance_threshold = 0.04
37
  max_planes = 1
 
 
 
 
 
38
  normal_angle_threshold_degrees = 35
39
  normal_smoothing_kernel = 5
40
  min_plane_pixels = 1500
 
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
+ enable_wall_segments = true
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
 
28
  debug_artifacts_enabled = false
29
  inference_max_dimension = 1024
30
  conversion_target_ms = 30000
31
+ max_concurrent_conversions = 2
32
  bundle_image_format = "jpeg"
33
  bundle_image_quality = 92
34
  data_dir = "data"
 
36
  [surface_mapping]
37
  ransac_distance_threshold = 0.04
38
  max_planes = 1
39
+ # Walls have their own plane budget; the floor keeps max_planes above.
40
+ wall_max_planes = 4
41
+ max_walls = 6
42
+ wall_work_max_dimension = 768
43
+ wall_edge_straighten_ratio = 0.004
44
  normal_angle_threshold_degrees = 35
45
  normal_smoothing_kernel = 5
46
  min_plane_pixels = 1500
visualizer.hf.toml CHANGED
@@ -17,7 +17,7 @@ enable_depth_estimation = true
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
- enable_wall_segments = false
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
@@ -27,11 +27,17 @@ enable_floor_mask_cleanup = true
27
  debug_artifacts_enabled = false
28
  inference_max_dimension = 1024
29
  conversion_target_ms = 30000
 
30
  data_dir = "data"
31
 
32
  [surface_mapping]
33
  ransac_distance_threshold = 0.04
34
  max_planes = 1
 
 
 
 
 
35
  normal_angle_threshold_degrees = 35
36
  normal_smoothing_kernel = 5
37
  min_plane_pixels = 1500
 
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
+ enable_wall_segments = true
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_fast_shadow_transfer = true
 
27
  debug_artifacts_enabled = false
28
  inference_max_dimension = 1024
29
  conversion_target_ms = 30000
30
+ max_concurrent_conversions = 2
31
  data_dir = "data"
32
 
33
  [surface_mapping]
34
  ransac_distance_threshold = 0.04
35
  max_planes = 1
36
+ # Walls have their own plane budget; the floor keeps max_planes above.
37
+ wall_max_planes = 4
38
+ max_walls = 6
39
+ wall_work_max_dimension = 768
40
+ wall_edge_straighten_ratio = 0.004
41
  normal_angle_threshold_degrees = 35
42
  normal_smoothing_kernel = 5
43
  min_plane_pixels = 1500
visualizer.local.toml CHANGED
@@ -13,7 +13,7 @@ sam2_checkpoint = ""
13
  enable_depth_estimation = false
14
  enable_plane_fit = true
15
  enable_multi_plane_surfaces = true
16
- enable_wall_segments = false
17
  enable_intrinsic_shading = false
18
  enable_shading_transfer = false
19
  enable_fast_shadow_transfer = true
@@ -27,7 +27,12 @@ data_dir = "data"
27
 
28
  [surface_mapping]
29
  ransac_distance_threshold = 0.04
30
- max_planes = 5
 
 
 
 
 
31
  normal_angle_threshold_degrees = 35
32
  normal_smoothing_kernel = 5
33
  min_plane_pixels = 1500
 
13
  enable_depth_estimation = false
14
  enable_plane_fit = true
15
  enable_multi_plane_surfaces = true
16
+ enable_wall_segments = true
17
  enable_intrinsic_shading = false
18
  enable_shading_transfer = false
19
  enable_fast_shadow_transfer = true
 
27
 
28
  [surface_mapping]
29
  ransac_distance_threshold = 0.04
30
+ max_planes = 1
31
+ # Walls have their own plane budget; the floor keeps max_planes above.
32
+ wall_max_planes = 4
33
+ max_walls = 6
34
+ wall_work_max_dimension = 768
35
+ wall_edge_straighten_ratio = 0.004
36
  normal_angle_threshold_degrees = 35
37
  normal_smoothing_kernel = 5
38
  min_plane_pixels = 1500