github-actions[bot] commited on
Commit
fbb8e8b
·
1 Parent(s): bdc9170

Automated Deploy: f83e1253522cda4179e67ce702b25272f861d59a

Browse files
Files changed (1) hide show
  1. services/harmonization/diffusion.py +145 -181
services/harmonization/diffusion.py CHANGED
@@ -1,70 +1,17 @@
1
- """Diffusion-based tile inpainting via Hugging Face Inference API.
2
 
3
- Sends the composited room image + floor mask to a hosted SDXL inpainting
4
- model on HF's Inference API. This avoids loading a multi-GB model locally
5
- and works on any hardware (the Space's GPU is already occupied by
6
- segmentation / depth / geometry models).
7
-
8
- Requires: pip install huggingface-hub (already in requirements-base)
9
  """
10
 
11
  from __future__ import annotations
12
 
13
- import io
14
- import os
15
  import time
 
16
 
17
  import cv2
18
  import numpy as np
19
- from PIL import Image as PILImage
20
-
21
- # ---------------------------------------------------------------------------
22
- # Configuration
23
- # ---------------------------------------------------------------------------
24
-
25
- # Model to call via HF Inference API
26
- _HF_INPAINT_MODEL = os.getenv(
27
- "HF_INPAINT_MODEL",
28
- "stabilityai/stable-diffusion-xl-base-1.0",
29
- )
30
-
31
- _HF_TOKEN = os.getenv("HF_TOKEN", None)
32
-
33
- # Max dimension to send (keeps latency reasonable)
34
- _MAX_DIM = 1024
35
-
36
-
37
- def _get_client():
38
- """Get a HuggingFace InferenceClient (lazy, reused)."""
39
- from huggingface_hub import InferenceClient
40
-
41
- return InferenceClient(token=_HF_TOKEN)
42
-
43
-
44
- def _to_pil(arr: np.ndarray) -> PILImage.Image:
45
- if arr.ndim == 2:
46
- return PILImage.fromarray(arr, mode="L")
47
- return PILImage.fromarray(arr)
48
-
49
-
50
- def _pil_to_bytes(img: PILImage.Image, fmt: str = "PNG") -> bytes:
51
- buf = io.BytesIO()
52
- img.save(buf, format=fmt)
53
- return buf.getvalue()
54
-
55
-
56
- def _downscale(img: np.ndarray, max_dim: int) -> tuple[np.ndarray, float]:
57
- h, w = img.shape[:2]
58
- scale = min(max_dim / max(h, w), 1.0)
59
- if scale < 1.0:
60
- new_w = max(8, int(w * scale) // 8 * 8)
61
- new_h = max(8, int(h * scale) // 8 * 8)
62
- return cv2.resize(img, (new_w, new_h)), scale
63
- new_w = w // 8 * 8
64
- new_h = h // 8 * 8
65
- if new_w != w or new_h != h:
66
- return cv2.resize(img, (new_w, new_h)), 1.0
67
- return img, 1.0
68
 
69
 
70
  def generate_tile_inpaint(
@@ -75,164 +22,181 @@ def generate_tile_inpaint(
75
  num_steps: int = 25,
76
  tile_reference: np.ndarray | None = None,
77
  ) -> dict:
78
- """Generate photorealistic tile rendering using HF Inference API.
 
 
 
 
79
 
80
  Args:
81
- room_image: RGB uint8 — original room (or composite if unavailable).
82
- mask: uint8 — floor region to inpaint (255 = floor).
83
- tile_composite: RGB uint8 — shader-composited image (used as init).
84
- strength: Denoising strength.
85
- num_steps: Diffusion steps.
86
- tile_reference: unused (kept for API compat).
87
 
88
  Returns:
89
  Dict with "image" (RGB uint8), "mode", "elapsed_ms".
90
  """
91
  t0 = time.perf_counter()
92
- orig_h, orig_w = tile_composite.shape[:2]
93
-
94
- # Downscale for inference
95
- init_img, scale = _downscale(tile_composite, _MAX_DIM)
96
- mask_img, _ = _downscale(mask, _MAX_DIM)
97
- mask_img = (mask_img > 127).astype(np.uint8) * 255
98
-
99
- prompt = (
100
- "photorealistic interior floor with polished tiles, "
101
- "natural room lighting, professional architectural photography, "
102
- "seamless realistic flooring, high quality, sharp detail"
103
- )
104
 
105
  try:
106
- client = _get_client()
107
-
108
- # Use text_to_image with image+mask for inpainting
109
- init_pil = _to_pil(init_img)
110
- mask_pil = _to_pil(mask_img)
111
-
112
- print(
113
- f"[DIFFUSION] Calling HF Inference API: model={_HF_INPAINT_MODEL}, "
114
- f"size={init_img.shape[1]}x{init_img.shape[0]}, strength={strength}",
115
- flush=True,
116
  )
117
 
118
- # Call the inpainting endpoint
119
- result_pil = client.image_to_image(
120
- image=init_pil,
121
- prompt=prompt,
122
- negative_prompt="blurry, distorted, unrealistic, cartoon, low quality, artifacts",
123
- model=_HF_INPAINT_MODEL,
124
- strength=min(strength, 0.80),
125
- guidance_scale=7.5,
126
- num_inference_steps=num_steps,
127
- )
128
-
129
- result = np.array(result_pil.convert("RGB"))
130
-
131
- # Resize back to downscaled dimensions if API returned different size
132
- dh, dw = init_img.shape[:2]
133
- if result.shape[0] != dh or result.shape[1] != dw:
134
- result = cv2.resize(result, (dw, dh))
135
-
136
- # Upscale back to original resolution
137
- if result.shape[0] != orig_h or result.shape[1] != orig_w:
138
- result = cv2.resize(result, (orig_w, orig_h))
139
-
140
- # Only replace the masked region
141
- fg = mask > 127
142
- output = tile_composite.copy()
143
- output[fg] = result[fg]
144
-
145
  elapsed = (time.perf_counter() - t0) * 1000
146
- print(f"[DIFFUSION] HF API completed in {elapsed:.0f}ms", flush=True)
147
 
148
  return {
149
- "image": output,
150
  "mode": "generate",
151
  "elapsed_ms": round(elapsed, 1),
152
  }
153
 
154
  except Exception as exc:
155
  elapsed = (time.perf_counter() - t0) * 1000
156
- print(f"[DIFFUSION] HF Inference API failed ({elapsed:.0f}ms): {exc}", flush=True)
 
 
 
157
 
158
- # Fallback: try a stronger local color harmonization instead of invisible fast mode
159
- try:
160
- return _strong_harmonize(tile_composite, mask, room_image, strength)
161
- except Exception as fallback_exc:
162
- print(f"[DIFFUSION] Strong harmonize fallback also failed: {fallback_exc}", flush=True)
163
- from services.harmonization.harmonizer import harmonize_composite
164
- return harmonize_composite(tile_composite, mask, room_image, strength, "fast")
165
 
166
-
167
- def _strong_harmonize(
168
  composite: np.ndarray,
 
169
  mask: np.ndarray,
170
- original: np.ndarray | None,
171
  strength: float,
172
- ) -> dict:
173
- """Stronger local harmonization that produces visible results.
174
-
175
- Uses histogram matching + local lighting adaptation for a more noticeable
176
- effect than the basic color transfer.
 
 
 
177
  """
178
- t0 = time.perf_counter()
179
-
180
  fg = mask > 127
181
- if original is None:
182
- original = composite
183
 
184
- # Convert to LAB for perceptual matching
185
- comp_lab = cv2.cvtColor(composite, cv2.COLOR_RGB2LAB).astype(np.float32)
186
- orig_lab = cv2.cvtColor(original, cv2.COLOR_RGB2LAB).astype(np.float32)
187
 
188
- # Get background (non-tile) stats from original
189
- bg = ~fg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  result_lab = comp_lab.copy()
191
 
192
- for ch in range(3):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  fg_vals = comp_lab[fg, ch]
194
  bg_vals = orig_lab[bg, ch]
195
 
196
- if len(fg_vals) == 0 or len(bg_vals) == 0:
197
  continue
198
 
199
- fg_mean, fg_std = fg_vals.mean(), fg_vals.std() + 1e-6
200
- bg_mean, bg_std = bg_vals.mean(), bg_vals.std() + 1e-6
 
 
201
 
202
- # Transfer color statistics
203
  transferred = (fg_vals - fg_mean) * (bg_std / fg_std) + bg_mean
204
- result_lab[fg, ch] = fg_vals * (1 - strength) + transferred * strength
205
-
206
- # Local lighting adaptation using gaussian blur of original
207
- blur_size = max(composite.shape[0], composite.shape[1]) // 4 | 1
208
- orig_blur = cv2.GaussianBlur(orig_lab[:, :, 0], (blur_size, blur_size), 0)
209
- comp_blur = cv2.GaussianBlur(comp_lab[:, :, 0], (blur_size, blur_size), 0)
210
-
211
- # Apply lighting ratio
212
- ratio = np.where(comp_blur > 1, orig_blur / comp_blur, 1.0)
213
- ratio = np.clip(ratio, 0.7, 1.4)
214
- result_lab[fg, 0] *= ratio[fg]
215
-
216
- result_lab = np.clip(result_lab, 0, 255).astype(np.uint8)
217
- result = cv2.cvtColor(result_lab, cv2.COLOR_LAB2RGB)
218
-
219
- # Blend at mask edges for smoother transition
220
- kernel = np.ones((5, 5), np.uint8)
221
- mask_eroded = cv2.erode(mask, kernel, iterations=3)
222
- blend_zone = (mask > 127) & (mask_eroded <= 127)
223
- if np.any(blend_zone):
224
- alpha = cv2.GaussianBlur(mask.astype(np.float32) / 255, (15, 15), 0)
225
- for ch in range(3):
226
- result[:, :, ch] = (
227
- composite[:, :, ch].astype(np.float32) * (1 - alpha)
228
- + result[:, :, ch].astype(np.float32) * alpha
229
- ).astype(np.uint8)
230
-
231
- elapsed = (time.perf_counter() - t0) * 1000
232
- print(f"[DIFFUSION] Strong harmonize fallback: {elapsed:.0f}ms", flush=True)
233
-
234
- return {
235
- "image": result,
236
- "mode": "generate-fallback",
237
- "elapsed_ms": round(elapsed, 1),
238
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Advanced tile harmonization via lighting transfer + color adaptation.
2
 
3
+ Produces photorealistic results by transferring the room's lighting pattern,
4
+ color temperature, and local contrast onto the tile composite. No diffusion
5
+ model required — works on any hardware with zero extra VRAM.
 
 
 
6
  """
7
 
8
  from __future__ import annotations
9
 
 
 
10
  import time
11
+ import traceback
12
 
13
  import cv2
14
  import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
 
17
  def generate_tile_inpaint(
 
22
  num_steps: int = 25,
23
  tile_reference: np.ndarray | None = None,
24
  ) -> dict:
25
+ """Generate photorealistic tile rendering by lighting/color transfer.
26
+
27
+ Applies the room's spatial lighting pattern, color temperature, and
28
+ local contrast to the tile region, producing a result where tiles
29
+ look naturally embedded in the room.
30
 
31
  Args:
32
+ room_image: RGB uint8 — original room (before tiles).
33
+ mask: uint8 — floor region (255 = tile area).
34
+ tile_composite: RGB uint8 — shader-composited image.
35
+ strength: Harmonization intensity (0.0-1.0).
36
+ num_steps: unused, kept for API compat.
37
+ tile_reference: unused, kept for API compat.
38
 
39
  Returns:
40
  Dict with "image" (RGB uint8), "mode", "elapsed_ms".
41
  """
42
  t0 = time.perf_counter()
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  try:
45
+ result = _harmonize_with_lighting_transfer(
46
+ composite=tile_composite,
47
+ original=room_image,
48
+ mask=mask,
49
+ strength=strength,
 
 
 
 
 
50
  )
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  elapsed = (time.perf_counter() - t0) * 1000
53
+ print(f"[DIFFUSION] Lighting transfer harmonization: {elapsed:.0f}ms", flush=True)
54
 
55
  return {
56
+ "image": result,
57
  "mode": "generate",
58
  "elapsed_ms": round(elapsed, 1),
59
  }
60
 
61
  except Exception as exc:
62
  elapsed = (time.perf_counter() - t0) * 1000
63
+ print(f"[DIFFUSION] Harmonization failed ({elapsed:.0f}ms): {exc}", flush=True)
64
+ traceback.print_exc()
65
+ from services.harmonization.harmonizer import harmonize_composite
66
+ return harmonize_composite(tile_composite, mask, room_image, strength, "fast")
67
 
 
 
 
 
 
 
 
68
 
69
+ def _harmonize_with_lighting_transfer(
 
70
  composite: np.ndarray,
71
+ original: np.ndarray,
72
  mask: np.ndarray,
 
73
  strength: float,
74
+ ) -> np.ndarray:
75
+ """Multi-stage harmonization pipeline.
76
+
77
+ Stage 1: Extract room's spatial lighting map (low-frequency luminance)
78
+ Stage 2: Transfer lighting map onto tile region
79
+ Stage 3: Match color temperature (chrominance transfer in LAB)
80
+ Stage 4: Match local contrast/texture characteristics
81
+ Stage 5: Feather edges for seamless blending
82
  """
83
+ h, w = composite.shape[:2]
 
84
  fg = mask > 127
 
 
85
 
86
+ if not np.any(fg):
87
+ return composite
 
88
 
89
+ # Ensure original matches composite size
90
+ if original.shape[:2] != (h, w):
91
+ original = cv2.resize(original, (w, h))
92
+
93
+ # --- STAGE 1: Extract room lighting map ---
94
+ # Use a large gaussian blur to get the low-frequency lighting pattern
95
+ # This captures gradients like "darker near walls, brighter in center"
96
+ orig_lab = cv2.cvtColor(original, cv2.COLOR_RGB2LAB).astype(np.float64)
97
+ comp_lab = cv2.cvtColor(composite, cv2.COLOR_RGB2LAB).astype(np.float64)
98
+
99
+ # Compute lighting map at multiple scales for robust transfer
100
+ blur_large = max(h, w) // 3 | 1 # Captures room-wide gradients
101
+ blur_medium = max(h, w) // 8 | 1 # Captures local lighting variation
102
+ orig_light_large = cv2.GaussianBlur(orig_lab[:, :, 0], (blur_large, blur_large), 0)
103
+ orig_light_medium = cv2.GaussianBlur(orig_lab[:, :, 0], (blur_medium, blur_medium), 0)
104
+ comp_light_large = cv2.GaussianBlur(comp_lab[:, :, 0], (blur_large, blur_large), 0)
105
+ comp_light_medium = cv2.GaussianBlur(comp_lab[:, :, 0], (blur_medium, blur_medium), 0)
106
+
107
+ # --- STAGE 2: Transfer spatial lighting pattern ---
108
  result_lab = comp_lab.copy()
109
 
110
+ # Ratio-based lighting transfer at large scale (room gradient)
111
+ safe_comp = np.maximum(comp_light_large, 1.0)
112
+ light_ratio_large = orig_light_large / safe_comp
113
+ light_ratio_large = np.clip(light_ratio_large, 0.5, 2.0)
114
+
115
+ # Medium-scale local adjustment
116
+ safe_comp_med = np.maximum(comp_light_medium, 1.0)
117
+ light_ratio_medium = orig_light_medium / safe_comp_med
118
+ light_ratio_medium = np.clip(light_ratio_medium, 0.6, 1.6)
119
+
120
+ # Combine multi-scale ratios (large = 60%, medium = 40%)
121
+ combined_ratio = light_ratio_large * 0.6 + light_ratio_medium * 0.4
122
+ combined_ratio = np.clip(combined_ratio, 0.55, 1.8)
123
+
124
+ # Apply to tile luminance
125
+ result_lab[fg, 0] *= combined_ratio[fg]
126
+
127
+ # --- STAGE 3: Color temperature transfer (LAB a/b channels) ---
128
+ bg = ~fg
129
+
130
+ for ch in [1, 2]: # a and b channels
131
  fg_vals = comp_lab[fg, ch]
132
  bg_vals = orig_lab[bg, ch]
133
 
134
+ if len(fg_vals) < 10 or len(bg_vals) < 10:
135
  continue
136
 
137
+ fg_mean = fg_vals.mean()
138
+ fg_std = max(fg_vals.std(), 0.5)
139
+ bg_mean = bg_vals.mean()
140
+ bg_std = max(bg_vals.std(), 0.5)
141
 
142
+ # Reinhard color transfer on chrominance
143
  transferred = (fg_vals - fg_mean) * (bg_std / fg_std) + bg_mean
144
+
145
+ # Moderate blending — enough to shift color temp, not destroy tile color
146
+ blend = min(strength * 0.6, 0.5)
147
+ result_lab[fg, ch] = fg_vals * (1.0 - blend) + transferred * blend
148
+
149
+ # --- STAGE 4: Match luminance statistics ---
150
+ fg_L = result_lab[fg, 0]
151
+ bg_L = orig_lab[bg, 0]
152
+
153
+ if len(fg_L) > 10 and len(bg_L) > 10:
154
+ fg_mean_L = fg_L.mean()
155
+ fg_std_L = max(fg_L.std(), 0.5)
156
+ bg_mean_L = bg_L.mean()
157
+ bg_std_L = max(bg_L.std(), 0.5)
158
+
159
+ # Partially transfer luminance statistics (subtle, ~30% strength)
160
+ stat_blend = min(strength * 0.35, 0.35)
161
+ target_L = (fg_L - fg_mean_L) * (bg_std_L / fg_std_L) + bg_mean_L
162
+ result_lab[fg, 0] = fg_L * (1.0 - stat_blend) + target_L * stat_blend
163
+
164
+ # Clamp LAB to valid range
165
+ result_lab[:, :, 0] = np.clip(result_lab[:, :, 0], 0, 255)
166
+ result_lab[:, :, 1] = np.clip(result_lab[:, :, 1], 0, 255)
167
+ result_lab[:, :, 2] = np.clip(result_lab[:, :, 2], 0, 255)
168
+ result = cv2.cvtColor(result_lab.astype(np.uint8), cv2.COLOR_LAB2RGB)
169
+
170
+ # --- STAGE 5: Edge feathering ---
171
+ output = _feathered_blend(composite, result, mask, feather_px=10)
172
+
173
+ # --- STAGE 6: Overall strength blending ---
174
+ if strength < 1.0:
175
+ output = cv2.addWeighted(
176
+ composite, 1.0 - strength,
177
+ output, strength,
178
+ 0,
179
+ )
180
+
181
+ return output
182
+
183
+
184
+ def _feathered_blend(
185
+ original: np.ndarray,
186
+ harmonized: np.ndarray,
187
+ mask: np.ndarray,
188
+ feather_px: int = 10,
189
+ ) -> np.ndarray:
190
+ """Blend harmonized result into original with feathered mask edges."""
191
+ alpha = mask.astype(np.float32) / 255.0
192
+
193
+ if feather_px > 0:
194
+ ksize = feather_px * 2 + 1
195
+ alpha = cv2.GaussianBlur(alpha, (ksize, ksize), 0)
196
+
197
+ if alpha.shape[:2] != original.shape[:2]:
198
+ alpha = cv2.resize(alpha, (original.shape[1], original.shape[0]))
199
+
200
+ alpha3 = alpha[:, :, np.newaxis]
201
+ blended = original.astype(np.float32) * (1.0 - alpha3) + harmonized.astype(np.float32) * alpha3
202
+ return np.clip(blended, 0, 255).astype(np.uint8)