github-actions[bot] commited on
Commit
485bb51
·
1 Parent(s): 130493a

Automated Deploy: 3dc961997aac03c2ddee153e433e5ce673197ac5

Browse files
app.py CHANGED
@@ -7,7 +7,7 @@ from fastapi.staticfiles import StaticFiles
7
 
8
  from config.paths import MATERIAL_DIR, UPLOAD_DIR
9
  from models.loader import warm_start_models
10
- from routes import floor_direction, gemini, materials, qa, segmentation, viz2d
11
 
12
  app = FastAPI()
13
 
@@ -25,6 +25,7 @@ app.include_router(gemini.router)
25
  app.include_router(materials.router)
26
  app.include_router(segmentation.router)
27
  app.include_router(floor_direction.router)
 
28
 
29
 
30
  @app.on_event("startup")
 
7
 
8
  from config.paths import MATERIAL_DIR, UPLOAD_DIR
9
  from models.loader import warm_start_models
10
+ from routes import floor_direction, gemini, harmonization, materials, qa, segmentation, viz2d
11
 
12
  app = FastAPI()
13
 
 
25
  app.include_router(materials.router)
26
  app.include_router(segmentation.router)
27
  app.include_router(floor_direction.router)
28
+ app.include_router(harmonization.router)
29
 
30
 
31
  @app.on_event("startup")
requirements-base.txt CHANGED
@@ -13,4 +13,6 @@ tokenizers==0.20.3
13
  transformers==4.46.3
14
  uvicorn==0.34.2
15
  scipy
 
 
16
  git+https://github.com/compphoto/Intrinsic.git
 
13
  transformers==4.46.3
14
  uvicorn==0.34.2
15
  scipy
16
+ diffusers>=0.30.0
17
+ accelerate>=0.33.0
18
  git+https://github.com/compphoto/Intrinsic.git
requirements.txt CHANGED
@@ -19,7 +19,7 @@ h11==0.16.0
19
  hf-xet==1.1.2
20
  httpcore==1.0.9
21
  httpx==0.28.1
22
- huggingface-hub==0.32.0
23
  idna==3.10
24
  Jinja2==3.1.6
25
  kiwisolver==1.4.8
@@ -86,4 +86,6 @@ urllib3==2.4.0
86
  uvicorn==0.34.2
87
  websockets==15.0.1
88
  scipy
 
 
89
  git+https://github.com/compphoto/Intrinsic.git
 
19
  hf-xet==1.1.2
20
  httpcore==1.0.9
21
  httpx==0.28.1
22
+ huggingface-hub>=0.33.5,<2.0
23
  idna==3.10
24
  Jinja2==3.1.6
25
  kiwisolver==1.4.8
 
86
  uvicorn==0.34.2
87
  websockets==15.0.1
88
  scipy
89
+ diffusers>=0.30.0
90
+ accelerate>=0.33.0
91
  git+https://github.com/compphoto/Intrinsic.git
