Spaces:
Paused
Paused
Download routes/harmonization.py from modventures/room-visualizer: direct link, hf CLI and curl.
- Browser
- Download file 5.18 kB
-
https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/routes/harmonization.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer/routes/harmonization.py
-
curl -L -o harmonization.py https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/routes/harmonization.py
5.18 kB
| """Post-composite harmonization and diffusion inpainting endpoint.""" | |
| from __future__ import annotations | |
| import asyncio | |
| import base64 | |
| import io | |
| import numpy as np | |
| from fastapi import APIRouter, HTTPException | |
| from PIL import Image | |
| from errors import bad_request | |
| router = APIRouter(prefix="/harmonize", tags=["harmonization"]) | |
| def _decode_image(value: str) -> np.ndarray: | |
| """Decode base64 data URL or raw base64 to RGB numpy array.""" | |
| if not value: | |
| bad_request("Image is required.") | |
| encoded = value | |
| if value.startswith("data:"): | |
| _, encoded = value.split(",", 1) | |
| raw = base64.b64decode(encoded) | |
| img = Image.open(io.BytesIO(raw)).convert("RGB") | |
| return np.array(img) | |
| def _decode_mask(value: str) -> np.ndarray: | |
| """Decode base64 mask to single-channel uint8 numpy array.""" | |
| if not value: | |
| bad_request("Mask is required.") | |
| encoded = value | |
| if value.startswith("data:"): | |
| _, encoded = value.split(",", 1) | |
| raw = base64.b64decode(encoded) | |
| img = Image.open(io.BytesIO(raw)).convert("L") | |
| return np.array(img) | |
| def _encode_image(img: np.ndarray, quality: int = 92) -> str: | |
| """Encode RGB numpy array to JPEG data URL.""" | |
| pil = Image.fromarray(img) | |
| buf = io.BytesIO() | |
| pil.save(buf, format="JPEG", quality=quality, optimize=True) | |
| b64 = base64.b64encode(buf.getvalue()).decode() | |
| return f"data:image/jpeg;base64,{b64}" | |
| async def harmonize(payload: dict): | |
| """Harmonize a tile composite to match room lighting/color. | |
| Accepts: | |
| image: base64 data URL — composited image (room + tile) | |
| mask: base64 data URL — tile region mask (white = tile) | |
| original: base64 data URL — original room image (optional, improves quality) | |
| mode: "fast" | "neural" | "generate" (default: "fast") | |
| strength: float 0-1 (default: 0.7) | |
| Returns: | |
| image: base64 data URL — harmonized image | |
| mode: actual mode used | |
| elapsed_ms: processing time | |
| """ | |
| import traceback | |
| try: | |
| image_value = payload.get("image") | |
| mask_value = payload.get("mask") | |
| original_value = payload.get("original") | |
| mode = payload.get("mode", "fast") | |
| strength = float(payload.get("strength", 0.7)) | |
| if not image_value or not mask_value: | |
| bad_request("Both 'image' and 'mask' are required.") | |
| print(f"[HARMONIZE] Request: mode={mode}, strength={strength}, " | |
| f"image_len={len(image_value) if image_value else 0}, " | |
| f"mask_len={len(mask_value) if mask_value else 0}", flush=True) | |
| composite = await asyncio.to_thread(_decode_image, image_value) | |
| mask = await asyncio.to_thread(_decode_mask, mask_value) | |
| original = await asyncio.to_thread(_decode_image, original_value) if original_value else None | |
| print(f"[HARMONIZE] Decoded: composite={composite.shape}, mask={mask.shape}", flush=True) | |
| # Ensure mask matches composite dimensions | |
| if mask.shape[:2] != composite.shape[:2]: | |
| import cv2 | |
| mask = cv2.resize(mask, (composite.shape[1], composite.shape[0]), interpolation=cv2.INTER_NEAREST) | |
| if mode == "generate": | |
| result = await asyncio.to_thread( | |
| _run_diffusion_inpaint, composite, mask, original, strength | |
| ) | |
| else: | |
| from services.harmonization.harmonizer import harmonize_composite | |
| result = await asyncio.to_thread( | |
| harmonize_composite, composite, mask, original, strength, mode | |
| ) | |
| print(f"[HARMONIZE] Done: mode={result['mode']}, elapsed={result['elapsed_ms']}ms", flush=True) | |
| return { | |
| "image": _encode_image(result["image"]), | |
| "mode": result["mode"], | |
| "elapsed_ms": result["elapsed_ms"], | |
| } | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| print(f"[HARMONIZE] ERROR: {exc}", flush=True) | |
| traceback.print_exc() | |
| raise HTTPException(status_code=500, detail=f"Harmonization failed: {exc}") | |
| def _run_diffusion_inpaint( | |
| composite: np.ndarray, | |
| mask: np.ndarray, | |
| original: np.ndarray | None, | |
| strength: float, | |
| ) -> dict: | |
| """Run diffusion inpainting. Falls back to harmonization if unavailable.""" | |
| try: | |
| from services.harmonization.diffusion import generate_tile_inpaint | |
| return generate_tile_inpaint( | |
| room_image=original if original is not None else composite, | |
| mask=mask, | |
| tile_composite=composite, | |
| strength=strength, | |
| ) | |
| except ImportError: | |
| print("[HARMONIZE] Diffusion module not available, falling back to fast harmonization.", flush=True) | |
| from services.harmonization.harmonizer import harmonize_composite | |
| return harmonize_composite(composite, mask, original, strength, "fast") | |
| except Exception as exc: | |
| print(f"[HARMONIZE] Diffusion inpainting failed: {exc}. Falling back.", flush=True) | |
| from services.harmonization.harmonizer import harmonize_composite | |
| return harmonize_composite(composite, mask, original, strength, "fast") | |