File size: 5,180 Bytes
485bb51
 
 
 
 
 
 
 
 
26ba662
485bb51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ba662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485bb51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
"""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}"


@router.post("/")
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")