Spaces:
Paused
Paused
Download scripts/refine_smoke_test.py from modventures/room-visualizer: direct link, hf CLI and curl.
- Browser
- Download file 9.28 kB
-
https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/scripts/refine_smoke_test.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer/scripts/refine_smoke_test.py
-
curl -L -o refine_smoke_test.py https://huggingface.co/spaces/modventures/room-visualizer/resolve/main/scripts/refine_smoke_test.py
9.28 kB
| """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]) -> Image.Image: | |
| """Flat-fill each surface, standing in for a browser tile render.""" | |
| array = np.array(original.convert("RGB"), dtype=np.uint8, copy=True) | |
| flat = array.reshape(-1, 3) | |
| for index, segment in enumerate(segments): | |
| mask = segment["mask"] | |
| if mask is None or not mask.any(): | |
| continue | |
| flat[mask] = FILL_COLOURS[index % len(FILL_COLOURS)] | |
| return Image.fromarray(flat.reshape(array.shape), mode="RGB") | |
| 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) | |
| 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) | |
| composite = fake_composite(original, segments) | |
| 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" | |
| ) | |
| difference = metadata.get("maxOutsideMaskDifference") | |
| print(f" outside-mask delta : {difference}") | |
| if difference != 0: | |
| print("\nFAILED: pixels outside the surface masks were altered.") | |
| return 1 | |
| print("\nRound trip OK.") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |