File size: 20,473 Bytes
c97431f
 
 
 
 
 
 
 
 
 
 
dbf1f41
 
 
 
 
 
c97431f
 
 
 
 
 
 
 
94b277a
c97431f
 
dbf1f41
 
 
 
 
c97431f
 
 
b267904
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b267904
 
 
 
 
c97431f
 
 
 
 
 
b267904
 
 
 
c97431f
b267904
 
 
 
c97431f
 
 
b267904
c97431f
 
b267904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c97431f
 
 
b267904
c97431f
 
b267904
c97431f
130493a
 
 
 
 
b267904
c97431f
 
 
 
 
 
 
 
 
 
 
b267904
c97431f
b267904
c97431f
 
 
 
 
 
 
 
b267904
c97431f
 
 
 
 
 
 
94b277a
 
 
c97431f
94b277a
 
 
 
 
 
 
 
73828b3
94b277a
c97431f
 
 
 
 
94b277a
 
 
 
 
 
 
 
 
 
 
c97431f
 
 
a0e83d6
c97431f
 
 
94b277a
 
 
 
 
 
c97431f
 
 
 
94b277a
 
 
 
 
 
 
 
 
c97431f
 
 
 
 
a0e83d6
 
 
 
 
 
 
 
 
 
 
 
 
 
dbf1f41
 
 
 
 
 
 
 
a0e83d6
 
 
 
 
 
 
 
dbf1f41
 
 
 
a0e83d6
 
 
0f200c9
 
c97431f
0f200c9
 
 
 
 
73828b3
0f200c9
 
130493a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0e83d6
 
 
c97431f
 
 
 
 
94b277a
 
 
 
 
 
 
 
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
b267904
c97431f
 
 
 
 
130493a
 
 
0f200c9
130493a
 
 
0f200c9
130493a
 
 
c97431f
 
 
b267904
c97431f
73828b3
 
 
 
 
 
 
 
 
 
 
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
73828b3
c97431f
130493a
 
 
73828b3
130493a
c97431f
 
73828b3
 
 
 
c97431f
 
 
 
 
b267904
0f200c9
 
 
 
 
c97431f
0f200c9
 
 
 
 
 
 
 
b267904
 
 
 
c97431f
 
a0e83d6
 
 
 
 
 
 
 
c97431f
a0e83d6
73828b3
 
 
 
b267904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
"""Main pipeline orchestrator: build_segmentation_bundle."""

from __future__ import annotations

import io
import time

import cv2
import numpy as np
from PIL import Image

from config.runtime import (
    ENABLE_FAST_SHADOW_TRANSFER,
    ENABLE_INTRINSIC_SHADING,
    ENABLE_SHADING_TRANSFER,
    ENABLE_WALL_SEGMENTS,
)
from models.depth import estimate_scene_geometry
from models.loader import _load_intrinsic_model
from models.segmentation import active_model_metadata, run_segmentation
from services.debug.capture import PipelineDebugCapture
from services.direction.analysis import floor_direction_geometry_inputs
from services.floor.edge_coverage import scaled_odd_kernel_size
from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
from services.floor.detection import estimate_floor_plane
from services.geometry.multi_plane import geometry_point_maps
from services.geometry.uv_mapping import build_surface_uv_mapping
from services.lighting.intrinsic import build_intrinsic_lighting_maps
from services.lighting.shading import (
    build_fast_shadow_lighting_maps,
    build_luminance_lighting_maps,
    lighting_map_statistics,
)
from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask
from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment, build_wall_segment
from services.pipeline import debug_stages
from services.pipeline.inference_utils import downscale_for_inference
from services.wall.components import wall_surface_components
from direction_finder import find_floor_direction
import state
from state import FLOOR_SURFACE_CLASSES, PRIMARY_FLOOR_CLASSES, REPLACEABLE_SOFT_FLOOR_CLASSES, class_ids
from enums import FloorMaskSource, PipelinePhase
from utils import mask_to_indices, seg_class_mask, timed_stage

from enums import TextureMappingMode, TextureMappingReason

_DEFAULT_MAPPING_META = {
    "surfaceUvEnabled": False, "textureMappingMode": TextureMappingMode.REGULARIZED_FLOOR_PLANE,
    "textureMappingReason": TextureMappingReason.SURFACE_UV_UNAVAILABLE, "surfaceUvCoverage": 0.0,
    "surfaceUvFinitePixels": 0, "surfaceUvTotalPixels": 0, "surfaceUvNeighborCount": 0,
    "surfaceUvMedianNeighborDelta": None, "surfaceUvP95NeighborDelta": None,
    "surfaceUvP99NeighborDelta": None, "surfaceUvJumpLimit": None,
    "surfaceUvBadNeighborRatio": None, "surfaceUvPlaneBoundaryRatio": None,
    "surfaceUvAssignedPlaneCount": 0,
}


