"""Image harmonization for tile composite blending. Provides two modes: - "fast": Color-statistics transfer (~20ms, no model, always available) - "neural": Neural harmonization model (~200-500ms, requires model download) """ from __future__ import annotations import time import cv2 import numpy as np from services.harmonization.color_transfer import ( harmonize_color_transfer, harmonize_with_local_lighting, ) def harmonize_composite( composite: np.ndarray, mask: np.ndarray, original: np.ndarray | None = None, strength: float = 0.7, mode: str = "fast", ) -> dict: """Harmonize a tile composite to match room lighting/color. Args: composite: RGB uint8 — room image with tile applied by frontend shader. mask: uint8 — where tile was applied (255 = tile, 0 = background). original: RGB uint8 — original room image before tile (optional, improves quality). strength: 0.0-1.0 harmonization strength. mode: "fast" (color transfer) or "neural" (model-based). Returns: Dict with "image" (RGB uint8), "mode", "elapsed_ms". """ t0 = time.perf_counter() if mode == "neural": result = _neural_harmonize(composite, mask, strength) if result is not None: elapsed = (time.perf_counter() - t0) * 1000 print(f"[HARMONIZE] neural mode: {elapsed:.0f}ms", flush=True) return {"image": result, "mode": "neural", "elapsed_ms": round(elapsed, 1)} # Fall through to fast mode if neural unavailable print("[HARMONIZE] Neural model unavailable, falling back to fast mode.", flush=True) if original is not None: result = harmonize_with_local_lighting(composite, original, mask, strength) else: result = harmonize_color_transfer(composite, mask, strength) elapsed = (time.perf_counter() - t0) * 1000 print(f"[HARMONIZE] fast mode: {elapsed:.0f}ms", flush=True) return {"image": result, "mode": "fast", "elapsed_ms": round(elapsed, 1)} # --------------------------------------------------------------------------- # Neural harmonization (optional — loaded on first use) # --------------------------------------------------------------------------- _neural_model = None _neural_load_attempted = False def _neural_harmonize( composite: np.ndarray, mask: np.ndarray, strength: float, ) -> np.ndarray | None: """Try neural harmonization. Returns None if model unavailable.""" global _neural_model, _neural_load_attempted if _neural_load_attempted and _neural_model is None: return None if _neural_model is None: _neural_load_attempted = True _neural_model = _try_load_neural_model() if _neural_model is None: return None return _run_neural_model(_neural_model, composite, mask, strength) def _try_load_neural_model(): """Attempt to load a neural harmonization model.""" try: import torch import state # Try loading CDTNet or similar from HuggingFace # For now, check if a local model checkpoint exists from pathlib import Path model_path = Path("data/models/harmonizer") if not model_path.exists(): print("[HARMONIZE] No neural harmonization model found at data/models/harmonizer", flush=True) return None print(f"[HARMONIZE] Loading neural harmonization model from {model_path}", flush=True) # Placeholder for actual model loading # model = HarmonizerNet.from_pretrained(model_path).to(state.device).eval() # return model return None except Exception as exc: print(f"[HARMONIZE] Failed to load neural model: {exc}", flush=True) return None def _run_neural_model(model, composite: np.ndarray, mask: np.ndarray, strength: float) -> np.ndarray | None: """Run neural harmonization model inference.""" try: import torch import state h, w = composite.shape[:2] # Downscale for speed max_dim = 512 scale = min(max_dim / max(h, w), 1.0) if scale < 1.0: new_w, new_h = int(w * scale), int(h * scale) img_s = cv2.resize(composite, (new_w, new_h)) mask_s = cv2.resize(mask, (new_w, new_h), interpolation=cv2.INTER_NEAREST) else: img_s, mask_s = composite, mask # Convert to tensor img_t = torch.from_numpy(img_s).float().permute(2, 0, 1).unsqueeze(0) / 255.0 mask_t = torch.from_numpy(mask_s).float().unsqueeze(0).unsqueeze(0) / 255.0 img_t = img_t.to(state.device) mask_t = mask_t.to(state.device) with torch.inference_mode(): output_t = model(img_t, mask_t) output = (output_t.squeeze(0).permute(1, 2, 0) * 255).clamp(0, 255).cpu().numpy().astype(np.uint8) # Upscale back if scale < 1.0: output = cv2.resize(output, (w, h)) # Blend with original based on strength if strength < 1.0: fg = mask > 127 blended = composite.copy() blended[fg] = (composite[fg].astype(np.float32) * (1 - strength) + output[fg].astype(np.float32) * strength).astype(np.uint8) return blended return output except Exception as exc: print(f"[HARMONIZE] Neural inference failed: {exc}", flush=True) return None