"""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, active_segmentation_model_name, 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 from services.pipeline import debug_stages from services.pipeline.inference_utils import downscale_for_inference from services.wall.pipeline import WallResult, build_wall_segments 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, include_pixels: bool = True, ): 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)) # Time job-progress updates so they show as their own report line instead # of hiding inside "Pipeline Overhead". Every call below sits between # timed stages, never inside one, so nothing is counted twice. progress_elapsed = 0.0 progress_calls = 0 report_progress = progress_callback def progress_callback(phase, phase_progress): nonlocal progress_elapsed, progress_calls if report_progress is None: return started = time.perf_counter() try: report_progress(phase, phase_progress) finally: progress_elapsed += time.perf_counter() - started progress_calls += 1 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) # --- Walls: one background thread, overlapping every floor stage below --- # All wall work runs at working resolution (see services.wall.pipeline), so # it normally finishes before the floor does and "Wall Wait" stays ~0. wall_future = None wall_pool = None if ENABLE_WALL_SEGMENTS: from concurrent.futures import ThreadPoolExecutor as _WallPool wall_pool = _WallPool(max_workers=1, thread_name_prefix="walls") wall_future = wall_pool.submit( build_wall_segments, img_np, seg_map, geometry, min_floor_area, active_segmentation_model_name(), 1, ) # --- Encode room image in background (overlaps with masking + later stages) --- # Skipped for job conversions: the split vizbundle references the uploaded # image by URL, so a full-resolution re-encode would be discarded. _img_pool = None _pixels_b64_future = None if include_pixels: 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, ) 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"})) 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) walls = _collect_walls(wall_future, wall_pool, _log_stage) # --- 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) 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)) segments.extend(walls.segments) if not segments: segments = build_fallback_segments(seg_map, depth, models) _log_stage("Packaging", t0, f"segments={len(segments)}") if progress_callback: progress_callback(PipelinePhase.PACKAGING, 100) pixels_b64 = None if _pixels_b64_future is not None: t0 = time.perf_counter() pixels_b64 = _pixels_b64_future.result() _img_pool.shutdown(wait=False) _log_stage("Image Encoding Wait", t0) if progress_calls: stage_times.append(("Progress Updates", progress_elapsed, f"calls={progress_calls}")) 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} def _collect_walls(wall_future, wall_pool, log_stage) -> WallResult: """Wait for the background wall thread and log its cost. "Wall Wait" is the only time walls add to the pipeline (the floor was already done); its detail carries the walls' own (overlapped) timings. A wall failure never fails the job: the floor ships without walls. """ if wall_future is None: return WallResult() t0 = time.perf_counter() try: walls = wall_future.result() except Exception as exc: print(f"[WALLS] skipped: wall stage failed ({exc})", flush=True) walls = WallResult() finally: wall_pool.shutdown(wait=False) # Wall timings go in the detail, not as their own stages, because they # overlapped the floor stages and would otherwise be counted twice. log_stage("Wall Wait", t0, walls.detail) print(f"[WALLS] {walls.detail}", flush=True) return walls 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)