File size: 6,645 Bytes
1003449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fast preview pipeline — ~3s segmentation-only bundle for immediate user interaction.

Runs segmentation at 512px, skips depth/UV/intrinsic lighting, and uses basic
luminance shading. Returns a minimal vizbundle that the frontend can render
while the full HD pipeline runs in the background.
"""

from __future__ import annotations

import io
import time

import cv2
import numpy as np
from PIL import Image

from models.segmentation import run_segmentation
from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
from services.floor.detection import estimate_floor_plane
from services.lighting.shading import 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.inference_utils import downscale_for_inference
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, GeometryProvider
from utils import mask_to_indices, seg_class_mask

PREVIEW_MAX_DIM = 512


def _downscale_to(img: Image.Image, img_np: np.ndarray, max_dim: int):
    """Downscale for preview inference at a fixed small size."""
    h, w = img_np.shape[:2]
    largest = max(h, w)
    if largest <= max_dim:
        return img, img_np, 1.0
    scale = max_dim / float(largest)
    new_w = max(1, int(round(w * scale)))
    new_h = max(1, int(round(h * scale)))
    resized_pil = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
    resized_np = np.array(resized_pil)
    return resized_pil, resized_np, scale


def build_preview_bundle(contents: bytes) -> dict:
    """Build a fast preview bundle (seg + basic shading, no depth/UV)."""
    t_start = 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 aggressively for speed
    inf_img, inf_np, _ = _downscale_to(img, img_np, PREVIEW_MAX_DIM)

    # Segmentation at 512px, output at full res
    seg_map = run_segmentation(inf_img, inf_np, target_h=h, target_w=w)

    # Floor masking (no SAM2)
    pixels_b64 = encode_bundle_image_data_url(img_np)
    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

    # Homography-only plane (no depth)
    geometry = {
        "provider": GeometryProvider.HOMOGRAPHY,
        "points": None, "depth": None, "normals": None,
        "validMask": None, "intrinsics": None,
    }
    homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)

    # Surface mask
    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, None, geometry, plane)
    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)

    # Basic luminance shading (fast, CPU-only)
    lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
    shade_map = lighting_maps.get("shadeMap") if lighting_maps else None
    showroom_shade_map = lighting_maps.get("showroomShadeMap") if lighting_maps else None
    reflection_map = lighting_maps.get("reflectionMap") if lighting_maps else None
    shade_statistics = lighting_map_statistics(shade_map, surface_mask)

    # Minimal floor direction
    wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
    struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}))
    floor_direction = find_floor_direction(
        img_np, surface_mask, wall_mask=wall_mask,
        structure_mask=struct_mask,
        normals_map=None, geometry_valid_mask=None,
        intrinsics=None, floor_normal=None,
        render_u_axis=None, render_v_axis=None,
        render_transform=homography,
        surface_uv=None, surface_indices=None, surface_plane_ids=None,
    )

    # Package
    sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "preview"}
    mapping_metadata = {"surfaceUvEnabled": False, "textureMappingMode": "regularized-floor-plane"}
    models = {
        "segmentation": {"backend": state.segmentation_backend, "name": "oneformer-preview"},
        "geometry": {"provider": GeometryProvider.HOMOGRAPHY, "name": None},
        "depth": {"enabled": False, "name": None},
        "intrinsic": {"enabled": False, "name": None},
    }

    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=None,
            use_surface_uv=False, 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="luminance",
            intrinsic_lighting_used=False, models=models, depth=None, geometry=geometry))
    if not segments:
        segments = build_fallback_segments(seg_map, None, models)

    total_elapsed = time.perf_counter() - t_start
    print(f"[PREVIEW] Built in {total_elapsed:.2f}s ({w}x{h}, inference@{PREVIEW_MAX_DIM}px)", flush=True)

    return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
            "modelName": models["segmentation"]["name"], "models": models,
            "isPreview": True}