File size: 12,358 Bytes
790d9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""Drive a full convert -> refine round trip and report what came back.

Usage (from backend/floor-visualizer, with the server running):

    python scripts/refine_smoke_test.py
    python scripts/refine_smoke_test.py path/to/room.jpg --material marble
    python scripts/refine_smoke_test.py --base https://baetes-wall-viz.loca.lt

There is no browser here, so there is no WebGL composite to upload. The script
fakes one by flat-filling each detected surface with a solid colour, which is
enough to exercise everything that can break outside the model itself: the
side-car, the GPU swap, mask alignment, pass grouping, and the outside-mask
guarantee. Judge output quality in the browser, not here.

Exit code is non-zero if the round trip fails or if refinement altered a pixel
it should not have.
"""

from __future__ import annotations

import argparse
import io
import sys
import time
import zipfile
from pathlib import Path

import numpy as np
import requests
from PIL import Image

REPO_ROOT = Path(__file__).resolve().parents[3]
DEFAULT_IMAGE = (
    REPO_ROOT / "frontend" / "viz2d-demo" / "src" / "assets" / "presets" / "bathroom.jpg"
)
# localtunnel serves a password interstitial to browsers; these headers opt out.
HEADERS = {"bypass-tunnel-reminder": "1", "ngrok-skip-browser-warning": "true"}

FILL_COLOURS = [(196, 190, 178), (150, 132, 108), (176, 178, 184), (128, 120, 112)]


def wait_for_job(base: str, job_id: str, timeout: int) -> dict:
    deadline = time.time() + timeout
    last_message = ""
    while time.time() < deadline:
        response = requests.get(
            f"{base}/viz2d/jobs/{job_id}?t={time.time()}", headers=HEADERS, timeout=60,
        )
        response.raise_for_status()
        job = response.json()
        message = f"{job.get('progress', 0):3}%  {job.get('message', '')}"
        if message != last_message:
            print(f"  {message}", flush=True)
            last_message = message
        if job.get("status") == "COMPLETED":
            return job
        if job.get("status") == "FAILED":
            raise RuntimeError(job.get("error") or job.get("message") or "job failed")
        time.sleep(2)
    raise TimeoutError(f"job {job_id} did not finish within {timeout}s")


def segments_from_bundle(bundle_bytes: bytes) -> tuple[int, int, list[dict]]:
    """Read each segment's id, class and boolean mask out of a .vizbundle.

    Masks are lazy binary refs pointing at a bitset entry inside the zip --
    one bit per pixel, least-significant-bit first -- not inline base64.
    """
    import json

    with zipfile.ZipFile(io.BytesIO(bundle_bytes)) as archive:
        manifest = json.loads(archive.read("metadata.json"))
        width, height = int(manifest["width"]), int(manifest["height"])
        pixel_count = width * height

        segments = []
        for entry in manifest.get("segments", []):
            reference = entry.get("mask")
            mask = None
            if isinstance(reference, dict) and reference.get("path"):
                bits = np.unpackbits(
                    np.frombuffer(archive.read(reference["path"]), dtype=np.uint8),
                    bitorder="little",
                )[:pixel_count]
                mask = bits.astype(bool)
            elif isinstance(reference, str) and reference:
                import base64

                indices = np.frombuffer(base64.b64decode(reference), dtype=np.uint32)
                mask = np.zeros(pixel_count, dtype=bool)
                mask[indices[indices < pixel_count]] = True
            segments.append({
                "id": int(entry["id"]),
                "className": entry.get("className", "floor"),
                "mask": mask,
            })

    return width, height, segments


def fake_composite(
    original: Image.Image,
    segments: list[dict],
    tile_path: Path | None = None,
) -> Image.Image:
    """Stand in for the browser's tile render.

    A flat fill proves the plumbing but gives diffusion nothing to preserve, so
    the output stays flat and tells you nothing about whether the model did any
    work. Pass --tile to paste a real repeating texture instead: then the
    before/after difference actually reflects material response.

    Tiling is screen-space, not perspective-correct. That is fine here -- this
    measures whether diffusion changes pixels, not whether the geometry is
    right, which the visualizer already handles.
    """
    array = np.array(original.convert("RGB"), dtype=np.uint8, copy=True)
    height, width = array.shape[:2]
    flat = array.reshape(-1, 3)

    tiled = None
    if tile_path is not None:
        texture = np.array(
            Image.open(tile_path).convert("RGB").resize((width // 3 or 1, height // 3 or 1),
                                                        Image.Resampling.LANCZOS),
            dtype=np.uint8,
        )
        repeats = (height // texture.shape[0] + 1, width // texture.shape[1] + 1, 1)
        tiled = np.tile(texture, repeats)[:height, :width].reshape(-1, 3)

    for index, segment in enumerate(segments):
        mask = segment["mask"]
        if mask is None or not mask.any():
            continue
        flat[mask] = tiled[mask] if tiled is not None else FILL_COLOURS[index % len(FILL_COLOURS)]
    return Image.fromarray(flat.reshape(array.shape), mode="RGB")


def report_difference(before: Image.Image, after: Image.Image, segments: list[dict]) -> bool:
    """Quantify what refinement changed, inside the surfaces and outside them.

    Returns False if diffusion left the surfaces untouched, which means it ran
    but did nothing -- the failure mode that looks like success.
    """
    before_np = np.asarray(before.convert("RGB"), dtype=np.int16)
    after_np = np.asarray(after.convert("RGB").resize(before.size), dtype=np.int16)
    difference = np.abs(after_np - before_np).max(axis=2)

    combined = np.zeros(before_np.shape[:2], dtype=bool)
    for segment in segments:
        if segment["mask"] is not None:
            combined |= segment["mask"].reshape(before_np.shape[:2])

    inside = difference[combined]
    outside = difference[~combined] if (~combined).any() else np.zeros(1, np.int16)

    print("\nPixel difference (refined vs the composite that was sent):")
    print(f"  inside surfaces : mean {inside.mean():6.2f}  p95 {np.percentile(inside, 95):5.1f}  "
          f"max {inside.max():3d}  changed {100 * (inside > 2).mean():5.1f}%")
    print(f"  outside surfaces: max {outside.max():3d}   (must be 0)")

    if inside.max() == 0:
        print("\n  WARNING: diffusion ran but changed nothing inside the surfaces.")
        return False
    return True


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("image", nargs="?", default=str(DEFAULT_IMAGE))
    parser.add_argument("--base", default="http://localhost:8002")
    parser.add_argument("--material", default="marble")
    parser.add_argument("--timeout", type=int, default=1800)
    parser.add_argument("--tile", help="Texture to paste into each surface, instead of a flat fill.")
    args = parser.parse_args()
    base = args.base.rstrip("/")

    image_path = Path(args.image)
    if not image_path.exists():
        print(f"Image not found: {image_path}")
        return 1

    print(f"\nBackend: {base}")
    availability = requests.get(f"{base}/viz2d/refine/materials", headers=HEADERS, timeout=60)
    if availability.status_code != 200:
        print(f"Refinement unavailable: {availability.status_code} {availability.text[:300]}")
        return 1
    print(f"Refinement ready on {availability.json().get('device')}")

    print(f"\nConverting {image_path.name} …")
    with image_path.open("rb") as handle:
        response = requests.post(
            f"{base}/viz2d/convert",
            files={"file": (image_path.name, handle, "image/jpeg")},
            headers=HEADERS, timeout=300,
        )
    response.raise_for_status()
    job_id = response.json()["id"]
    wait_for_job(base, job_id, args.timeout)

    bundle = requests.get(f"{base}/viz2d/jobs/{job_id}/file", headers=HEADERS, timeout=300)
    bundle.raise_for_status()
    width, height, segments = segments_from_bundle(bundle.content)
    print(f"\n{len(segments)} segment(s) at {width}x{height}:")
    for segment in segments:
        pixels = int(segment["mask"].sum()) if segment["mask"] is not None else 0
        print(f"  id={segment['id']}  {segment['className']:6}  {pixels} px")
    if not segments:
        print("No segments to refine.")
        return 1

    original = Image.open(image_path).convert("RGB").resize((width, height), Image.Resampling.LANCZOS)
    tile_path = Path(args.tile) if args.tile else None
    if tile_path is not None and not tile_path.exists():
        print(f"Tile not found: {tile_path}")
        return 1
    composite = fake_composite(original, segments, tile_path)
    composite.save("refine-smoke-before.png")
    print(f"  composite: {'tiled with ' + tile_path.name if tile_path else 'flat fill'}"
          f" -> refine-smoke-before.png")

    payload = {
        "surfaces": [
            {
                "segmentIds": [segment["id"]],
                "materialType": args.material,
                "surfaceKind": "wall" if segment["className"] == "wall" else "floor",
            }
            for segment in segments
        ]
    }

    buffer = io.BytesIO()
    composite.save(buffer, format="PNG")
    buffer.seek(0)

    print(f"\nRefining as '{args.material}' …")
    import json as json_module

    started = time.time()
    response = requests.post(
        f"{base}/viz2d/jobs/{job_id}/refine",
        files={"composite": ("composite.png", buffer, "image/png")},
        data={"surfaces": json_module.dumps(payload)},
        headers=HEADERS, timeout=300,
    )
    if response.status_code != 200:
        print(f"Refinement rejected: {response.status_code} {response.text[:500]}")
        return 1
    refine_id = response.json()["refineId"]

    deadline = time.time() + args.timeout
    last_message = ""
    job = {}
    while time.time() < deadline:
        status = requests.get(
            f"{base}/viz2d/jobs/{job_id}/refine/{refine_id}?t={time.time()}",
            headers=HEADERS, timeout=60,
        )
        status.raise_for_status()
        job = status.json()
        message = f"{job.get('progress', 0):3}%  {job.get('message', '')}"
        if message != last_message:
            print(f"  {message}", flush=True)
            last_message = message
        if job.get("status") == "COMPLETED":
            break
        if job.get("status") == "FAILED":
            print(f"\nFAILED: {job.get('message')}")
            return 1
        time.sleep(2)
    else:
        print("\nRefinement timed out.")
        return 1

    result = requests.get(
        f"{base}/viz2d/jobs/{job_id}/refine/{refine_id}/result", headers=HEADERS, timeout=300,
    )
    result.raise_for_status()
    output_path = Path(f"refine-smoke-{refine_id}.png")
    output_path.write_bytes(result.content)

    metadata = job.get("refinement") or {}
    print(f"\nDone in {time.time() - started:.1f}s -> {output_path}")
    print(f"  processing resolution : {metadata.get('processingResolution')}")
    print(f"  blend mode            : {metadata.get('blendMode')}")
    print(f"  passes                : {metadata.get('passCount')}")
    for entry in metadata.get("passes", []):
        if entry.get("skipped"):
            print(f"    - {entry['materialType']}/{entry['surfaceKind']}: SKIPPED ({entry.get('reason')})")
        else:
            print(
                f"    - {entry['materialType']}/{entry['surfaceKind']}: "
                f"{entry.get('pixels')} px, coverage {entry.get('diffusionCoverage')}, "
                f"{entry.get('elapsedMs')} ms"
            )

    changed = report_difference(composite, Image.open(output_path), segments)

    difference = metadata.get("maxOutsideMaskDifference")
    print(f"  outside-mask delta    : {difference}")
    if difference != 0:
        print("\nFAILED: pixels outside the surface masks were altered.")
        return 1

    if not changed:
        print("\nFAILED: refinement produced no change inside the surfaces.")
        return 1

    print("\nRound trip OK — diffusion ran and changed the surfaces.")
    return 0


if __name__ == "__main__":
    sys.exit(main())