def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None, progress_callback=None):
    t_start = time.perf_counter()
    d = debug  # shorthand
    stage_times: list[tuple[str, float, str]] = []  # (stage_name, seconds, detail)

    def _log_stage(name: str, t0: float, detail: str = ""):
        elapsed = time.perf_counter() - t0
        stage_times.append((name, elapsed, detail))

    t0 = time.perf_counter()
    img = Image.open(io.BytesIO(contents)).convert("RGB")
    img_np = np.array(img)
    h, w = img_np.shape[:2]
    min_floor_area = max(1200, int(w * h * 0.015))

    # Downscale for faster inference β€” masks/depth are output at full resolution
    inf_img, inf_np, inf_scale = downscale_for_inference(img, img_np)
    inf_h, inf_w = inf_np.shape[:2]
    el = (time.perf_counter() - t0) * 1000
    if inf_scale < 1.0:
        _log_stage("Image Loading", t0, f"{w}x{h} (inference@{inf_w}x{inf_h})")
    else:
        _log_stage("Image Loading", t0, f"{w}x{h}")
    if d:
        debug_stages.record_source_image(d, img_np, w, h, min_floor_area, el)

    # --- Segmentation + Geometry (parallel on CPU, sequential on single GPU) ---
    if progress_callback:
        progress_callback(PipelinePhase.SEGMENTATION, 0)

    use_parallel = state.device.type == "cpu"
    if use_parallel:
        from concurrent.futures import ThreadPoolExecutor
        t0 = time.perf_counter()
        with ThreadPoolExecutor(max_workers=2) as pool:
            seg_future = pool.submit(run_segmentation, inf_img, inf_np, h, w)
            geo_future = pool.submit(estimate_scene_geometry, inf_img, inf_np, w, h)
            seg_map = seg_future.result()
            geometry = geo_future.result()
        t_seg_geo = time.perf_counter() - t0
        _log_stage("Segmentation+Geometry (parallel)", t0)
    else:
        t0 = time.perf_counter()
        seg_map = run_segmentation(inf_img, inf_np, target_h=h, target_w=w)
        _log_stage("Segmentation", t0)
        t0 = time.perf_counter()
        geometry = estimate_scene_geometry(inf_img, inf_np, w, h)
        _log_stage("Geometry", t0, f"provider={geometry.get('provider')}")

    depth = geometry.get("depth")
    el = (time.perf_counter() - t0) * 1000
    if d:
        debug_stages.record_segmentation(d, img_np, seg_map, state.segmentation_backend, w, h, el)
        debug_stages.record_geometry(d, depth, None, geometry, el)
    if progress_callback:
        progress_callback(PipelinePhase.SEGMENTATION, 100)
        progress_callback(PipelinePhase.GEOMETRY, 55)

    # --- Encode room image in background (overlaps with masking + later stages) ---
    from concurrent.futures import ThreadPoolExecutor as _TP
    _img_pool = _TP(max_workers=1)
    _pixels_b64_future = _img_pool.submit(encode_bundle_image_data_url, img_np)

    # --- Floor masking (SAM2 removed β€” morphological cleanup only) ---
    if progress_callback:
        progress_callback(PipelinePhase.MASKING, 0)
    t0 = time.perf_counter()
    raw_primary = seg_class_mask(seg_map, class_ids(PRIMARY_FLOOR_CLASSES))
    floor_mask = clean_floor_mask(wall_subtract(raw_primary.copy(), seg_map, dilation=0))
    floor_mask_source = FloorMaskSource.PRIMARY_FLOOR
    if int(floor_mask.sum()) < min_floor_area:
        floor_mask = clean_floor_mask(wall_subtract(
            seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0))
        floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK
    cleaned = floor_mask.copy()
    sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "removed"}
    el = (time.perf_counter() - t0) * 1000
    _log_stage("Floor Masking", t0, f"source={floor_mask_source}")
    if d:
        debug_stages.record_floor_mask(d, img_np, raw_primary, cleaned, floor_mask, floor_mask_source, sam_metadata, el)
    if progress_callback:
        progress_callback(PipelinePhase.MASKING, 100)

    t0 = time.perf_counter()
    homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
    el = (time.perf_counter() - t0) * 1000
    _log_stage("Plane Fitting", t0)
    if d:
        debug_stages.record_plane(d, img_np, plane, homography, el)
    if progress_callback:
        progress_callback(PipelinePhase.GEOMETRY, 100)

    # --- Surface mask ---
    t0 = time.perf_counter()
    geometry_maps_started = time.perf_counter()
    prepared_geometry_maps = geometry_point_maps(floor_mask, geometry)
    geometry_maps_ms = (time.perf_counter() - geometry_maps_started) * 1000
    quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
    surface_mask, edge_metadata = build_floor_surface_mask(
        floor_mask,
        seg_map,
        quad,
        depth,
        geometry,
        plane,
        geometry_maps=prepared_geometry_maps,
        image_rgb=img_np,
    )
    replaced_material_mask = (seg_class_mask(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES)).astype(bool) & (surface_mask > 0)).astype(np.uint8)
    surface_indices = mask_to_indices(surface_mask)
    occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
    occlusion_indices = mask_to_indices(occlusion_mask)
    el = (time.perf_counter() - t0) * 1000
    surface_timing = edge_metadata.get("surfaceMaskingTimingMs") or {}
    filter_ms = sum(float(surface_timing.get(name) or 0.0) for name in (
        "initialGeometryFilter",
        "postEdgeGeometryFilter",
        "postSoftFloorGeometryFilter",
    ))
    _log_stage(
        "Surface Masking",
        t0,
        f"geometry-prep={geometry_maps_ms:.0f}ms filters={filter_ms:.0f}ms",
    )
    if d:
        debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)

    # --- Surface UV mapping ---
    if progress_callback:
        progress_callback(PipelinePhase.SURFACE_MAPPING, 0)
    t0 = time.perf_counter()
    surface_mapping = build_surface_uv_mapping(
        surface_mask,
        surface_indices,
        geometry,
        geometry_maps=prepared_geometry_maps,
    )
    use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
    mapping_metadata = surface_mapping["metadata"] if surface_mapping is not None else {
        **_DEFAULT_MAPPING_META, "surfaceUvTotalPixels": int(len(surface_indices))}
    el = (time.perf_counter() - t0) * 1000
    uv_timing = mapping_metadata.get("surfaceUvTimingMs") or {}
    uv_detail = f"uv={'yes' if use_surface_uv else 'no'}"
    if uv_timing:
        uv_detail += (
            f" fit={float(uv_timing.get('planeFit') or 0.0):.0f}ms"
            f" assign={float(uv_timing.get('planeAssignment') or 0.0):.0f}ms"
            f" quality={float(uv_timing.get('qualityAnalysis') or 0.0):.0f}ms"
        )
    _log_stage("UV Mapping", t0, uv_detail)
    if d:
        debug_stages.record_surface_mapping(d, h, w, surface_indices, surface_mapping, use_surface_uv, mapping_metadata, el)
    if progress_callback:
        progress_callback(PipelinePhase.SURFACE_MAPPING, 100)

    # --- Lighting ---
    if progress_callback:
        progress_callback(PipelinePhase.LIGHTING, 0)
    t0 = time.perf_counter()
    lighting_maps, shade_map, showroom_shade_map, reflection_map = None, None, None, None
    lighting_source, intrinsic_lighting_used = None, False
    if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
        if state.intrinsic_models is None:
            _load_intrinsic_model()
        if state.intrinsic_models is not None:
            lighting_maps = build_intrinsic_lighting_maps(img_np, surface_mask, replaced_material_mask)
            if lighting_maps and lighting_maps.get("shadeMap") is not None:
                from config.models import INTRINSIC_MODEL_VERSION
                lighting_source, intrinsic_lighting_used = f"intrinsic-{INTRINSIC_MODEL_VERSION}", True
    if ENABLE_FAST_SHADOW_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
        lighting_maps = build_fast_shadow_lighting_maps(
            img_np,
            surface_mask,
            replaced_material_mask,
        )
        if lighting_maps and lighting_maps.get("shadeMap") is not None:
            lighting_source = "fast-luminance"
    if ENABLE_SHADING_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
        lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
        if lighting_maps and lighting_maps.get("shadeMap") is not None:
            lighting_source = "luminance"
    if lighting_maps:
        shade_map, showroom_shade_map, reflection_map = lighting_maps.get("shadeMap"), lighting_maps.get("showroomShadeMap"), lighting_maps.get("reflectionMap")
    shade_statistics = lighting_map_statistics(shade_map, surface_mask)
    el = (time.perf_counter() - t0) * 1000
    lighting_detail = f"source={lighting_source}"
    if shade_map is not None:
        lighting_detail += f" map={shade_map.shape[1]}x{shade_map.shape[0]}"
    _log_stage("Lighting", t0, lighting_detail)
    if d:
        debug_stages.record_lighting(d, shade_map, showroom_shade_map, reflection_map, surface_mask, lighting_source, el)

    # The semantic wall mask remains useful as a structural cue for floor
    # direction, even when wall surfaces are not emitted in the bundle.
    wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
    wall_components = []
    wall_protected_mask = None
    if ENABLE_WALL_SEGMENTS:
        t0 = time.perf_counter()
        wall_components, wall_protected_mask = wall_surface_components(
            seg_map, min_floor_area, geometry, image_rgb=img_np,
        )
        _log_stage("Wall Discovery", t0, f"components={len(wall_components)}")

    # --- Pre-compute wall lighting in parallel with floor direction ---
    # Wall lighting was previously computed inside build_wall_segment (in the
    # "Packaging" phase), adding ~5s for large images.  Moving it here lets it
    # overlap with floor-direction detection.
    from concurrent.futures import ThreadPoolExecutor, Future

    def _compute_wall_lighting(component_mask):
        return build_luminance_lighting_maps(img_np, component_mask)

    wall_lighting_futures: list[Future] = []
    wall_executor = ThreadPoolExecutor(max_workers=max(1, len(wall_components))) if wall_components else None
    if wall_executor:
        for _, cm in wall_components:
            wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))

    if progress_callback:
        progress_callback(PipelinePhase.LIGHTING, 100)

    # --- Floor direction ---
    if progress_callback:
        progress_callback(PipelinePhase.DIRECTION, 0)
    t0 = time.perf_counter()
    dir_xform = plane.get("floorTransform") if plane and plane.get("floorTransform") and float(plane.get("geometryConfidence") or 0.0) >= 0.35 else homography
    dir_inputs = floor_direction_geometry_inputs(
        surface_mask,
        geometry,
        plane,
        surface_mapping,
        use_surface_uv=use_surface_uv,
        geometry_maps=prepared_geometry_maps,
    )
    struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}))
    sk = scaled_odd_kernel_size(h, w, 0.006, minimum=3)
    struct_mask = cv2.dilate(struct_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (sk, sk)), iterations=1)
    floor_direction = find_floor_direction(
        img_np, surface_mask, wall_mask=wall_mask, structure_mask=struct_mask,
        normals_map=dir_inputs["normalsMap"], geometry_valid_mask=dir_inputs["validMask"],
        intrinsics=dir_inputs["intrinsics"], floor_normal=dir_inputs["floorNormal"],
        render_u_axis=dir_inputs["renderUAxis"], render_v_axis=dir_inputs["renderVAxis"],
        render_transform=dir_xform,
        surface_uv=surface_mapping["uv"] if use_surface_uv else None,
        surface_indices=surface_indices if use_surface_uv else None,
        surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None,
    )
    el = (time.perf_counter() - t0) * 1000
    _log_stage("Floor Direction", t0, f"method={floor_direction.get('directionMethod')}")
    if d:
        debug_stages.record_direction(d, img_np, floor_direction, el)
    if progress_callback:
        progress_callback(PipelinePhase.DIRECTION, 100)

    # Collect pre-computed wall lighting results
    wall_lighting_results: list[dict | None] = []
    if wall_executor:
        t0 = time.perf_counter()
        for fut in wall_lighting_futures:
            wall_lighting_results.append(fut.result())
        wall_executor.shutdown(wait=False)
        _log_stage("Wall Lighting Wait", t0, f"components={len(wall_components)}")
    else:
        wall_lighting_results = [None] * len(wall_components)

    # --- Package segments ---
    if progress_callback:
        progress_callback(PipelinePhase.PACKAGING, 0)
    t0 = time.perf_counter()
    models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
    # A floor is horizontal by definition, so its normal is true vertical in
    # whatever frame the point cloud uses. Walls need that rather than +Y,
    # which is camera-up and tilts the tile grid with the camera.
    floor_up = None
    if surface_mapping is not None:
        for candidate in (surface_mapping.get('planes') or []):
            if candidate.get('isFloor'):
                floor_up = np.asarray(candidate['normal'], dtype=np.float32)
                break
    if floor_up is not None:
        print(f'[WALL_UP] using floor normal as vertical: {floor_up.round(3).tolist()}', flush=True)
    segments = []
    if len(surface_indices) >= min_floor_area:
        segments.append(build_floor_segment(
            surface_indices=surface_indices, occlusion_indices=occlusion_indices,
            homography=homography, plane=plane, surface_mapping=surface_mapping,
            use_surface_uv=use_surface_uv, shade_map=shade_map,
            showroom_shade_map=showroom_shade_map, reflection_map=reflection_map,
            floor_mask=floor_mask, surface_mask=surface_mask,
            replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask,
            floor_direction=floor_direction, sam_metadata=sam_metadata,
            edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
            shade_statistics=shade_statistics, lighting_source=lighting_source,
            intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
    wall_segments = []
    for wi, (_, cm) in enumerate(wall_components):
        ws = build_wall_segment(
            wi, cm, wall_protected_mask, geometry, img_np, wall_components, models,
            precomputed_lighting=wall_lighting_results[wi] if wi < len(wall_lighting_results) else None,
            up_vector=floor_up,
        )
        if ws:
            segments.append(ws)
            wall_segments.append(ws)
    if d:
        debug_stages.record_walls(d, img_np, wall_mask, wall_protected_mask, wall_components,
                                  wall_segments, (time.perf_counter() - t0) * 1000)
    if not segments:
        segments = build_fallback_segments(seg_map, depth, models)

    if progress_callback:
        progress_callback(PipelinePhase.PACKAGING, 100)
    _log_stage("Packaging", t0, f"segments={len(segments)}")
    t0 = time.perf_counter()
    pixels_b64 = _pixels_b64_future.result()
    _img_pool.shutdown(wait=False)
    _log_stage("Image Encoding Wait", t0)

    total_elapsed = time.perf_counter() - t_start
    accounted_elapsed = sum(elapsed for _, elapsed, _ in stage_times)
    overhead_elapsed = max(0.0, total_elapsed - accounted_elapsed)
    if overhead_elapsed >= 0.001:
        stage_times.append((
            "Pipeline Overhead",
            overhead_elapsed,
            "callbacks, metadata and untimed glue",
        ))

    # ── Print clean timing summary ──
    _print_pipeline_summary(stage_times, total_elapsed, w, h)

    if d:
        d.complete(total_elapsed * 1000)
    pipeline_stages = [
        {"name": name, "elapsed_s": round(elapsed, 3), "detail": detail}
        for name, elapsed, detail in stage_times
    ]
    pipeline_stages.append({
        "name": "TOTAL", "elapsed_s": round(total_elapsed, 3), "detail": f"{w}x{h}",
    })

    return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
            "modelName": models["segmentation"]["name"], "models": models,
            "pipelineStages": pipeline_stages,
            # Raw depth for the refinement side-car. Popped by the conversion
            # task before packaging, so it never reaches the bundle.
            "depthMap": depth}


def _print_pipeline_summary(
    stage_times: list[tuple[str, float, str]],
    total_elapsed: float,
    w: int,
    h: int,
):
    """Print a formatted pipeline timing summary to stdout."""
    sep = "─" * 60
    lines = [
        "",
        f"β”Œ{sep}┐",
        f"β”‚ {'PIPELINE TIMING REPORT':^58} β”‚",
        f"β”‚ {'Image: ' + f'{w}x{h}':^58} β”‚",
        f"β”œ{'─' * 30}┬{'─' * 14}┬{'─' * 14}─",
        f"β”‚ {'Stage':<28} β”‚ {'Time':>12} β”‚ {'% Total':>12} β”‚",
        f"β”œ{'─' * 30}β”Ό{'─' * 14}β”Ό{'─' * 14}─",
    ]
    for name, elapsed, detail in stage_times:
        pct = (elapsed / total_elapsed * 100) if total_elapsed > 0 else 0
        time_str = f"{elapsed:.2f}s"
        pct_str = f"{pct:.1f}%"
        label = f"{name} ({detail})" if detail else name
        if len(label) > 28:
            label = label[:27] + "\u2026"
        lines.append(f"β”‚ {label:<28} β”‚ {time_str:>12} β”‚ {pct_str:>12} β”‚")
    lines.append(f"β”œ{'─' * 30}β”Ό{'─' * 14}β”Ό{'─' * 14}─")
    total_str = f"{total_elapsed:.2f}s"
    lines.append(f"β”‚ {'TOTAL':.<28} β”‚ {total_str:>12} β”‚ {'100%':>12} β”‚")
    lines.append(f"β””{'─' * 30}β”΄{'─' * 14}β”΄{'─' * 14}β”˜")
    lines.append("")
    print("\n".join(lines), flush=True)