routes/harmonization.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Post-composite harmonization and diffusion inpainting endpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import base64
7
+ import io
8
+
9
+ import numpy as np
10
+ from fastapi import APIRouter
11
+ from PIL import Image
12
+
13
+ from errors import bad_request
14
+
15
+ router = APIRouter(prefix="/harmonize", tags=["harmonization"])
16
+
17
+
18
+ def _decode_image(value: str) -> np.ndarray:
19
+ """Decode base64 data URL or raw base64 to RGB numpy array."""
20
+ if not value:
21
+ bad_request("Image is required.")
22
+ encoded = value
23
+ if value.startswith("data:"):
24
+ _, encoded = value.split(",", 1)
25
+ raw = base64.b64decode(encoded)
26
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
27
+ return np.array(img)
28
+
29
+
30
+ def _decode_mask(value: str) -> np.ndarray:
31
+ """Decode base64 mask to single-channel uint8 numpy array."""
32
+ if not value:
33
+ bad_request("Mask is required.")
34
+ encoded = value
35
+ if value.startswith("data:"):
36
+ _, encoded = value.split(",", 1)
37
+ raw = base64.b64decode(encoded)
38
+ img = Image.open(io.BytesIO(raw)).convert("L")
39
+ return np.array(img)
40
+
41
+
42
+ def _encode_image(img: np.ndarray, quality: int = 92) -> str:
43
+ """Encode RGB numpy array to JPEG data URL."""
44
+ pil = Image.fromarray(img)
45
+ buf = io.BytesIO()
46
+ pil.save(buf, format="JPEG", quality=quality, optimize=True)
47
+ b64 = base64.b64encode(buf.getvalue()).decode()
48
+ return f"data:image/jpeg;base64,{b64}"
49
+
50
+
51
+ @router.post("/")
52
+ async def harmonize(payload: dict):
53
+ """Harmonize a tile composite to match room lighting/color.
54
+
55
+ Accepts:
56
+ image: base64 data URL — composited image (room + tile)
57
+ mask: base64 data URL — tile region mask (white = tile)
58
+ original: base64 data URL — original room image (optional, improves quality)
59
+ mode: "fast" | "neural" | "generate" (default: "fast")
60
+ strength: float 0-1 (default: 0.7)
61
+
62
+ Returns:
63
+ image: base64 data URL — harmonized image
64
+ mode: actual mode used
65
+ elapsed_ms: processing time
66
+ """
67
+ image_value = payload.get("image")
68
+ mask_value = payload.get("mask")
69
+ original_value = payload.get("original")
70
+ mode = payload.get("mode", "fast")
71
+ strength = float(payload.get("strength", 0.7))
72
+
73
+ if not image_value or not mask_value:
74
+ bad_request("Both 'image' and 'mask' are required.")
75
+
76
+ composite = await asyncio.to_thread(_decode_image, image_value)
77
+ mask = await asyncio.to_thread(_decode_mask, mask_value)
78
+ original = await asyncio.to_thread(_decode_image, original_value) if original_value else None
79
+
80
+ # Ensure mask matches composite dimensions
81
+ if mask.shape[:2] != composite.shape[:2]:
82
+ import cv2
83
+ mask = cv2.resize(mask, (composite.shape[1], composite.shape[0]), interpolation=cv2.INTER_NEAREST)
84
+
85
+ if mode == "generate":
86
+ # Diffusion inpainting mode
87
+ result = await asyncio.to_thread(
88
+ _run_diffusion_inpaint, composite, mask, original, strength
89
+ )
90
+ else:
91
+ # Harmonization mode (fast or neural)
92
+ from services.harmonization.harmonizer import harmonize_composite
93
+ result = await asyncio.to_thread(
94
+ harmonize_composite, composite, mask, original, strength, mode
95
+ )
96
+
97
+ return {
98
+ "image": _encode_image(result["image"]),
99
+ "mode": result["mode"],
100
+ "elapsed_ms": result["elapsed_ms"],
101
+ }
102
+
103
+
104
+ def _run_diffusion_inpaint(
105
+ composite: np.ndarray,
106
+ mask: np.ndarray,
107
+ original: np.ndarray | None,
108
+ strength: float,
109
+ ) -> dict:
110
+ """Run diffusion inpainting. Falls back to harmonization if unavailable."""
111
+ try:
112
+ from services.harmonization.diffusion import generate_tile_inpaint
113
+ return generate_tile_inpaint(
114
+ room_image=original if original is not None else composite,
115
+ mask=mask,
116
+ tile_composite=composite,
117
+ strength=strength,
118
+ )
119
+ except ImportError:
120
+ print("[HARMONIZE] Diffusion module not available, falling back to fast harmonization.", flush=True)
121
+ from services.harmonization.harmonizer import harmonize_composite
122
+ return harmonize_composite(composite, mask, original, strength, "fast")
123
+ except Exception as exc:
124
+ print(f"[HARMONIZE] Diffusion inpainting failed: {exc}. Falling back.", flush=True)
125
+ from services.harmonization.harmonizer import harmonize_composite
126
+ return harmonize_composite(composite, mask, original, strength, "fast")
services/harmonization/__init__.py ADDED
File without changes
services/harmonization/color_transfer.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast color-statistics harmonization using Lab color space transfer.
2
+
3
+ Matches the foreground (tile composite) region's color distribution to the
4
+ background (room) region. This is a zero-model, pure-numpy approach that
5
+ runs in <20ms and handles the most visible artifact: color temperature
6
+ mismatch between pasted tiles and the room's ambient lighting.
7
+
8
+ Based on Reinhard et al. "Color Transfer between Images" (2001), adapted
9
+ for masked foreground/background regions.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import cv2
15
+ import numpy as np
16
+
17
+
18
+ def _rgb_to_lab(img: np.ndarray) -> np.ndarray:
19
+ """Convert uint8 RGB to float32 Lab."""
20
+ bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
21
+ return cv2.cvtColor(bgr, cv2.COLOR_BGR2Lab).astype(np.float32)
22
+
23
+
24
+ def _lab_to_rgb(lab: np.ndarray) -> np.ndarray:
25
+ """Convert float32 Lab to uint8 RGB."""
26
+ lab_u8 = np.clip(lab, 0, 255).astype(np.uint8)
27
+ bgr = cv2.cvtColor(lab_u8, cv2.COLOR_Lab2BGR)
28
+ return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
29
+
30
+
31
+ def harmonize_color_transfer(
32
+ composite: np.ndarray,
33
+ mask: np.ndarray,
34
+ strength: float = 0.7,
35
+ ) -> np.ndarray:
36
+ """Harmonize foreground region to match background color distribution.
37
+
38
+ Args:
39
+ composite: RGB uint8 image with tile already composited.
40
+ mask: uint8 mask — 255 = tile region, 0 = background.
41
+ strength: Blend strength (0 = no change, 1 = full transfer).
42
+
43
+ Returns:
44
+ Harmonized RGB uint8 image.
45
+ """
46
+ if strength <= 0:
47
+ return composite
48
+
49
+ fg_mask = mask > 127
50
+ bg_mask = ~fg_mask
51
+
52
+ if fg_mask.sum() < 100 or bg_mask.sum() < 100:
53
+ return composite
54
+
55
+ lab = _rgb_to_lab(composite)
56
+
57
+ # Compute mean/std for each channel in foreground and background
58
+ fg_pixels = lab[fg_mask] # (N, 3)
59
+ bg_pixels = lab[bg_mask] # (M, 3)
60
+
61
+ fg_mean = fg_pixels.mean(axis=0)
62
+ fg_std = fg_pixels.std(axis=0) + 1e-6
63
+ bg_mean = bg_pixels.mean(axis=0)
64
+ bg_std = bg_pixels.std(axis=0) + 1e-6
65
+
66
+ # Transfer: shift and scale foreground to match background stats
67
+ # Only transfer chromatic channels (a, b) fully; attenuate lightness transfer
68
+ # to preserve tile's intended brightness while matching color temperature.
69
+ result = lab.copy()
70
+ for c in range(3):
71
+ channel = lab[:, :, c]
72
+ transferred = (channel[fg_mask] - fg_mean[c]) * (bg_std[c] / fg_std[c]) + bg_mean[c]
73
+ # For lightness (L channel), reduce transfer strength to preserve tile brightness
74
+ channel_strength = strength * (0.3 if c == 0 else 1.0)
75
+ result[:, :, c][fg_mask] = channel[fg_mask] * (1 - channel_strength) + transferred * channel_strength
76
+
77
+ return _lab_to_rgb(result)
78
+
79
+
80
+ def harmonize_with_local_lighting(
81
+ composite: np.ndarray,
82
+ original: np.ndarray,
83
+ mask: np.ndarray,
84
+ strength: float = 0.7,
85
+ ) -> np.ndarray:
86
+ """Enhanced harmonization: color transfer + local lighting adaptation.
87
+
88
+ Uses the original room image to extract local lighting patterns and
89
+ applies them to the tile region for more natural integration.
90
+
91
+ Args:
92
+ composite: RGB uint8 image with tile composited.
93
+ original: RGB uint8 original room image (before tile).
94
+ mask: uint8 mask — 255 = tile region, 0 = background.
95
+ strength: Blend strength.
96
+
97
+ Returns:
98
+ Harmonized RGB uint8 image.
99
+ """
100
+ # Step 1: Basic color transfer
101
+ result = harmonize_color_transfer(composite, mask, strength)
102
+
103
+ if original is None or strength <= 0:
104
+ return result
105
+
106
+ fg_mask = mask > 127
107
+ if fg_mask.sum() < 100:
108
+ return result
109
+
110
+ # Step 2: Extract local color cast from original room image
111
+ # Blur original to get smooth lighting field
112
+ sigma = max(15, min(original.shape[:2]) // 20)
113
+ ksize = sigma * 2 + 1
114
+ original_blur = cv2.GaussianBlur(
115
+ original.astype(np.float32), (ksize, ksize), sigma
116
+ )
117
+ composite_blur = cv2.GaussianBlur(
118
+ result.astype(np.float32), (ksize, ksize), sigma
119
+ )
120
+
121
+ # Ratio of original-to-composite lighting in the tile region
122
+ # This captures local color gradients (e.g., warmer near downlights)
123
+ ratio = np.ones_like(original_blur)
124
+ valid = composite_blur > 5
125
+ ratio[valid] = original_blur[valid] / composite_blur[valid]
126
+ ratio = np.clip(ratio, 0.5, 2.0)
127
+
128
+ # Apply local lighting ratio only in foreground
129
+ result_f = result.astype(np.float32)
130
+ local_strength = strength * 0.4 # Subtle local lighting adaptation
131
+ adjusted = result_f * (1.0 + (ratio - 1.0) * local_strength)
132
+ adjusted = np.clip(adjusted, 0, 255)
133
+
134
+ output = result.copy()
135
+ output[fg_mask] = adjusted[fg_mask].astype(np.uint8)
136
+ return output
services/harmonization/diffusion.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Diffusion-based tile inpainting with SDXL + IP-Adapter.
2
+
3
+ Generates photorealistic tile rendering by inpainting the floor region
4
+ using a diffusion model conditioned on the tile texture as a reference.
5
+
6
+ Requires: pip install diffusers accelerate
7
+ VRAM: ~8GB in fp16 with CPU offloading enabled.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import time
13
+
14
+ import cv2
15
+ import numpy as np
16
+
17
+ import state
18
+
19
+ _pipeline = None
20
+ _load_attempted = False
21
+
22
+ # Maximum dimension for diffusion inference (SDXL works best at 1024)
23
+ _DIFFUSION_MAX_DIM = 1024
24
+
25
+
26
+ def _load_pipeline():
27
+ """Load SDXL inpainting pipeline with IP-Adapter. Lazy, one-time."""
28
+ global _pipeline, _load_attempted
29
+ if _load_attempted:
30
+ return _pipeline
31
+ _load_attempted = True
32
+
33
+ try:
34
+ import torch
35
+ from diffusers import AutoPipelineForInpainting
36
+
37
+ print("[DIFFUSION] Loading SDXL inpainting pipeline...", flush=True)
38
+ t0 = time.perf_counter()
39
+
40
+ _pipe = AutoPipelineForInpainting.from_pretrained(
41
+ "diffusers/stable-diffusion-xl-1.0-inpainting-0.1",
42
+ torch_dtype=torch.float16,
43
+ variant="fp16",
44
+ )
45
+
46
+ # CPU offload keeps VRAM usage manageable alongside other models
47
+ _pipe.enable_model_cpu_offload()
48
+
49
+ # Try loading IP-Adapter for tile reference conditioning
50
+ try:
51
+ _pipe.load_ip_adapter(
52
+ "h94/IP-Adapter",
53
+ subfolder="sdxl_models",
54
+ weight_name="ip-adapter_sdxl.bin",
55
+ )
56
+ _pipe.set_ip_adapter_scale(0.6)
57
+ print("[DIFFUSION] IP-Adapter loaded for tile reference conditioning.", flush=True)
58
+ except Exception as exc:
59
+ print(f"[DIFFUSION] IP-Adapter not available ({exc}). Using prompt-only mode.", flush=True)
60
+
61
+ elapsed = time.perf_counter() - t0
62
+ print(f"[DIFFUSION] Pipeline loaded in {elapsed:.1f}s", flush=True)
63
+ _pipeline = _pipe
64
+ return _pipeline
65
+
66
+ except ImportError as exc:
67
+ print(f"[DIFFUSION] diffusers not installed: {exc}. Install with: pip install diffusers accelerate", flush=True)
68
+ return None
69
+ except Exception as exc:
70
+ print(f"[DIFFUSION] Failed to load pipeline: {exc}", flush=True)
71
+ return None
72
+
73
+
74
+ def _downscale(img: np.ndarray, max_dim: int) -> tuple[np.ndarray, float]:
75
+ """Downscale image to fit within max_dim, return (image, scale)."""
76
+ h, w = img.shape[:2]
77
+ scale = min(max_dim / max(h, w), 1.0)
78
+ if scale < 1.0:
79
+ new_w = max(8, int(w * scale) // 8 * 8) # SDXL needs multiples of 8
80
+ new_h = max(8, int(h * scale) // 8 * 8)
81
+ return cv2.resize(img, (new_w, new_h)), scale
82
+ # Ensure dimensions are multiples of 8
83
+ new_w = w // 8 * 8
84
+ new_h = h // 8 * 8
85
+ if new_w != w or new_h != h:
86
+ return cv2.resize(img, (new_w, new_h)), 1.0
87
+ return img, 1.0
88
+
89
+
90
+ def generate_tile_inpaint(
91
+ room_image: np.ndarray,
92
+ mask: np.ndarray,
93
+ tile_composite: np.ndarray,
94
+ strength: float = 0.85,
95
+ num_steps: int = 20,
96
+ tile_reference: np.ndarray | None = None,
97
+ ) -> dict:
98
+ """Generate photorealistic tile rendering using diffusion inpainting.
99
+
100
+ Args:
101
+ room_image: RGB uint8 — original room (or composite if original unavailable).
102
+ mask: uint8 — floor region to inpaint (255 = floor).
103
+ tile_composite: RGB uint8 — shader-composited image (used as init image).
104
+ strength: Denoising strength (0.7-0.95, higher = more creative).
105
+ num_steps: Diffusion steps (15-30, more = higher quality).
106
+ tile_reference: RGB uint8 — tile texture image for IP-Adapter conditioning.
107
+
108
+ Returns:
109
+ Dict with "image" (RGB uint8), "mode", "elapsed_ms".
110
+ """
111
+ from PIL import Image as PILImage
112
+
113
+ t0 = time.perf_counter()
114
+
115
+ pipe = _load_pipeline()
116
+ if pipe is None:
117
+ # Fallback to color transfer harmonization
118
+ from services.harmonization.harmonizer import harmonize_composite
119
+ return harmonize_composite(tile_composite, mask, room_image, strength, "fast")
120
+
121
+ orig_h, orig_w = room_image.shape[:2]
122
+
123
+ # Downscale for diffusion
124
+ init_img, scale = _downscale(tile_composite, _DIFFUSION_MAX_DIM)
125
+ mask_img, _ = _downscale(mask, _DIFFUSION_MAX_DIM)
126
+
127
+ # Ensure mask is binary
128
+ mask_img = (mask_img > 127).astype(np.uint8) * 255
129
+
130
+ # Convert to PIL
131
+ init_pil = PILImage.fromarray(init_img)
132
+ mask_pil = PILImage.fromarray(mask_img)
133
+
134
+ prompt = (
135
+ "photorealistic interior floor, polished tile surface, "
136
+ "natural room lighting, professional architectural photography, "
137
+ "high quality, sharp detail"
138
+ )
139
+ negative_prompt = (
140
+ "blurry, distorted, unrealistic, cartoon, painting, "
141
+ "low quality, artifacts, noise"
142
+ )
143
+
144
+ # Build generation kwargs
145
+ gen_kwargs = dict(
146
+ prompt=prompt,
147
+ negative_prompt=negative_prompt,
148
+ image=init_pil,
149
+ mask_image=mask_pil,
150
+ strength=min(strength, 0.95),
151
+ num_inference_steps=num_steps,
152
+ guidance_scale=7.5,
153
+ )
154
+
155
+ # Add IP-Adapter image if available
156
+ if tile_reference is not None and hasattr(pipe, "ip_adapter_scale"):
157
+ try:
158
+ ref_pil = PILImage.fromarray(tile_reference).resize((256, 256))
159
+ gen_kwargs["ip_adapter_image"] = ref_pil
160
+ except Exception:
161
+ pass
162
+
163
+ result_pil = pipe(**gen_kwargs).images[0]
164
+ result = np.array(result_pil)
165
+
166
+ # Upscale back to original resolution
167
+ if result.shape[0] != orig_h or result.shape[1] != orig_w:
168
+ result = cv2.resize(result, (orig_w, orig_h))
169
+
170
+ # Only replace the masked region — keep the rest of the room untouched
171
+ fg = mask > 127
172
+ output = room_image.copy()
173
+ output[fg] = result[fg]
174
+
175
+ elapsed = (time.perf_counter() - t0) * 1000
176
+ print(f"[DIFFUSION] Generated in {elapsed:.0f}ms ({num_steps} steps, strength={strength})", flush=True)
177
+
178
+ return {
179
+ "image": output,
180
+ "mode": "generate",
181
+ "elapsed_ms": round(elapsed, 1),
182
+ }
services/harmonization/harmonizer.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image harmonization for tile composite blending.
2
+
3
+ Provides two modes:
4
+ - "fast": Color-statistics transfer (~20ms, no model, always available)
5
+ - "neural": Neural harmonization model (~200-500ms, requires model download)
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+
12
+ import cv2
13
+ import numpy as np
14
+
15
+ from services.harmonization.color_transfer import (
16
+ harmonize_color_transfer,
17
+ harmonize_with_local_lighting,
18
+ )
19
+
20
+
21
+ def harmonize_composite(
22
+ composite: np.ndarray,
23
+ mask: np.ndarray,
24
+ original: np.ndarray | None = None,
25
+ strength: float = 0.7,
26
+ mode: str = "fast",
27
+ ) -> dict:
28
+ """Harmonize a tile composite to match room lighting/color.
29
+
30
+ Args:
31
+ composite: RGB uint8 — room image with tile applied by frontend shader.
32
+ mask: uint8 — where tile was applied (255 = tile, 0 = background).
33
+ original: RGB uint8 — original room image before tile (optional, improves quality).
34
+ strength: 0.0-1.0 harmonization strength.
35
+ mode: "fast" (color transfer) or "neural" (model-based).
36
+
37
+ Returns:
38
+ Dict with "image" (RGB uint8), "mode", "elapsed_ms".
39
+ """
40
+ t0 = time.perf_counter()
41
+
42
+ if mode == "neural":
43
+ result = _neural_harmonize(composite, mask, strength)
44
+ if result is not None:
45
+ elapsed = (time.perf_counter() - t0) * 1000
46
+ print(f"[HARMONIZE] neural mode: {elapsed:.0f}ms", flush=True)
47
+ return {"image": result, "mode": "neural", "elapsed_ms": round(elapsed, 1)}
48
+ # Fall through to fast mode if neural unavailable
49
+ print("[HARMONIZE] Neural model unavailable, falling back to fast mode.", flush=True)
50
+
51
+ if original is not None:
52
+ result = harmonize_with_local_lighting(composite, original, mask, strength)
53
+ else:
54
+ result = harmonize_color_transfer(composite, mask, strength)
55
+
56
+ elapsed = (time.perf_counter() - t0) * 1000
57
+ print(f"[HARMONIZE] fast mode: {elapsed:.0f}ms", flush=True)
58
+ return {"image": result, "mode": "fast", "elapsed_ms": round(elapsed, 1)}
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Neural harmonization (optional — loaded on first use)
63
+ # ---------------------------------------------------------------------------
64
+
65
+ _neural_model = None
66
+ _neural_load_attempted = False
67
+
68
+
69
+ def _neural_harmonize(
70
+ composite: np.ndarray,
71
+ mask: np.ndarray,
72
+ strength: float,
73
+ ) -> np.ndarray | None:
74
+ """Try neural harmonization. Returns None if model unavailable."""
75
+ global _neural_model, _neural_load_attempted
76
+
77
+ if _neural_load_attempted and _neural_model is None:
78
+ return None
79
+
80
+ if _neural_model is None:
81
+ _neural_load_attempted = True
82
+ _neural_model = _try_load_neural_model()
83
+ if _neural_model is None:
84
+ return None
85
+
86
+ return _run_neural_model(_neural_model, composite, mask, strength)
87
+
88
+
89
+ def _try_load_neural_model():
90
+ """Attempt to load a neural harmonization model."""
91
+ try:
92
+ import torch
93
+ import state
94
+
95
+ # Try loading CDTNet or similar from HuggingFace
96
+ # For now, check if a local model checkpoint exists
97
+ from pathlib import Path
98
+ model_path = Path("data/models/harmonizer")
99
+ if not model_path.exists():
100
+ print("[HARMONIZE] No neural harmonization model found at data/models/harmonizer", flush=True)
101
+ return None
102
+
103
+ print(f"[HARMONIZE] Loading neural harmonization model from {model_path}", flush=True)
104
+ # Placeholder for actual model loading
105
+ # model = HarmonizerNet.from_pretrained(model_path).to(state.device).eval()
106
+ # return model
107
+ return None
108
+ except Exception as exc:
109
+ print(f"[HARMONIZE] Failed to load neural model: {exc}", flush=True)
110
+ return None
111
+
112
+
113
+ def _run_neural_model(model, composite: np.ndarray, mask: np.ndarray, strength: float) -> np.ndarray | None:
114
+ """Run neural harmonization model inference."""
115
+ try:
116
+ import torch
117
+ import state
118
+
119
+ h, w = composite.shape[:2]
120
+ # Downscale for speed
121
+ max_dim = 512
122
+ scale = min(max_dim / max(h, w), 1.0)
123
+ if scale < 1.0:
124
+ new_w, new_h = int(w * scale), int(h * scale)
125
+ img_s = cv2.resize(composite, (new_w, new_h))
126
+ mask_s = cv2.resize(mask, (new_w, new_h), interpolation=cv2.INTER_NEAREST)
127
+ else:
128
+ img_s, mask_s = composite, mask
129
+
130
+ # Convert to tensor
131
+ img_t = torch.from_numpy(img_s).float().permute(2, 0, 1).unsqueeze(0) / 255.0
132
+ mask_t = torch.from_numpy(mask_s).float().unsqueeze(0).unsqueeze(0) / 255.0
133
+ img_t = img_t.to(state.device)
134
+ mask_t = mask_t.to(state.device)
135
+
136
+ with torch.inference_mode():
137
+ output_t = model(img_t, mask_t)
138
+
139
+ output = (output_t.squeeze(0).permute(1, 2, 0) * 255).clamp(0, 255).cpu().numpy().astype(np.uint8)
140
+
141
+ # Upscale back
142
+ if scale < 1.0:
143
+ output = cv2.resize(output, (w, h))
144
+
145
+ # Blend with original based on strength
146
+ if strength < 1.0:
147
+ fg = mask > 127
148
+ blended = composite.copy()
149
+ blended[fg] = (composite[fg].astype(np.float32) * (1 - strength) + output[fg].astype(np.float32) * strength).astype(np.uint8)
150
+ return blended
151
+ return output
152
+ except Exception as exc:
153
+ print(f"[HARMONIZE] Neural inference failed: {exc}", flush=True)
154
+ return None
services/lighting/intrinsic.py CHANGED
@@ -135,62 +135,83 @@ def align_intrinsic_shading_to_luminance(
135
  # Intrinsic lighting maps
136
  # ---------------------------------------------------------------------------
137
 
 
 
 
138
  def build_intrinsic_lighting_maps(
139
  img_np: np.ndarray,
140
  surface_mask: np.ndarray,
141
  replaced_material_mask: np.ndarray | None = None,
142
  ) -> dict[str, np.ndarray | None] | None:
 
143
  if not surface_mask.any() or intrinsic_models is None:
144
  return None
145
 
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
153
 
154
- relative = normalize_relative_shading(shading, surface_mask)
155
  if relative is None:
156
  return None
157
- relative, alignment = align_intrinsic_shading_to_luminance(relative, img_np, surface_mask)
158
- smoothed = smooth_relative_lighting(relative, surface_mask)
159
  if smoothed is None:
160
  return None
161
 
162
- luminance_maps = build_luminance_lighting_maps(
163
- img_np,
164
- surface_mask,
165
- replaced_material_mask,
166
- )
167
  if luminance_maps and luminance_maps.get("shadeMap") is not None:
168
  observed = decode_relative_map(
169
  luminance_maps["shadeMap"],
170
  SHADE_MAP_MIN,
171
  SHADE_MAP_MAX,
172
  )
173
- smoothed = preserve_observed_lighting(smoothed, observed, surface_mask)
174
  alignment = f"{alignment}+observed-lighting"
175
- smoothed = suppress_replaced_material_lighting(
176
- smoothed,
177
- surface_mask,
178
- replaced_material_mask,
179
- )
180
  print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True)
181
 
182
  from services.lighting.showroom import build_showroom_shade_map_from_relative
183
  from services.lighting.reflection import build_reflection_map
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  return {
186
- "shadeMap": encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX),
187
- "showroomShadeMap": build_showroom_shade_map_from_relative(smoothed, surface_mask),
188
- "reflectionMap": build_reflection_map(
189
- img_np,
190
- surface_mask,
191
- smoothed,
192
- replaced_material_mask,
193
- ),
194
  }
195
  except Exception as exc:
196
  print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
 
135
  # Intrinsic lighting maps
136
  # ---------------------------------------------------------------------------
137
 
138
+ _INTRINSIC_MAX_DIM = 512 # Intrinsic model runs at reduced resolution for speed
139
+
140
+
141
  def build_intrinsic_lighting_maps(
142
  img_np: np.ndarray,
143
  surface_mask: np.ndarray,
144
  replaced_material_mask: np.ndarray | None = None,
145
  ) -> dict[str, np.ndarray | None] | None:
146
+ import cv2
147
  if not surface_mask.any() or intrinsic_models is None:
148
  return None
149
 
150
  try:
151
+ orig_h, orig_w = img_np.shape[:2]
152
+
153
+ # Downscale for faster intrinsic inference
154
+ largest = max(orig_h, orig_w)
155
+ if largest > _INTRINSIC_MAX_DIM:
156
+ scale = _INTRINSIC_MAX_DIM / float(largest)
157
+ new_w = max(1, int(round(orig_w * scale)))
158
+ new_h = max(1, int(round(orig_h * scale)))
159
+ img_s = cv2.resize(img_np, (new_w, new_h), interpolation=cv2.INTER_AREA)
160
+ mask_s = cv2.resize(surface_mask.astype(np.uint8), (new_w, new_h), interpolation=cv2.INTER_NEAREST)
161
+ repl_s = cv2.resize(replaced_material_mask.astype(np.uint8), (new_w, new_h), interpolation=cv2.INTER_NEAREST) if replaced_material_mask is not None else None
162
+ else:
163
+ img_s, mask_s, repl_s = img_np, surface_mask, replaced_material_mask
164
+
165
+ img_float = img_s.astype(np.float32) / 255.0
166
  from intrinsic.pipeline import run_pipeline
167
  results = run_pipeline(intrinsic_models, img_float, device=str(device))
168
  shading = extract_intrinsic_shading(results)
169
  if shading is None:
170
  return None
171
 
172
+ relative = normalize_relative_shading(shading, mask_s)
173
  if relative is None:
174
  return None
175
+ relative, alignment = align_intrinsic_shading_to_luminance(relative, img_s, mask_s)
176
+ smoothed = smooth_relative_lighting(relative, mask_s)
177
  if smoothed is None:
178
  return None
179
 
180
+ luminance_maps = build_luminance_lighting_maps(img_s, mask_s, repl_s)
 
 
 
 
181
  if luminance_maps and luminance_maps.get("shadeMap") is not None:
182
  observed = decode_relative_map(
183
  luminance_maps["shadeMap"],
184
  SHADE_MAP_MIN,
185
  SHADE_MAP_MAX,
186
  )
187
+ smoothed = preserve_observed_lighting(smoothed, observed, mask_s)
188
  alignment = f"{alignment}+observed-lighting"
189
+ smoothed = suppress_replaced_material_lighting(smoothed, mask_s, repl_s)
 
 
 
 
190
  print(f"[LIGHTING] intrinsic shading alignment={alignment}", flush=True)
191
 
192
  from services.lighting.showroom import build_showroom_shade_map_from_relative
193
  from services.lighting.reflection import build_reflection_map
194
 
195
+ shade_encoded = encode_relative_map(smoothed, SHADE_MAP_MIN, SHADE_MAP_MAX)
196
+ showroom_encoded = build_showroom_shade_map_from_relative(smoothed, mask_s)
197
+ reflection_encoded = build_reflection_map(img_s, mask_s, smoothed, repl_s)
198
+
199
+ # Upscale back to original resolution if we downscaled
200
+ if largest > _INTRINSIC_MAX_DIM:
201
+ def _up(arr):
202
+ if arr is None:
203
+ return None
204
+ if arr.shape[0] == orig_h and arr.shape[1] == orig_w:
205
+ return arr
206
+ return cv2.resize(arr, (orig_w, orig_h), interpolation=cv2.INTER_LINEAR)
207
+ shade_encoded = _up(shade_encoded)
208
+ showroom_encoded = _up(showroom_encoded)
209
+ reflection_encoded = _up(reflection_encoded)
210
+
211
  return {
212
+ "shadeMap": shade_encoded,
213
+ "showroomShadeMap": showroom_encoded,
214
+ "reflectionMap": reflection_encoded,
 
 
 
 
 
215
  }
216
  except Exception as exc:
217
  print(f"Intrinsic shading decomposition failed: {exc}. Falling back to default luminance shading.", flush=True)
services/lighting/shading.py CHANGED
@@ -100,6 +100,43 @@ def suppress_replaced_material_lighting(
100
  # Luminance-based lighting maps
101
  # ---------------------------------------------------------------------------
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  def build_luminance_lighting_maps(
104
  img_np: np.ndarray,
105
  surface_mask: np.ndarray,
@@ -108,8 +145,15 @@ def build_luminance_lighting_maps(
108
  if not surface_mask.any():
109
  return None
110
 
111
- mask = surface_mask.astype(np.uint8)
112
- luminance = image_linear_luminance(img_np)
 
 
 
 
 
 
 
113
  h, w = mask.shape[:2]
114
  floor_values = luminance[mask > 0]
115
  if floor_values.size < max(256, int(h * w * 0.002)):
@@ -126,7 +170,7 @@ def build_luminance_lighting_maps(
126
  relative = suppress_replaced_material_lighting(
127
  relative,
128
  mask,
129
- replaced_material_mask,
130
  )
131
  shade = smooth_relative_lighting(relative, mask)
132
  if shade is None:
@@ -135,15 +179,25 @@ def build_luminance_lighting_maps(
135
  from services.lighting.showroom import build_showroom_shade_map_from_relative
136
  from services.lighting.reflection import build_reflection_map
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  return {
139
- "shadeMap": encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX),
140
- "showroomShadeMap": build_showroom_shade_map_from_relative(shade, mask),
141
- "reflectionMap": build_reflection_map(
142
- img_np,
143
- surface_mask,
144
- None,
145
- replaced_material_mask,
146
- ),
147
  }
148
 
149
 
 
100
  # Luminance-based lighting maps
101
  # ---------------------------------------------------------------------------
102
 
103
+ _LIGHTING_MAX_DIM = 800 # Compute lighting at this resolution for speed
104
+
105
+
106
+ def _downscale_for_lighting(
107
+ img_np: np.ndarray,
108
+ surface_mask: np.ndarray,
109
+ replaced_material_mask: np.ndarray | None,
110
+ ):
111
+ """Downscale inputs if the image exceeds _LIGHTING_MAX_DIM.
112
+
113
+ Returns (img, mask, replaced, scale) — scale is 1.0 when no resize needed.
114
+ """
115
+ h, w = img_np.shape[:2]
116
+ largest = max(h, w)
117
+ if largest <= _LIGHTING_MAX_DIM:
118
+ return img_np, surface_mask, replaced_material_mask, 1.0
119
+
120
+ scale = _LIGHTING_MAX_DIM / float(largest)
121
+ new_w = max(1, int(round(w * scale)))
122
+ new_h = max(1, int(round(h * scale)))
123
+ img_s = cv2.resize(img_np, (new_w, new_h), interpolation=cv2.INTER_AREA)
124
+ mask_s = cv2.resize(surface_mask.astype(np.uint8), (new_w, new_h), interpolation=cv2.INTER_NEAREST)
125
+ repl_s = None
126
+ if replaced_material_mask is not None:
127
+ repl_s = cv2.resize(replaced_material_mask.astype(np.uint8), (new_w, new_h), interpolation=cv2.INTER_NEAREST)
128
+ return img_s, mask_s, repl_s, scale
129
+
130
+
131
+ def _upscale_map(encoded: np.ndarray | None, target_h: int, target_w: int) -> np.ndarray | None:
132
+ """Upscale an encoded uint8 map back to original resolution."""
133
+ if encoded is None:
134
+ return None
135
+ if encoded.shape[0] == target_h and encoded.shape[1] == target_w:
136
+ return encoded
137
+ return cv2.resize(encoded, (target_w, target_h), interpolation=cv2.INTER_LINEAR)
138
+
139
+
140
  def build_luminance_lighting_maps(
141
  img_np: np.ndarray,
142
  surface_mask: np.ndarray,
 
145
  if not surface_mask.any():
146
  return None
147
 
148
+ orig_h, orig_w = surface_mask.shape[:2]
149
+
150
+ # Downscale for speed — shade/reflection maps are low-frequency signals
151
+ img_s, mask_s, repl_s, scale = _downscale_for_lighting(
152
+ img_np, surface_mask, replaced_material_mask,
153
+ )
154
+
155
+ mask = mask_s.astype(np.uint8)
156
+ luminance = image_linear_luminance(img_s)
157
  h, w = mask.shape[:2]
158
  floor_values = luminance[mask > 0]
159
  if floor_values.size < max(256, int(h * w * 0.002)):
 
170
  relative = suppress_replaced_material_lighting(
171
  relative,
172
  mask,
173
+ repl_s,
174
  )
175
  shade = smooth_relative_lighting(relative, mask)
176
  if shade is None:
 
179
  from services.lighting.showroom import build_showroom_shade_map_from_relative
180
  from services.lighting.reflection import build_reflection_map
181
 
182
+ shade_encoded = encode_relative_map(shade, SHADE_MAP_MIN, SHADE_MAP_MAX)
183
+ showroom_encoded = build_showroom_shade_map_from_relative(shade, mask)
184
+ reflection_encoded = build_reflection_map(
185
+ img_s,
186
+ mask_s,
187
+ None,
188
+ repl_s,
189
+ )
190
+
191
+ # Upscale back to original resolution if we downscaled
192
+ if scale < 1.0:
193
+ shade_encoded = _upscale_map(shade_encoded, orig_h, orig_w)
194
+ showroom_encoded = _upscale_map(showroom_encoded, orig_h, orig_w)
195
+ reflection_encoded = _upscale_map(reflection_encoded, orig_h, orig_w)
196
+
197
  return {
198
+ "shadeMap": shade_encoded,
199
+ "showroomShadeMap": showroom_encoded,
200
+ "reflectionMap": reflection_encoded,
 
 
 
 
 
201
  }
202
 
203
 
services/pipeline/builder.py CHANGED
@@ -150,9 +150,36 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
150
  if d:
151
  debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)
152
 
153
- # --- Surface UV mapping ---
154
  if progress_callback:
155
  progress_callback(PipelinePhase.SURFACE_MAPPING, 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  t0 = time.perf_counter()
157
  surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
158
  use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
@@ -165,32 +192,6 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
165
  if progress_callback:
166
  progress_callback(PipelinePhase.SURFACE_MAPPING, 100)
167
 
168
- # --- Lighting ---
169
- if progress_callback:
170
- progress_callback(PipelinePhase.LIGHTING, 0)
171
- t0 = time.perf_counter()
172
- lighting_maps, shade_map, showroom_shade_map, reflection_map = None, None, None, None
173
- lighting_source, intrinsic_lighting_used = None, False
174
- if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
175
- if state.intrinsic_models is None:
176
- _load_intrinsic_model()
177
- if state.intrinsic_models is not None:
178
- lighting_maps = build_intrinsic_lighting_maps(img_np, surface_mask, replaced_material_mask)
179
- if lighting_maps and lighting_maps.get("shadeMap") is not None:
180
- from config.models import INTRINSIC_MODEL_VERSION
181
- lighting_source, intrinsic_lighting_used = f"intrinsic-{INTRINSIC_MODEL_VERSION}", True
182
- if ENABLE_SHADING_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
183
- lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
184
- if lighting_maps and lighting_maps.get("shadeMap") is not None:
185
- lighting_source = "luminance"
186
- if lighting_maps:
187
- shade_map, showroom_shade_map, reflection_map = lighting_maps.get("shadeMap"), lighting_maps.get("showroomShadeMap"), lighting_maps.get("reflectionMap")
188
- shade_statistics = lighting_map_statistics(shade_map, surface_mask)
189
- el = (time.perf_counter() - t0) * 1000
190
- _log_stage("Lighting", t0, f"source={lighting_source}")
191
- if d:
192
- debug_stages.record_lighting(d, shade_map, showroom_shade_map, reflection_map, surface_mask, lighting_source, el)
193
-
194
  wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
195
  wall_components, wall_protected_mask = (
196
  wall_surface_components(seg_map, min_floor_area, geometry) if ENABLE_WALL_SEGMENTS else ([], np.zeros_like(wall_mask)))
@@ -210,9 +211,6 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
210
  for _, cm in wall_components:
211
  wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))
212
 
213
- if progress_callback:
214
- progress_callback(PipelinePhase.LIGHTING, 100)
215
-
216
  # --- Floor direction ---
217
  if progress_callback:
218
  progress_callback(PipelinePhase.DIRECTION, 0)
@@ -239,6 +237,19 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
239
  if progress_callback:
240
  progress_callback(PipelinePhase.DIRECTION, 100)
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  # Collect pre-computed wall lighting results
243
  wall_lighting_results: list[dict | None] = []
244
  if wall_executor:
 
150
  if d:
151
  debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)
152
 
153
+ # --- UV Mapping + Lighting (parallel — both depend only on surface_mask) ---
154
  if progress_callback:
155
  progress_callback(PipelinePhase.SURFACE_MAPPING, 0)
156
+ progress_callback(PipelinePhase.LIGHTING, 0)
157
+
158
+ # Kick off lighting in a background thread while UV mapping runs on main thread
159
+ from concurrent.futures import ThreadPoolExecutor as _LightPool
160
+
161
+ def _compute_lighting():
162
+ _lighting_maps = None
163
+ _lighting_source, _intrinsic_used = None, False
164
+ if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
165
+ if state.intrinsic_models is None:
166
+ _load_intrinsic_model()
167
+ if state.intrinsic_models is not None:
168
+ _lighting_maps = build_intrinsic_lighting_maps(img_np, surface_mask, replaced_material_mask)
169
+ if _lighting_maps and _lighting_maps.get("shadeMap") is not None:
170
+ from config.models import INTRINSIC_MODEL_VERSION
171
+ _lighting_source, _intrinsic_used = f"intrinsic-{INTRINSIC_MODEL_VERSION}", True
172
+ if ENABLE_SHADING_TRANSFER and (not _lighting_maps or _lighting_maps.get("shadeMap") is None):
173
+ _lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
174
+ if _lighting_maps and _lighting_maps.get("shadeMap") is not None:
175
+ _lighting_source = "luminance"
176
+ return _lighting_maps, _lighting_source, _intrinsic_used
177
+
178
+ t_lighting_start = time.perf_counter()
179
+ _light_pool = _LightPool(max_workers=1)
180
+ _lighting_future = _light_pool.submit(_compute_lighting)
181
+
182
+ # UV mapping runs on main thread concurrently with lighting
183
  t0 = time.perf_counter()
184
  surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
185
  use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
 
192
  if progress_callback:
193
  progress_callback(PipelinePhase.SURFACE_MAPPING, 100)
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
196
  wall_components, wall_protected_mask = (
197
  wall_surface_components(seg_map, min_floor_area, geometry) if ENABLE_WALL_SEGMENTS else ([], np.zeros_like(wall_mask)))
 
211
  for _, cm in wall_components:
212
  wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))
213
 
 
 
 
214
  # --- Floor direction ---
215
  if progress_callback:
216
  progress_callback(PipelinePhase.DIRECTION, 0)
 
237
  if progress_callback:
238
  progress_callback(PipelinePhase.DIRECTION, 100)
239
 
240
+
241
+ lighting_maps, lighting_source, intrinsic_lighting_used = _lighting_future.result()
242
+ _light_pool.shutdown(wait=False)
243
+ shade_map, showroom_shade_map, reflection_map = None, None, None
244
+ if lighting_maps:
245
+ shade_map, showroom_shade_map, reflection_map = lighting_maps.get("shadeMap"), lighting_maps.get("showroomShadeMap"), lighting_maps.get("reflectionMap")
246
+ shade_statistics = lighting_map_statistics(shade_map, surface_mask)
247
+ _log_stage("Lighting", t_lighting_start, f"source={lighting_source}")
248
+ if d:
249
+ debug_stages.record_lighting(d, shade_map, showroom_shade_map, reflection_map, surface_mask, lighting_source, (time.perf_counter() - t_lighting_start) * 1000)
250
+ if progress_callback:
251
+ progress_callback(PipelinePhase.LIGHTING, 100)
252
+
253
  # Collect pre-computed wall lighting results
254
  wall_lighting_results: list[dict | None] = []
255
  if wall_executor: