Spaces:
Paused
Paused
GitHub Actions commited on
Commit ·
6a75a66
1
Parent(s): 6399d71
Deploy from GitHub commit 12f3f8bcabf5ca76d0009b00142eea4562e462b6
Browse files- Dockerfile +13 -0
- app.py +206 -14
- golden_render.py +114 -9
- verify_live_smoke.py +151 -0
- verify_n4_sim.py +88 -0
- verify_r1_rotation_sim.py +130 -0
- verify_r2_layout_sim.py +149 -0
- verify_r3_rug_sim.py +108 -0
- verify_r4_eval.py +147 -0
- verify_r4_intrinsic_sim.py +177 -0
Dockerfile
CHANGED
|
@@ -35,6 +35,19 @@ COPY requirements-base.txt requirements-gpu-cu126.txt ./
|
|
| 35 |
RUN pip install --no-cache-dir --upgrade pip && \
|
| 36 |
pip install --no-cache-dir -r requirements-gpu-cu126.txt
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
# Copy the rest of the application files
|
| 39 |
COPY --chown=user:1000 . .
|
| 40 |
|
|
|
|
| 35 |
RUN pip install --no-cache-dir --upgrade pip && \
|
| 36 |
pip install --no-cache-dir -r requirements-gpu-cu126.txt
|
| 37 |
|
| 38 |
+
# R4-1 — bake the intrinsic-decomposition weights (~1.4 GB) into the image:
|
| 39 |
+
# Space disk is ephemeral, so without this every wake re-downloads them
|
| 40 |
+
# before the first conversion. The trusted_list write mirrors
|
| 41 |
+
# app._ensure_torch_hub_trust (altered_midas prompts interactively without
|
| 42 |
+
# it and crashes headless builds). chown in the SAME layer so the cache
|
| 43 |
+
# isn't duplicated into a second layer.
|
| 44 |
+
RUN python3 -c "import os, torch.hub as hub; \
|
| 45 |
+
os.makedirs(hub.get_dir(), exist_ok=True); \
|
| 46 |
+
open(os.path.join(hub.get_dir(), 'trusted_list'), 'a').write('rwightman_gen-efficientnet-pytorch\n'); \
|
| 47 |
+
__import__('intrinsic.pipeline', fromlist=['load_models']).load_models('v2', device='cpu'); \
|
| 48 |
+
print('intrinsic weights baked')" && \
|
| 49 |
+
chown -R user:1000 /home/user/.cache
|
| 50 |
+
|
| 51 |
# Copy the rest of the application files
|
| 52 |
COPY --chown=user:1000 . .
|
| 53 |
|
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import aiofiles
|
| 2 |
import asyncio
|
| 3 |
import base64
|
|
|
|
| 4 |
import io
|
| 5 |
import json
|
| 6 |
import os
|
|
@@ -135,11 +136,16 @@ INTRINSIC_MODEL_VERSION = str(config_value(
|
|
| 135 |
"intrinsic_model_version",
|
| 136 |
"v2",
|
| 137 |
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
ENABLE_INTRINSIC_SHADING = str(config_value(
|
| 139 |
"ENABLE_INTRINSIC_SHADING",
|
| 140 |
"runtime",
|
| 141 |
"enable_intrinsic_shading",
|
| 142 |
-
"
|
| 143 |
)).lower() in {"1", "true", "yes", "on"}
|
| 144 |
VISUALIZER_DATA_DIR = str(config_value(
|
| 145 |
"VISUALIZER_DATA_DIR",
|
|
@@ -214,11 +220,28 @@ def _load_segmentation_model():
|
|
| 214 |
print("SegFormer loaded.", flush=True)
|
| 215 |
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
def _load_intrinsic_model():
|
| 218 |
global intrinsic_models
|
| 219 |
if ENABLE_INTRINSIC_SHADING and intrinsic_models is None:
|
| 220 |
try:
|
| 221 |
print(f"Loading Intrinsic Image Decomposition model: {INTRINSIC_MODEL_VERSION} ...", flush=True)
|
|
|
|
| 222 |
from intrinsic.pipeline import load_models
|
| 223 |
intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(device))
|
| 224 |
print("Intrinsic model loaded.", flush=True)
|
|
@@ -256,9 +279,14 @@ REJECT_SURFACE_CLASSES = {
|
|
| 256 |
"countertop", "kitchen island", "stove", "refrigerator", "oven", "microwave",
|
| 257 |
"dishwasher", "sink",
|
| 258 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
OCCLUDER_CLASSES = {
|
| 260 |
"bed", "cabinet", "person", "door", "table", "plant", "curtain", "chair",
|
| 261 |
-
"car", "painting", "sofa", "shelf", "mirror", "
|
| 262 |
"wardrobe", "lamp", "bathtub", "railing", "cushion", "base", "box",
|
| 263 |
"column", "chest of drawers", "counter", "fireplace",
|
| 264 |
"bookcase", "blind", "coffee table", "toilet", "bench",
|
|
@@ -444,7 +472,7 @@ def _suppress_periodic_shading(field: np.ndarray) -> np.ndarray:
|
|
| 444 |
# ---------------------------------------------------------------------------
|
| 445 |
|
| 446 |
def build_shade_map(
|
| 447 |
-
img_np: np.ndarray, surface_mask: np.ndarray
|
| 448 |
) -> tuple[np.ndarray | None, tuple[float, float]]:
|
| 449 |
default_range = (0.55, 1.35)
|
| 450 |
if not surface_mask.any():
|
|
@@ -495,6 +523,18 @@ def build_shade_map(
|
|
| 495 |
# extraction noise read as stains on light replacement floors; a mild
|
| 496 |
# gamma keeps shadow placement while taking the "dirt" edge off.
|
| 497 |
relative = np.where(relative < 1.0, np.power(relative, 0.85), relative)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 498 |
lo, hi = _adaptive_shade_range(relative, mask)
|
| 499 |
return _encode_shade(relative, lo, hi), (lo, hi)
|
| 500 |
|
|
@@ -512,6 +552,10 @@ def build_intrinsic_shade_map(
|
|
| 512 |
from intrinsic.pipeline import run_pipeline
|
| 513 |
results = run_pipeline(intrinsic_models, img_float, device=str(device))
|
| 514 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
shading = None
|
| 516 |
if "gry_shd" in results:
|
| 517 |
shading = results["gry_shd"]
|
|
@@ -521,9 +565,11 @@ def build_intrinsic_shade_map(
|
|
| 521 |
else:
|
| 522 |
for k in results.keys():
|
| 523 |
if "shd" in k or "shading" in k:
|
| 524 |
-
shading = results[k]
|
| 525 |
-
if
|
| 526 |
shading = shading[:, :, 0] * 0.299 + shading[:, :, 1] * 0.587 + shading[:, :, 2] * 0.114
|
|
|
|
|
|
|
| 527 |
break
|
| 528 |
|
| 529 |
if shading is None:
|
|
@@ -532,19 +578,30 @@ def build_intrinsic_shade_map(
|
|
| 532 |
h, w = surface_mask.shape[:2]
|
| 533 |
if shading.shape[:2] != (h, w):
|
| 534 |
shading = cv2.resize(shading, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 535 |
-
|
| 536 |
-
sigma = max(3.0, min(h, w) / 80.0)
|
| 537 |
-
shading = cv2.GaussianBlur(shading.astype(np.float32), (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 538 |
|
| 539 |
floor_vals = shading[surface_mask > 0]
|
| 540 |
if floor_vals.size == 0:
|
| 541 |
return None, default_range
|
| 542 |
-
|
| 543 |
median_val = float(np.median(floor_vals))
|
| 544 |
if median_val < 1e-3:
|
| 545 |
return None, default_range
|
| 546 |
|
| 547 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
relative_shading[surface_mask == 0] = 1.0
|
| 549 |
lo, hi = _adaptive_shade_range(relative_shading, surface_mask)
|
| 550 |
return _encode_shade(relative_shading, lo, hi), (lo, hi)
|
|
@@ -1318,6 +1375,89 @@ def estimate_default_rotation(
|
|
| 1318 |
return 0.0
|
| 1319 |
|
| 1320 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1321 |
# ---------------------------------------------------------------------------
|
| 1322 |
# B5 — Complement-Stamp Furniture
|
| 1323 |
# Use a single dilation pass (down from two) and restore the narrow contact
|
|
@@ -1607,11 +1747,14 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 1607 |
t0 = time.perf_counter()
|
| 1608 |
primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES)
|
| 1609 |
floor_class_ids = class_ids(FLOOR_SURFACE_CLASSES)
|
| 1610 |
-
|
|
|
|
|
|
|
|
|
|
| 1611 |
floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
|
| 1612 |
floor_mask = clean_floor_mask(floor_mask)
|
| 1613 |
if int(floor_mask.sum()) < min_floor_area:
|
| 1614 |
-
floor_mask = np.isin(seg_map, floor_class_ids).astype(np.uint8)
|
| 1615 |
floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
|
| 1616 |
floor_mask = clean_floor_mask(floor_mask)
|
| 1617 |
# P1-3 — reclaim small enclosed islands (accent tiles, pattern features)
|
|
@@ -1633,6 +1776,15 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 1633 |
# R1-3 — physical plane scale; null on relative depth so the frontend
|
| 1634 |
# falls back to the heuristic repeat.
|
| 1635 |
plane["metersPerUnit"] = estimate_meters_per_unit(depth, floor_mask, homography, w, h)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1636 |
print(f"[TIMING] Plane fitting / homography calculation took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 1637 |
|
| 1638 |
t0 = time.perf_counter()
|
|
@@ -1650,13 +1802,18 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 1650 |
|
| 1651 |
t0 = time.perf_counter()
|
| 1652 |
shade_map, shade_range = None, (0.55, 1.35)
|
|
|
|
| 1653 |
if ENABLE_INTRINSIC_SHADING:
|
| 1654 |
if intrinsic_models is None:
|
| 1655 |
_load_intrinsic_model()
|
| 1656 |
if intrinsic_models is not None:
|
| 1657 |
shade_map, shade_range = build_intrinsic_shade_map(img_np, surface_mask)
|
|
|
|
|
|
|
| 1658 |
if shade_map is None:
|
| 1659 |
-
shade_map, shade_range = build_shade_map(img_np, surface_mask)
|
|
|
|
|
|
|
| 1660 |
print(f"[TIMING] Shade map construction took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 1661 |
|
| 1662 |
t0 = time.perf_counter()
|
|
@@ -1684,6 +1841,14 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 1684 |
# Per-region confidence sub-map
|
| 1685 |
region_conf = build_confidence_map(region_mask, occluder_zone)
|
| 1686 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1687 |
segments.append({
|
| 1688 |
"id": region_idx,
|
| 1689 |
"className": "floor",
|
|
@@ -1695,6 +1860,7 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 1695 |
"colorTemperature": color_temperature, # B2
|
| 1696 |
"lightVector": light_vector, # B3
|
| 1697 |
"confidenceMap": base64.b64encode(region_conf.tobytes()).decode() if region_conf is not None else None, # B10
|
|
|
|
| 1698 |
"multiRoom": multi_room, # B7
|
| 1699 |
"gridGroup": "primary" if region_idx == 0 else f"room_{region_idx}", # B7
|
| 1700 |
"metadata": {
|
|
@@ -1703,6 +1869,10 @@ def build_segmentation_bundle(contents: bytes):
|
|
| 1703 |
"surfacePixels": int(region_mask.sum()),
|
| 1704 |
"depthEnabled": depth is not None,
|
| 1705 |
"shadingEnabled": shade_map is not None,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1706 |
},
|
| 1707 |
# R1-1 — metric floor depth stats (metres). The seam for R1-2
|
| 1708 |
# (plane fit) and R1-3 (true tile scale); null on relative
|
|
@@ -1785,18 +1955,40 @@ def run_conversion_task(job_id: str, upload_path: Path):
|
|
| 1785 |
pass
|
| 1786 |
|
| 1787 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1788 |
@app.post("/viz2d/convert")
|
| 1789 |
async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
|
| 1790 |
if file.content_type and not file.content_type.startswith("image/"):
|
| 1791 |
raise HTTPException(status_code=400, detail="Upload must be a JPG or PNG image.")
|
| 1792 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1793 |
job_id = uuid.uuid4().hex
|
| 1794 |
ext = Path(file.filename or "room.jpg").suffix.lower()
|
| 1795 |
if ext not in {".jpg", ".jpeg", ".png", ".webp"}:
|
| 1796 |
ext = ".jpg"
|
| 1797 |
upload_path = UPLOAD_DIR / f"{job_id}{ext}"
|
| 1798 |
with upload_path.open("wb") as out:
|
| 1799 |
-
|
|
|
|
| 1800 |
|
| 1801 |
job = {
|
| 1802 |
"id": job_id,
|
|
|
|
| 1 |
import aiofiles
|
| 2 |
import asyncio
|
| 3 |
import base64
|
| 4 |
+
import hashlib
|
| 5 |
import io
|
| 6 |
import json
|
| 7 |
import os
|
|
|
|
| 136 |
"intrinsic_model_version",
|
| 137 |
"v2",
|
| 138 |
))
|
| 139 |
+
# R4-1 — default ON: evaluated 2026-06-12 on the reference rooms; the
|
| 140 |
+
# intrinsic illumination map is pattern/stain-free where the luminance
|
| 141 |
+
# heuristic transferred the old floor's albedo (ghost lattices, stain blobs)
|
| 142 |
+
# and over-brightened window zones (desk room p95 2.27x -> 1.27x). The
|
| 143 |
+
# luminance path remains the automatic fallback on any load/run failure.
|
| 144 |
ENABLE_INTRINSIC_SHADING = str(config_value(
|
| 145 |
"ENABLE_INTRINSIC_SHADING",
|
| 146 |
"runtime",
|
| 147 |
"enable_intrinsic_shading",
|
| 148 |
+
"1",
|
| 149 |
)).lower() in {"1", "true", "yes", "on"}
|
| 150 |
VISUALIZER_DATA_DIR = str(config_value(
|
| 151 |
"VISUALIZER_DATA_DIR",
|
|
|
|
| 220 |
print("SegFormer loaded.", flush=True)
|
| 221 |
|
| 222 |
|
| 223 |
+
def _ensure_torch_hub_trust():
|
| 224 |
+
"""altered_midas (Intrinsic's backbone loader) calls torch.hub.load
|
| 225 |
+
without trust_repo, which PROMPTS interactively on first use and crashes
|
| 226 |
+
headless servers with EOFError. Pre-trust the pinned repo."""
|
| 227 |
+
import torch.hub as _hub
|
| 228 |
+
|
| 229 |
+
hub_dir = _hub.get_dir()
|
| 230 |
+
os.makedirs(hub_dir, exist_ok=True)
|
| 231 |
+
path = os.path.join(hub_dir, "trusted_list")
|
| 232 |
+
entry = "rwightman_gen-efficientnet-pytorch"
|
| 233 |
+
existing = open(path).read().splitlines() if os.path.exists(path) else []
|
| 234 |
+
if entry not in existing:
|
| 235 |
+
with open(path, "a") as f:
|
| 236 |
+
f.write(entry + "\n")
|
| 237 |
+
|
| 238 |
+
|
| 239 |
def _load_intrinsic_model():
|
| 240 |
global intrinsic_models
|
| 241 |
if ENABLE_INTRINSIC_SHADING and intrinsic_models is None:
|
| 242 |
try:
|
| 243 |
print(f"Loading Intrinsic Image Decomposition model: {INTRINSIC_MODEL_VERSION} ...", flush=True)
|
| 244 |
+
_ensure_torch_hub_trust()
|
| 245 |
from intrinsic.pipeline import load_models
|
| 246 |
intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(device))
|
| 247 |
print("Intrinsic model loaded.", flush=True)
|
|
|
|
| 279 |
"countertop", "kitchen island", "stove", "refrigerator", "oven", "microwave",
|
| 280 |
"dishwasher", "sink",
|
| 281 |
}
|
| 282 |
+
# R3-3 — rugs are REPLACEABLE floor, not occluders: the reference competitor
|
| 283 |
+
# renders the new floor beneath area rugs. Kept as a separate set (not merged
|
| 284 |
+
# into FLOOR_SURFACE_CLASSES) so the bundle can carry the rug region and the
|
| 285 |
+
# frontend can offer a per-photo keep/replace toggle.
|
| 286 |
+
RUG_CLASSES = {"rug"}
|
| 287 |
OCCLUDER_CLASSES = {
|
| 288 |
"bed", "cabinet", "person", "door", "table", "plant", "curtain", "chair",
|
| 289 |
+
"car", "painting", "sofa", "shelf", "mirror", "armchair", "seat", "desk",
|
| 290 |
"wardrobe", "lamp", "bathtub", "railing", "cushion", "base", "box",
|
| 291 |
"column", "chest of drawers", "counter", "fireplace",
|
| 292 |
"bookcase", "blind", "coffee table", "toilet", "bench",
|
|
|
|
| 472 |
# ---------------------------------------------------------------------------
|
| 473 |
|
| 474 |
def build_shade_map(
|
| 475 |
+
img_np: np.ndarray, surface_mask: np.ndarray, rug_mask: np.ndarray | None = None
|
| 476 |
) -> tuple[np.ndarray | None, tuple[float, float]]:
|
| 477 |
default_range = (0.55, 1.35)
|
| 478 |
if not surface_mask.any():
|
|
|
|
| 523 |
# extraction noise read as stains on light replacement floors; a mild
|
| 524 |
# gamma keeps shadow placement while taking the "dirt" edge off.
|
| 525 |
relative = np.where(relative < 1.0, np.power(relative, 0.85), relative)
|
| 526 |
+
# R3-3 — over a replaced rug the heuristic "shading" is the rug's own
|
| 527 |
+
# albedo (a persian rug reads as a giant stain on the new floor), and the
|
| 528 |
+
# true lighting under it is unknowable from the photo. Flatten the rug
|
| 529 |
+
# region to neutral with a feathered blend so real shadows still carry
|
| 530 |
+
# across the rug edge. The intrinsic path keeps its values instead: the
|
| 531 |
+
# rug surface receives the same illumination the floor beneath would.
|
| 532 |
+
if rug_mask is not None and rug_mask.any():
|
| 533 |
+
feather = cv2.GaussianBlur(
|
| 534 |
+
rug_mask.astype(np.float32), (0, 0), sigmaX=max(4.0, min(h, w) / 60.0)
|
| 535 |
+
)
|
| 536 |
+
feather = np.clip(feather, 0.0, 1.0)
|
| 537 |
+
relative = relative * (1.0 - feather) + feather
|
| 538 |
lo, hi = _adaptive_shade_range(relative, mask)
|
| 539 |
return _encode_shade(relative, lo, hi), (lo, hi)
|
| 540 |
|
|
|
|
| 552 |
from intrinsic.pipeline import run_pipeline
|
| 553 |
results = run_pipeline(intrinsic_models, img_float, device=str(device))
|
| 554 |
|
| 555 |
+
# R4-1 — key variants across pipeline versions: 'gry_shd' (grayscale),
|
| 556 |
+
# 'dif_shd' (RGB diffuse), 'inv_shd'/'inv_shading' (INVERSE encoding
|
| 557 |
+
# 1/(shd+1) — must be decoded, a raw substring match would flip
|
| 558 |
+
# shadows into highlights).
|
| 559 |
shading = None
|
| 560 |
if "gry_shd" in results:
|
| 561 |
shading = results["gry_shd"]
|
|
|
|
| 565 |
else:
|
| 566 |
for k in results.keys():
|
| 567 |
if "shd" in k or "shading" in k:
|
| 568 |
+
shading = np.asarray(results[k], dtype=np.float32)
|
| 569 |
+
if shading.ndim == 3:
|
| 570 |
shading = shading[:, :, 0] * 0.299 + shading[:, :, 1] * 0.587 + shading[:, :, 2] * 0.114
|
| 571 |
+
if "inv" in k:
|
| 572 |
+
shading = 1.0 / np.clip(shading, 1e-4, None) - 1.0
|
| 573 |
break
|
| 574 |
|
| 575 |
if shading is None:
|
|
|
|
| 578 |
h, w = surface_mask.shape[:2]
|
| 579 |
if shading.shape[:2] != (h, w):
|
| 580 |
shading = cv2.resize(shading, (w, h), interpolation=cv2.INTER_LINEAR)
|
| 581 |
+
shading = shading.astype(np.float32)
|
|
|
|
|
|
|
| 582 |
|
| 583 |
floor_vals = shading[surface_mask > 0]
|
| 584 |
if floor_vals.size == 0:
|
| 585 |
return None, default_range
|
|
|
|
| 586 |
median_val = float(np.median(floor_vals))
|
| 587 |
if median_val < 1e-3:
|
| 588 |
return None, default_range
|
| 589 |
|
| 590 |
+
# R4-1 — fill non-floor with the floor median BEFORE smoothing, same
|
| 591 |
+
# as the heuristic path: otherwise the blur mixes furniture/wall
|
| 592 |
+
# shading across the mask boundary and paints a halo ring onto the
|
| 593 |
+
# floor edge (the desk/curtain light-leak from the Sprint-1 round).
|
| 594 |
+
filled = shading.copy()
|
| 595 |
+
filled[surface_mask == 0] = median_val
|
| 596 |
+
sigma = max(3.0, min(h, w) / 80.0)
|
| 597 |
+
filled = cv2.GaussianBlur(filled, (0, 0), sigmaX=sigma, sigmaY=sigma)
|
| 598 |
+
|
| 599 |
+
relative_shading = filled / median_val
|
| 600 |
+
# R4-1 — the model decomposes in LINEAR light (srgb^2.2 = albedo x
|
| 601 |
+
# shading); the frontend multiplies sRGB-encoded texels, so the
|
| 602 |
+
# linear ratio must be brought to display space or shadows render
|
| 603 |
+
# ~gamma deeper than the photo's.
|
| 604 |
+
relative_shading = np.power(np.clip(relative_shading, 0.0, None), 1.0 / 2.2)
|
| 605 |
relative_shading[surface_mask == 0] = 1.0
|
| 606 |
lo, hi = _adaptive_shade_range(relative_shading, surface_mask)
|
| 607 |
return _encode_shade(relative_shading, lo, hi), (lo, hi)
|
|
|
|
| 1375 |
return 0.0
|
| 1376 |
|
| 1377 |
|
| 1378 |
+
# ---------------------------------------------------------------------------
|
| 1379 |
+
# R1-4 — wall-aligned rotation v2
|
| 1380 |
+
# v1 reads the floor mask's top silhouette, which is furniture/curtains as
|
| 1381 |
+
# often as it is wall, so it fires rarely. v2 reads the actual wall-floor
|
| 1382 |
+
# contact band and measures the wall direction IN PLANE SPACE, where an
|
| 1383 |
+
# installer's reference wall is a straight line regardless of perspective.
|
| 1384 |
+
# Perpendicular walls reinforce each other through the 90-deg fold.
|
| 1385 |
+
# ---------------------------------------------------------------------------
|
| 1386 |
+
|
| 1387 |
+
WALL_CONTACT_CLASSES = {"wall", "door", "window"}
|
| 1388 |
+
|
| 1389 |
+
|
| 1390 |
+
def estimate_wall_rotation(
|
| 1391 |
+
wall_mask: np.ndarray, floor_mask: np.ndarray, H: np.ndarray
|
| 1392 |
+
) -> float | None:
|
| 1393 |
+
"""Dominant wall direction in floor-plane space, folded to the tile
|
| 1394 |
+
grid's 90-deg symmetry, in the same chart `defaultRotation` is consumed
|
| 1395 |
+
in. Returns None unless one direction clearly wins — a wrong rotation
|
| 1396 |
+
lays every tile visibly wrong, so the gates err on abstaining (the
|
| 1397 |
+
caller keeps the v1 estimate).
|
| 1398 |
+
"""
|
| 1399 |
+
h, w = wall_mask.shape[:2]
|
| 1400 |
+
kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
|
| 1401 |
+
band = cv2.bitwise_and(cv2.dilate(wall_mask, kern), cv2.dilate(floor_mask, kern))
|
| 1402 |
+
if int(band.sum()) < w:
|
| 1403 |
+
return None
|
| 1404 |
+
|
| 1405 |
+
segs = cv2.HoughLinesP(
|
| 1406 |
+
(band * 255).astype(np.uint8),
|
| 1407 |
+
rho=1.0,
|
| 1408 |
+
theta=np.pi / 360.0,
|
| 1409 |
+
threshold=40,
|
| 1410 |
+
minLineLength=max(24, int(min(h, w) * 0.08)),
|
| 1411 |
+
maxLineGap=10,
|
| 1412 |
+
)
|
| 1413 |
+
if segs is None or len(segs) < 5:
|
| 1414 |
+
return None
|
| 1415 |
+
|
| 1416 |
+
angles, weights = [], []
|
| 1417 |
+
for x1, y1, x2, y2 in segs[:, 0]:
|
| 1418 |
+
p = np.array([[x1, y1, 1.0], [x2, y2, 1.0]], dtype=np.float64) @ H.T
|
| 1419 |
+
if np.any(np.abs(p[:, 2]) < 1e-9):
|
| 1420 |
+
continue
|
| 1421 |
+
u = p[:, 0] / p[:, 2]
|
| 1422 |
+
v = p[:, 1] / p[:, 2]
|
| 1423 |
+
du, dv = float(u[1] - u[0]), float(v[1] - v[0])
|
| 1424 |
+
length = float(np.hypot(du, dv))
|
| 1425 |
+
if length < 1e-9:
|
| 1426 |
+
continue
|
| 1427 |
+
angles.append(np.degrees(np.arctan2(dv, du)) % 90.0)
|
| 1428 |
+
weights.append(length)
|
| 1429 |
+
if len(angles) < 5:
|
| 1430 |
+
return None
|
| 1431 |
+
|
| 1432 |
+
# Deduplicate before voting: a thick contact band yields MANY parallel
|
| 1433 |
+
# Hough segments for ONE wall, which would multiply that wall's weight
|
| 1434 |
+
# and let a long noisy diagonal outvote the true wall instead of
|
| 1435 |
+
# conflicting with it. One direction = one vote: keep the longest
|
| 1436 |
+
# segment per 3-deg direction bin.
|
| 1437 |
+
bins: dict[int, float] = {}
|
| 1438 |
+
for ang, wt in zip(angles, weights):
|
| 1439 |
+
b = int(ang // 3.0)
|
| 1440 |
+
bins[b] = max(bins.get(b, 0.0), wt)
|
| 1441 |
+
bin_angles = np.array([(b * 3.0 + 1.5) for b in bins])
|
| 1442 |
+
wts = np.array(list(bins.values()))
|
| 1443 |
+
|
| 1444 |
+
# Circular consensus over the 90-deg period: the resultant length is ~1
|
| 1445 |
+
# when directions agree (incl. perpendicular walls, which fold together)
|
| 1446 |
+
# and collapses when they conflict — a corridor of doorways, curved bay
|
| 1447 |
+
# walls, segmentation noise.
|
| 1448 |
+
theta = bin_angles / 90.0 * 2.0 * np.pi
|
| 1449 |
+
cw = float(np.sum(wts * np.cos(theta)))
|
| 1450 |
+
sw = float(np.sum(wts * np.sin(theta)))
|
| 1451 |
+
total = float(np.sum(wts))
|
| 1452 |
+
if total < 1e-9 or np.hypot(cw, sw) / total < 0.6:
|
| 1453 |
+
return None
|
| 1454 |
+
|
| 1455 |
+
ang = (np.degrees(np.arctan2(sw, cw)) % 360.0) / 360.0 * 90.0
|
| 1456 |
+
if ang >= 45.0:
|
| 1457 |
+
ang -= 90.0
|
| 1458 |
+
return float(ang)
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
# ---------------------------------------------------------------------------
|
| 1462 |
# B5 — Complement-Stamp Furniture
|
| 1463 |
# Use a single dilation pass (down from two) and restore the narrow contact
|
|
|
|
| 1747 |
t0 = time.perf_counter()
|
| 1748 |
primary_floor_ids = class_ids(PRIMARY_FLOOR_CLASSES)
|
| 1749 |
floor_class_ids = class_ids(FLOOR_SURFACE_CLASSES)
|
| 1750 |
+
# R3-3 — rug pixels are replaceable floor (coplanar by construction);
|
| 1751 |
+
# unioned before wall-subtract/cleanup so they ride the whole pipeline.
|
| 1752 |
+
rug_mask = np.isin(seg_map, class_ids(RUG_CLASSES)).astype(np.uint8)
|
| 1753 |
+
floor_mask = np.maximum(np.isin(seg_map, primary_floor_ids).astype(np.uint8), rug_mask)
|
| 1754 |
floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
|
| 1755 |
floor_mask = clean_floor_mask(floor_mask)
|
| 1756 |
if int(floor_mask.sum()) < min_floor_area:
|
| 1757 |
+
floor_mask = np.maximum(np.isin(seg_map, floor_class_ids).astype(np.uint8), rug_mask)
|
| 1758 |
floor_mask = wall_subtract(floor_mask, seg_map, dilation=1)
|
| 1759 |
floor_mask = clean_floor_mask(floor_mask)
|
| 1760 |
# P1-3 — reclaim small enclosed islands (accent tiles, pattern features)
|
|
|
|
| 1776 |
# R1-3 — physical plane scale; null on relative depth so the frontend
|
| 1777 |
# falls back to the heuristic repeat.
|
| 1778 |
plane["metersPerUnit"] = estimate_meters_per_unit(depth, floor_mask, homography, w, h)
|
| 1779 |
+
# R1-4 — wall-aligned rotation v2 overrides the silhouette estimate
|
| 1780 |
+
# when the wall-floor contact band yields a confident direction.
|
| 1781 |
+
wall_mask = np.isin(seg_map, class_ids(WALL_CONTACT_CLASSES)).astype(np.uint8)
|
| 1782 |
+
wall_rot = estimate_wall_rotation(
|
| 1783 |
+
wall_mask, floor_mask, np.asarray(homography, np.float64).reshape(3, 3)
|
| 1784 |
+
)
|
| 1785 |
+
if wall_rot is not None:
|
| 1786 |
+
plane["defaultRotation"] = wall_rot
|
| 1787 |
+
plane["rotationSource"] = "wall-contact"
|
| 1788 |
print(f"[TIMING] Plane fitting / homography calculation took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 1789 |
|
| 1790 |
t0 = time.perf_counter()
|
|
|
|
| 1802 |
|
| 1803 |
t0 = time.perf_counter()
|
| 1804 |
shade_map, shade_range = None, (0.55, 1.35)
|
| 1805 |
+
shade_source = "none"
|
| 1806 |
if ENABLE_INTRINSIC_SHADING:
|
| 1807 |
if intrinsic_models is None:
|
| 1808 |
_load_intrinsic_model()
|
| 1809 |
if intrinsic_models is not None:
|
| 1810 |
shade_map, shade_range = build_intrinsic_shade_map(img_np, surface_mask)
|
| 1811 |
+
if shade_map is not None:
|
| 1812 |
+
shade_source = "intrinsic"
|
| 1813 |
if shade_map is None:
|
| 1814 |
+
shade_map, shade_range = build_shade_map(img_np, surface_mask, rug_mask)
|
| 1815 |
+
if shade_map is not None:
|
| 1816 |
+
shade_source = "luminance"
|
| 1817 |
print(f"[TIMING] Shade map construction took {time.perf_counter() - t0:.3f} seconds", flush=True)
|
| 1818 |
|
| 1819 |
t0 = time.perf_counter()
|
|
|
|
| 1841 |
# Per-region confidence sub-map
|
| 1842 |
region_conf = build_confidence_map(region_mask, occluder_zone)
|
| 1843 |
|
| 1844 |
+
# R3-3 — rug pixels inside this region, so the frontend can offer
|
| 1845 |
+
# a keep/replace toggle (default: replaced, like the benchmark).
|
| 1846 |
+
region_rug = (
|
| 1847 |
+
np.flatnonzero(((region_mask > 0) & (rug_mask > 0)).ravel()).astype(np.uint32)
|
| 1848 |
+
if rug_mask.any()
|
| 1849 |
+
else np.empty(0, np.uint32)
|
| 1850 |
+
)
|
| 1851 |
+
|
| 1852 |
segments.append({
|
| 1853 |
"id": region_idx,
|
| 1854 |
"className": "floor",
|
|
|
|
| 1860 |
"colorTemperature": color_temperature, # B2
|
| 1861 |
"lightVector": light_vector, # B3
|
| 1862 |
"confidenceMap": base64.b64encode(region_conf.tobytes()).decode() if region_conf is not None else None, # B10
|
| 1863 |
+
"rugMask": base64.b64encode(region_rug.tobytes()).decode() if region_rug.size else None, # R3-3
|
| 1864 |
"multiRoom": multi_room, # B7
|
| 1865 |
"gridGroup": "primary" if region_idx == 0 else f"room_{region_idx}", # B7
|
| 1866 |
"metadata": {
|
|
|
|
| 1869 |
"surfacePixels": int(region_mask.sum()),
|
| 1870 |
"depthEnabled": depth is not None,
|
| 1871 |
"shadingEnabled": shade_map is not None,
|
| 1872 |
+
# R4-1 — which extractor produced the shade map, so test
|
| 1873 |
+
# rounds can verify the intrinsic path actually engaged
|
| 1874 |
+
# (the geometrySource lesson).
|
| 1875 |
+
"shadingSource": shade_source,
|
| 1876 |
},
|
| 1877 |
# R1-1 — metric floor depth stats (metres). The seam for R1-2
|
| 1878 |
# (plane fit) and R1-3 (true tile scale); null on relative
|
|
|
|
| 1955 |
pass
|
| 1956 |
|
| 1957 |
|
| 1958 |
+
# R0-2 — image-hash cache: identical photo bytes map to the existing job, so
|
| 1959 |
+
# re-tiling a known photo (or a double-submit) returns instantly instead of
|
| 1960 |
+
# re-running the model pipeline. In-memory is enough: it lives exactly as
|
| 1961 |
+
# long as the job files on the same ephemeral disk.
|
| 1962 |
+
CONVERT_CACHE: dict[str, str] = {}
|
| 1963 |
+
|
| 1964 |
+
|
| 1965 |
@app.post("/viz2d/convert")
|
| 1966 |
async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
|
| 1967 |
if file.content_type and not file.content_type.startswith("image/"):
|
| 1968 |
raise HTTPException(status_code=400, detail="Upload must be a JPG or PNG image.")
|
| 1969 |
|
| 1970 |
+
content = await file.read()
|
| 1971 |
+
digest = hashlib.sha256(content).hexdigest()
|
| 1972 |
+
cached_id = CONVERT_CACHE.get(digest)
|
| 1973 |
+
if cached_id:
|
| 1974 |
+
try:
|
| 1975 |
+
cached = read_job(cached_id)
|
| 1976 |
+
if cached.get("status") == "PROCESSING" or (
|
| 1977 |
+
cached.get("status") == "COMPLETED"
|
| 1978 |
+
and (JOB_DIR / f"{cached_id}.bundle.json").exists()
|
| 1979 |
+
):
|
| 1980 |
+
return cached
|
| 1981 |
+
except Exception:
|
| 1982 |
+
pass # stale entry (evicted files) — fall through to a fresh run
|
| 1983 |
+
|
| 1984 |
job_id = uuid.uuid4().hex
|
| 1985 |
ext = Path(file.filename or "room.jpg").suffix.lower()
|
| 1986 |
if ext not in {".jpg", ".jpeg", ".png", ".webp"}:
|
| 1987 |
ext = ".jpg"
|
| 1988 |
upload_path = UPLOAD_DIR / f"{job_id}{ext}"
|
| 1989 |
with upload_path.open("wb") as out:
|
| 1990 |
+
out.write(content)
|
| 1991 |
+
CONVERT_CACHE[digest] = job_id
|
| 1992 |
|
| 1993 |
job = {
|
| 1994 |
"id": job_id,
|
golden_render.py
CHANGED
|
@@ -55,11 +55,29 @@ def soft_clip(v):
|
|
| 55 |
return np.where(v <= knee, v, knee + (t * rng) / (t + rng))
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
def prepare_texture(tile_path):
|
| 59 |
tex = np.asarray(Image.open(tile_path).convert("RGB"))
|
| 60 |
h, w, _ = tex.shape
|
| 61 |
mode, _, _ = detect_wrap_mode(tex)
|
| 62 |
repeat_scale = 1.0
|
|
|
|
| 63 |
if mode != "wrap":
|
| 64 |
prepared, info = period_snap(tex)
|
| 65 |
if info[0] == "snap":
|
|
@@ -67,10 +85,78 @@ def prepare_texture(tile_path):
|
|
| 67 |
tex = prepared
|
| 68 |
else:
|
| 69 |
tex = make_seamless(tex)
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
d = load_bundle(bundle_path)
|
| 75 |
w, h = d["width"], d["height"]
|
| 76 |
base = np.asarray(
|
|
@@ -110,8 +196,12 @@ def render(bundle_path, tile_path):
|
|
| 110 |
col = np.array([ct.get("r", 1.0), ct.get("g", 1.0), ct.get("b", 1.0)])
|
| 111 |
lv = seg.get("lightVector")
|
| 112 |
|
| 113 |
-
tex, repeat_scale = prepare_texture(tile_path)
|
| 114 |
gloss = estimate_gloss(np.asarray(Image.open(tile_path).convert("RGB")).astype(np.float64))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
th, tw, _ = tex.shape
|
| 116 |
mips = build_mips(tex)
|
| 117 |
max_l = len(mips) - 1
|
|
@@ -154,12 +244,19 @@ def render(bundle_path, tile_path):
|
|
| 154 |
rx1, ry1 = rot(fx1, fy1)
|
| 155 |
rx2, ry2 = rot(fx2, fy2)
|
| 156 |
|
| 157 |
-
u = np.mod(rx / repeat_w, 1.0)
|
| 158 |
-
v = np.mod(ry / repeat_h, 1.0)
|
| 159 |
tcx, tcy = (rx / repeat_w) * tw, (ry / repeat_h) * th
|
| 160 |
du = np.hypot((rx1 / repeat_w) * tw - tcx, (ry1 / repeat_h) * th - tcy)
|
| 161 |
dv = np.hypot((rx2 / repeat_w) * tw - tcx, (ry2 / repeat_h) * th - tcy)
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
l0 = np.clip(np.floor(lod), 0, max_l).astype(np.int64)
|
| 164 |
frac = np.clip(lod - l0, 0, 1)
|
| 165 |
|
|
@@ -177,6 +274,12 @@ def render(bundle_path, tile_path):
|
|
| 177 |
else:
|
| 178 |
sample[sel] = sa
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
shade = (
|
| 181 |
shade_lo + (shade_map[ys, xs] / 255.0) * (shade_hi - shade_lo)
|
| 182 |
if shade_map is not None
|
|
@@ -200,7 +303,9 @@ def render(bundle_path, tile_path):
|
|
| 200 |
dot = np.where(ok, (dfx * lvx + dfy * lvy) / np.maximum(dlen, 1e-9), 0.0)
|
| 201 |
specular = 0.12 * gloss * np.maximum(0, dot) ** 4
|
| 202 |
|
| 203 |
-
texel = soft_clip(sample
|
|
|
|
|
|
|
| 204 |
alpha = conf[ys, xs][:, None] if conf is not None else np.ones((len(xs), 1))
|
| 205 |
|
| 206 |
out = base.copy()
|
|
|
|
| 55 |
return np.where(v <= knee, v, knee + (t * rng) / (t + rng))
|
| 56 |
|
| 57 |
|
| 58 |
+
def apply_shade(sample, m):
|
| 59 |
+
"""Port of applyShade (canvas-engine.ts) — N4 highlight-preserving shading.
|
| 60 |
+
|
| 61 |
+
Dimming (m <= 1) stays a physical multiply. Brightening near-white texels
|
| 62 |
+
by multiply clips at 255 and erases pale-tile detail (the white-tile
|
| 63 |
+
washout), so for m > 1 blend toward a screen-style lift by texel
|
| 64 |
+
brightness: dark texels keep the multiply, bright texels brighten by
|
| 65 |
+
closing their gap to white — grout/figuring contrast survives by
|
| 66 |
+
construction because the result stays below 255.
|
| 67 |
+
"""
|
| 68 |
+
mult = sample * m
|
| 69 |
+
screen = 255.0 - (255.0 - sample) / np.maximum(m, 1e-6)
|
| 70 |
+
t = sample / 255.0
|
| 71 |
+
w = t * t * (3.0 - 2.0 * t)
|
| 72 |
+
return np.where(m <= 1.0, mult, mult * (1.0 - w) + screen * w)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
def prepare_texture(tile_path):
|
| 76 |
tex = np.asarray(Image.open(tile_path).convert("RGB"))
|
| 77 |
h, w, _ = tex.shape
|
| 78 |
mode, _, _ = detect_wrap_mode(tex)
|
| 79 |
repeat_scale = 1.0
|
| 80 |
+
lay_mode = "repeat"
|
| 81 |
if mode != "wrap":
|
| 82 |
prepared, info = period_snap(tex)
|
| 83 |
if info[0] == "snap":
|
|
|
|
| 85 |
tex = prepared
|
| 86 |
else:
|
| 87 |
tex = make_seamless(tex)
|
| 88 |
+
# R2-3 v1 — truly organic materials (healed, not periodic) lay as
|
| 89 |
+
# procedural cells; periodic/authored tiles keep the plain repeat.
|
| 90 |
+
lay_mode = "cells"
|
| 91 |
+
return tex, repeat_scale, lay_mode
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
_M32 = np.uint64(0xFFFFFFFF)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def hash01(a, b):
|
| 98 |
+
"""Port of hash01 (canvas-engine.ts) — bit-exact with Math.imul/>>> JS
|
| 99 |
+
semantics so both engines lay identical cells."""
|
| 100 |
+
a = (np.asarray(a, np.int64) & 0xFFFFFFFF).astype(np.uint64)
|
| 101 |
+
b = (np.asarray(b, np.int64) & 0xFFFFFFFF).astype(np.uint64)
|
| 102 |
+
h = ((a * np.uint64(374761393)) & _M32) ^ ((b * np.uint64(668265263)) & _M32)
|
| 103 |
+
h = ((h ^ (h >> np.uint64(13))) * np.uint64(1274126177)) & _M32
|
| 104 |
+
return ((h ^ (h >> np.uint64(16))) >> np.uint64(8)).astype(np.float64) / 16777216.0
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def procedural_cells(rx, ry, repeat_w, repeat_h, grout_frac, tw, th, footprint, pattern="straight"):
|
| 108 |
+
"""Port of the R2-3 v1 cell logic (canvas-engine.ts composite):
|
| 109 |
+
per-cell toroidal grain offset, tone jitter, pattern-driven bond
|
| 110 |
+
(straight = random running bond, brick = fixed half offset, grid/diamond
|
| 111 |
+
= aligned), and an anti-aliased seam mask. Returns (u, v, tone, blend)."""
|
| 112 |
+
row = np.floor(ry / repeat_h).astype(np.int64)
|
| 113 |
+
if pattern in ("grid", "diamond"):
|
| 114 |
+
stagger = np.zeros(len(row), np.float64)
|
| 115 |
+
elif pattern == "brick":
|
| 116 |
+
stagger = (row & 1) * 0.5
|
| 117 |
+
else:
|
| 118 |
+
stagger = hash01(row, np.full_like(row, 0x9E37))
|
| 119 |
+
sx = rx + stagger * repeat_w
|
| 120 |
+
col = np.floor(sx / repeat_w).astype(np.int64)
|
| 121 |
+
lu = sx / repeat_w - col
|
| 122 |
+
lv = ry / repeat_h - row
|
| 123 |
+
u = np.mod(lu + hash01(col, row), 1.0)
|
| 124 |
+
v = np.mod(lv + hash01(col + 0x55, row - 0x21), 1.0)
|
| 125 |
+
tone = 0.94 + 0.12 * hash01(col - 0x13, row + 0x77)
|
| 126 |
+
half_u = grout_frac * 0.5
|
| 127 |
+
half_v = half_u * (repeat_w / repeat_h)
|
| 128 |
+
aa_u = np.maximum(footprint / tw, 1e-4)
|
| 129 |
+
aa_v = np.maximum(footprint / th, 1e-4)
|
| 130 |
+
du_b = np.minimum(lu, 1.0 - lu)
|
| 131 |
+
dv_b = np.minimum(lv, 1.0 - lv)
|
| 132 |
+
b_u = np.clip((du_b - half_u) / aa_u + 0.5, 0.0, 1.0)
|
| 133 |
+
b_v = np.clip((dv_b - half_v) / aa_v + 0.5, 0.0, 1.0)
|
| 134 |
+
return u, v, tone, 1.0 - np.minimum(b_u, b_v)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def apply_reflection(texel, base, xs, ys, h, w):
|
| 138 |
+
"""Port of the R4-2 gloss reflection (canvas-engine.ts composite):
|
| 139 |
+
mirror the above-floor scene about the per-column contact line, faded
|
| 140 |
+
with distance and weighted by reflected brightness squared."""
|
| 141 |
+
ys_f = ys.astype(np.float64)
|
| 142 |
+
top = np.full(w, np.inf)
|
| 143 |
+
np.minimum.at(top, xs, ys_f)
|
| 144 |
+
floor_flags = np.zeros((h, w), bool)
|
| 145 |
+
floor_flags[ys, xs] = True
|
| 146 |
+
ty = top[xs]
|
| 147 |
+
ry_refl = np.floor(2.0 * ty - ys_f).astype(np.int64)
|
| 148 |
+
valid = np.isfinite(ty) & (ry_refl >= 0) & (ry_refl < h)
|
| 149 |
+
ry_c = np.clip(ry_refl, 0, h - 1)
|
| 150 |
+
src_floor = floor_flags[ry_c, xs]
|
| 151 |
+
refl = base[ry_c, xs]
|
| 152 |
+
lum = (refl[:, 0] * 0.299 + refl[:, 1] * 0.587 + refl[:, 2] * 0.114) / 255.0
|
| 153 |
+
fade = np.maximum(0.0, 1.0 - (ys_f - ty) / (h * 0.35))
|
| 154 |
+
k = np.where(valid & ~src_floor, 0.22 * fade * lum * lum, 0.0)
|
| 155 |
+
k = np.where(k > 0.003, k, 0.0)
|
| 156 |
+
return texel * (1.0 - k[:, None]) + refl * k[:, None]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def render(bundle_path, tile_path, finish="matte"):
|
| 160 |
d = load_bundle(bundle_path)
|
| 161 |
w, h = d["width"], d["height"]
|
| 162 |
base = np.asarray(
|
|
|
|
| 196 |
col = np.array([ct.get("r", 1.0), ct.get("g", 1.0), ct.get("b", 1.0)])
|
| 197 |
lv = seg.get("lightVector")
|
| 198 |
|
| 199 |
+
tex, repeat_scale, lay_mode = prepare_texture(tile_path)
|
| 200 |
gloss = estimate_gloss(np.asarray(Image.open(tile_path).convert("RGB")).astype(np.float64))
|
| 201 |
+
# R2-3 v1 — derived seam tone + width; mirrors canvas-engine.ts (same
|
| 202 |
+
# every-16th-pixel mean, same no-physical-metadata fraction).
|
| 203 |
+
grout_col = tex.reshape(-1, 3)[::16].astype(np.float64).mean(axis=0) * 0.45
|
| 204 |
+
grout_frac = 0.012
|
| 205 |
th, tw, _ = tex.shape
|
| 206 |
mips = build_mips(tex)
|
| 207 |
max_l = len(mips) - 1
|
|
|
|
| 244 |
rx1, ry1 = rot(fx1, fy1)
|
| 245 |
rx2, ry2 = rot(fx2, fy2)
|
| 246 |
|
|
|
|
|
|
|
| 247 |
tcx, tcy = (rx / repeat_w) * tw, (ry / repeat_h) * th
|
| 248 |
du = np.hypot((rx1 / repeat_w) * tw - tcx, (ry1 / repeat_h) * th - tcy)
|
| 249 |
dv = np.hypot((rx2 / repeat_w) * tw - tcx, (ry2 / repeat_h) * th - tcy)
|
| 250 |
+
footprint = np.maximum(np.maximum(du, dv), 1e-3)
|
| 251 |
+
lod = np.log2(footprint) + 0.5
|
| 252 |
+
|
| 253 |
+
if lay_mode == "cells":
|
| 254 |
+
u, v, cell_tone, grout_blend = procedural_cells(
|
| 255 |
+
rx, ry, repeat_w, repeat_h, grout_frac, tw, th, footprint
|
| 256 |
+
)
|
| 257 |
+
else:
|
| 258 |
+
u = np.mod(rx / repeat_w, 1.0)
|
| 259 |
+
v = np.mod(ry / repeat_h, 1.0)
|
| 260 |
l0 = np.clip(np.floor(lod), 0, max_l).astype(np.int64)
|
| 261 |
frac = np.clip(lod - l0, 0, 1)
|
| 262 |
|
|
|
|
| 274 |
else:
|
| 275 |
sample[sel] = sa
|
| 276 |
|
| 277 |
+
if lay_mode == "cells":
|
| 278 |
+
sample = (
|
| 279 |
+
sample * cell_tone[:, None] * (1.0 - grout_blend[:, None])
|
| 280 |
+
+ grout_col[None, :] * grout_blend[:, None]
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
shade = (
|
| 284 |
shade_lo + (shade_map[ys, xs] / 255.0) * (shade_hi - shade_lo)
|
| 285 |
if shade_map is not None
|
|
|
|
| 303 |
dot = np.where(ok, (dfx * lvx + dfy * lvy) / np.maximum(dlen, 1e-9), 0.0)
|
| 304 |
specular = 0.12 * gloss * np.maximum(0, dot) ** 4
|
| 305 |
|
| 306 |
+
texel = soft_clip(apply_shade(sample, shade[:, None] * col[None, :]) + specular[:, None] * 255.0)
|
| 307 |
+
if finish == "gloss":
|
| 308 |
+
texel = apply_reflection(texel, base, xs, ys, h, w)
|
| 309 |
alpha = conf[ys, xs][:, None] if conf is not None else np.ones((len(xs), 1))
|
| 310 |
|
| 311 |
out = base.copy()
|
verify_live_smoke.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R0-3 — post-deploy live smoke gate.
|
| 2 |
+
|
| 3 |
+
Verifies the ARTIFACT, not the pipeline: after a deploy, converts the kitchen
|
| 4 |
+
reference photo (extracted from the committed bundle, so no binary assets in
|
| 5 |
+
the repo) against the LIVE Space and asserts the bundle carries the metric
|
| 6 |
+
stack. Catches stale images, partial rsyncs, and dependency regressions that
|
| 7 |
+
deploy "successfully" while serving old behaviour — both deploy traps hit in
|
| 8 |
+
June 2026 (unpromoted Vercel build; rsync size+mtime skip) would have failed
|
| 9 |
+
this gate within minutes instead of costing a photo test round.
|
| 10 |
+
|
| 11 |
+
Pure stdlib (no pip installs in CI).
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python verify_live_smoke.py [base_url]
|
| 15 |
+
# default base_url: https://modventures-room-visualizer.hf.space
|
| 16 |
+
|
| 17 |
+
Exit 0 = live Space serves the expected stack; non-zero = block/alert.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import base64
|
| 21 |
+
import io
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
import urllib.error
|
| 27 |
+
import urllib.request
|
| 28 |
+
import uuid
|
| 29 |
+
|
| 30 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 31 |
+
BUNDLE = os.path.join(HERE, "data", "ref_kitchen.vizbundle.json")
|
| 32 |
+
DEFAULT_BASE = "https://modventures-room-visualizer.hf.space"
|
| 33 |
+
SPACE_API = "https://huggingface.co/api/spaces/modventures/room-visualizer"
|
| 34 |
+
|
| 35 |
+
BUILD_WAIT_S = 20 * 60 # Space docker rebuild after a push
|
| 36 |
+
CONVERT_RETRY_S = 10 * 60 # wake-from-sleep + model loads on first request
|
| 37 |
+
JOB_WAIT_S = 6 * 60
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_json(url, timeout=30):
|
| 41 |
+
with urllib.request.urlopen(url, timeout=timeout) as r:
|
| 42 |
+
return json.load(r)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def wait_for_space_ready():
|
| 46 |
+
"""Wait out a BUILDING stage; RUNNING/SLEEPING are both fine (a request
|
| 47 |
+
wakes a sleeping Space)."""
|
| 48 |
+
deadline = time.time() + BUILD_WAIT_S
|
| 49 |
+
last = None
|
| 50 |
+
while time.time() < deadline:
|
| 51 |
+
try:
|
| 52 |
+
stage = get_json(SPACE_API).get("runtime", {}).get("stage")
|
| 53 |
+
except Exception as exc:
|
| 54 |
+
stage = f"api-error: {exc}"
|
| 55 |
+
if stage != last:
|
| 56 |
+
print(f" space stage: {stage}", flush=True)
|
| 57 |
+
last = stage
|
| 58 |
+
if stage in ("RUNNING", "SLEEPING", "PAUSED"):
|
| 59 |
+
return stage
|
| 60 |
+
time.sleep(20)
|
| 61 |
+
raise SystemExit(f"FAIL: Space not ready within {BUILD_WAIT_S}s (stage={last})")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def post_convert(base, img_bytes):
|
| 65 |
+
boundary = uuid.uuid4().hex
|
| 66 |
+
body = (
|
| 67 |
+
f"--{boundary}\r\nContent-Disposition: form-data; "
|
| 68 |
+
f'name="file"; filename="smoke.jpg"\r\n'
|
| 69 |
+
f"Content-Type: image/jpeg\r\n\r\n"
|
| 70 |
+
).encode() + img_bytes + f"\r\n--{boundary}--\r\n".encode()
|
| 71 |
+
req = urllib.request.Request(
|
| 72 |
+
base + "/viz2d/convert",
|
| 73 |
+
data=body,
|
| 74 |
+
method="POST",
|
| 75 |
+
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
| 76 |
+
)
|
| 77 |
+
deadline = time.time() + CONVERT_RETRY_S
|
| 78 |
+
while True:
|
| 79 |
+
try:
|
| 80 |
+
with urllib.request.urlopen(req, timeout=120) as r:
|
| 81 |
+
return json.load(r)
|
| 82 |
+
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, OSError) as exc:
|
| 83 |
+
if time.time() > deadline:
|
| 84 |
+
raise SystemExit(f"FAIL: /viz2d/convert unreachable: {exc}")
|
| 85 |
+
print(f" convert not ready ({exc}), retrying...", flush=True)
|
| 86 |
+
time.sleep(30)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main():
|
| 90 |
+
base = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_BASE
|
| 91 |
+
print(f"smoke target: {base}", flush=True)
|
| 92 |
+
|
| 93 |
+
img_bytes = base64.b64decode(json.load(open(BUNDLE))["pixels"])
|
| 94 |
+
print(f" reference photo: {len(img_bytes)} bytes (from committed kitchen bundle)")
|
| 95 |
+
|
| 96 |
+
wait_for_space_ready()
|
| 97 |
+
|
| 98 |
+
job = post_convert(base, img_bytes)
|
| 99 |
+
jid = job.get("id") or job.get("jobId")
|
| 100 |
+
if not jid:
|
| 101 |
+
raise SystemExit(f"FAIL: convert returned no job id: {job}")
|
| 102 |
+
print(f" job: {jid}", flush=True)
|
| 103 |
+
|
| 104 |
+
deadline = time.time() + JOB_WAIT_S
|
| 105 |
+
status = None
|
| 106 |
+
while time.time() < deadline:
|
| 107 |
+
status = get_json(f"{base}/viz2d/jobs/{jid}").get("status")
|
| 108 |
+
if status not in ("PENDING", "PROCESSING"):
|
| 109 |
+
break
|
| 110 |
+
time.sleep(5)
|
| 111 |
+
if status != "COMPLETED":
|
| 112 |
+
raise SystemExit(f"FAIL: job status {status}")
|
| 113 |
+
|
| 114 |
+
bundle = get_json(f"{base}/viz2d/jobs/{jid}/file", timeout=120)
|
| 115 |
+
segs = bundle.get("segments") or []
|
| 116 |
+
if not segs:
|
| 117 |
+
raise SystemExit("FAIL: no segments in live bundle")
|
| 118 |
+
seg = max(segs, key=lambda s: s.get("metadata", {}).get("surfacePixels", 0))
|
| 119 |
+
meta = seg.get("metadata", {})
|
| 120 |
+
plane = seg.get("plane") or {}
|
| 121 |
+
|
| 122 |
+
checks = [
|
| 123 |
+
("depthEnabled", meta.get("depthEnabled") is True),
|
| 124 |
+
("geometrySource=depth-plane", plane.get("geometrySource") == "depth-plane"),
|
| 125 |
+
("metersPerUnit in [0.5, 2.0]",
|
| 126 |
+
isinstance(plane.get("metersPerUnit"), (int, float))
|
| 127 |
+
and 0.5 <= plane["metersPerUnit"] <= 2.0),
|
| 128 |
+
("plane size sane (0.5..20 m)",
|
| 129 |
+
0.5 <= plane.get("width", 0) <= 20 and 0.5 <= plane.get("height", 0) <= 20),
|
| 130 |
+
("shadeMap present", bool(seg.get("shadeMap"))),
|
| 131 |
+
("shadeRange present", bool(seg.get("shadeRange"))),
|
| 132 |
+
# R4-1 — the intrinsic model must actually engage; a silent fall back
|
| 133 |
+
# to the luminance heuristic (load failure, missing weights, trust
|
| 134 |
+
# prompt) is exactly the class of regression this gate exists for.
|
| 135 |
+
("shadingSource=intrinsic", meta.get("shadingSource") == "intrinsic"),
|
| 136 |
+
]
|
| 137 |
+
ok = True
|
| 138 |
+
for label, passed in checks:
|
| 139 |
+
print(f" [{'PASS' if passed else 'FAIL'}] {label}")
|
| 140 |
+
ok &= passed
|
| 141 |
+
if not ok:
|
| 142 |
+
print(f"\n plane: { {k: plane.get(k) for k in ('geometrySource', 'metersPerUnit', 'width', 'height')} }")
|
| 143 |
+
print(f" metadata: { {k: meta.get(k) for k in ('depthEnabled', 'segmenter')} }")
|
| 144 |
+
raise SystemExit("LIVE SMOKE FAILED — the deployed Space is not serving the expected stack")
|
| 145 |
+
|
| 146 |
+
print("\nLIVE SMOKE PASSED")
|
| 147 |
+
return 0
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
raise SystemExit(main())
|
verify_n4_sim.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""N4 — white-tile washout certification (highlight-preserving shading).
|
| 2 |
+
|
| 3 |
+
Certifies apply_shade (golden_render.py, mirrored as applyShade in
|
| 4 |
+
canvas-engine.ts): brightening (shade > 1) must preserve pale-tile detail
|
| 5 |
+
instead of slamming it into the 255 ceiling / soft-clip shoulder.
|
| 6 |
+
|
| 7 |
+
Checks:
|
| 8 |
+
1. dimming path is the exact physical multiply (m <= 1 unchanged behaviour)
|
| 9 |
+
2. continuity at m = 1 (no curve seam between dim and brighten)
|
| 10 |
+
3. white-tile contrast: tile 245 / grout 200 under m = 1.3 keeps >= 60% of
|
| 11 |
+
the unshaded contrast (the old multiply+clip path collapses it)
|
| 12 |
+
4. headroom by construction: any texel under any m in (1, 2] stays < 255
|
| 13 |
+
5. monotonic in texel value for fixed m (no detail inversions)
|
| 14 |
+
6. documents the bug it fixes: the legacy soft_clip(multiply) path keeps
|
| 15 |
+
< 25% of the same contrast
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from golden_render import apply_shade, soft_clip
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
ok = True
|
| 25 |
+
|
| 26 |
+
# 1 — dimming is a pure multiply
|
| 27 |
+
s = np.linspace(0, 255, 256)
|
| 28 |
+
for m in (0.4, 0.7, 1.0):
|
| 29 |
+
got = apply_shade(s, np.full_like(s, m))
|
| 30 |
+
want = s * m
|
| 31 |
+
good = np.allclose(got, want, atol=1e-9)
|
| 32 |
+
print(f" [{'PASS' if good else 'FAIL'}] dim path m={m}: exact multiply")
|
| 33 |
+
ok &= good
|
| 34 |
+
|
| 35 |
+
# 2 — continuity at m = 1
|
| 36 |
+
below = apply_shade(s, np.full_like(s, 1.0 - 1e-9))
|
| 37 |
+
above = apply_shade(s, np.full_like(s, 1.0 + 1e-9))
|
| 38 |
+
good = float(np.max(np.abs(above - below))) < 1e-3
|
| 39 |
+
print(f" [{'PASS' if good else 'FAIL'}] continuity at m=1: max jump "
|
| 40 |
+
f"{float(np.max(np.abs(above - below))):.2e}")
|
| 41 |
+
ok &= good
|
| 42 |
+
|
| 43 |
+
# 3 — white-tile contrast retention under brightening
|
| 44 |
+
tile, grout, m = 245.0, 200.0, 1.3
|
| 45 |
+
base_contrast = tile - grout
|
| 46 |
+
new = apply_shade(np.array([tile, grout]), np.array([m, m]))
|
| 47 |
+
new_contrast = float(new[0] - new[1])
|
| 48 |
+
retained = new_contrast / base_contrast
|
| 49 |
+
good = retained >= 0.60 and float(new.max()) < 255.0
|
| 50 |
+
print(f" [{'PASS' if good else 'FAIL'}] white-tile contrast: {base_contrast:.0f} -> "
|
| 51 |
+
f"{new_contrast:.1f} ({retained * 100:.0f}% retained), max {new.max():.1f} < 255")
|
| 52 |
+
ok &= good
|
| 53 |
+
|
| 54 |
+
# 4 — headroom by construction: any texel BELOW white stays below white
|
| 55 |
+
# (pure 255 in -> 255 out is correct: white can't get whiter).
|
| 56 |
+
sub = s[s < 255.0]
|
| 57 |
+
worst = 0.0
|
| 58 |
+
worst_white = 0.0
|
| 59 |
+
for m in np.linspace(1.001, 2.0, 40):
|
| 60 |
+
worst = max(worst, float(apply_shade(sub, np.full_like(sub, m)).max()))
|
| 61 |
+
worst_white = max(worst_white, float(apply_shade(np.array([255.0]), np.array([m]))[0]))
|
| 62 |
+
good = worst < 255.0 and worst_white <= 255.0
|
| 63 |
+
print(f" [{'PASS' if good else 'FAIL'}] headroom: max output {worst:.2f} < 255 "
|
| 64 |
+
f"for texel<255, white -> {worst_white:.2f} <= 255, m in (1, 2]")
|
| 65 |
+
ok &= good
|
| 66 |
+
|
| 67 |
+
# 5 — monotonic in texel for fixed m
|
| 68 |
+
mono_ok = True
|
| 69 |
+
for m in (1.1, 1.35, 1.8):
|
| 70 |
+
got = apply_shade(s, np.full_like(s, m))
|
| 71 |
+
mono_ok &= bool(np.all(np.diff(got) > -1e-9))
|
| 72 |
+
print(f" [{'PASS' if mono_ok else 'FAIL'}] monotonic in texel for m=1.1/1.35/1.8")
|
| 73 |
+
ok &= mono_ok
|
| 74 |
+
|
| 75 |
+
# 6 — the legacy path really was the bug
|
| 76 |
+
legacy = soft_clip(np.array([tile, grout]) * m)
|
| 77 |
+
legacy_contrast = float(legacy[0] - legacy[1])
|
| 78 |
+
good = legacy_contrast / base_contrast < 0.25
|
| 79 |
+
print(f" [{'PASS' if good else 'FAIL'}] legacy multiply+clip collapses the same "
|
| 80 |
+
f"contrast to {legacy_contrast:.1f} ({legacy_contrast / base_contrast * 100:.0f}%)")
|
| 81 |
+
ok &= good
|
| 82 |
+
|
| 83 |
+
print("\n" + ("ALL N4 SIM CHECKS PASSED" if ok else "N4 SIM CHECKS FAILED"))
|
| 84 |
+
return 0 if ok else 1
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
raise SystemExit(main())
|
verify_r1_rotation_sim.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R1-4 — wall-aligned rotation v2 certification (CI-safe: analytic scene,
|
| 2 |
+
no torch).
|
| 3 |
+
|
| 4 |
+
Reuses the pinhole ground-plane camera from verify_r1_scale_sim and builds a
|
| 5 |
+
ROTATED room: a floor rectangle at a known world angle phi with wall bands
|
| 6 |
+
along its far edges. The analytic metre-plane homography is constructed in
|
| 7 |
+
closed form (and self-checked against the projection), so the only thing
|
| 8 |
+
under test is the REAL estimate_wall_rotation from app.py.
|
| 9 |
+
|
| 10 |
+
Checks:
|
| 11 |
+
1-4. recovers phi = 0 / 18 / -30 / 70 deg within 2 deg (70 folds to -20:
|
| 12 |
+
the tile grid is 90-deg symmetric; perpendicular walls reinforce)
|
| 13 |
+
5. abstains on scattered wall blobs (no straight contact line)
|
| 14 |
+
6. abstains when two walls disagree (0 vs 45 deg — conflicting cues)
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import cv2
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from verify_r1_scale_sim import CAM_H, F, H as IMG_H, PITCH, W as IMG_W
|
| 21 |
+
|
| 22 |
+
# --- real implementation from app.py ------------------------------------------
|
| 23 |
+
src = open("app.py").read()
|
| 24 |
+
ns = {"np": np, "cv2": cv2}
|
| 25 |
+
start = src.index("def estimate_wall_rotation")
|
| 26 |
+
end = src.index("\ndef ", start + 10)
|
| 27 |
+
exec(compile(src[start:end], "app.py", "exec"), ns)
|
| 28 |
+
estimate_wall_rotation = ns["estimate_wall_rotation"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def plane_homography():
|
| 32 |
+
"""Closed-form image -> (x_w, fwd) metre-plane homography for the scene
|
| 33 |
+
camera (height CAM_H, pitch PITCH, f = F, principal point at centre)."""
|
| 34 |
+
c, s = np.cos(PITCH), np.sin(PITCH)
|
| 35 |
+
M = np.array(
|
| 36 |
+
[
|
| 37 |
+
[F, (IMG_W / 2.0) * c, (IMG_W / 2.0) * s * CAM_H],
|
| 38 |
+
[0.0, -F * s + (IMG_H / 2.0) * c, F * c * CAM_H + (IMG_H / 2.0) * s * CAM_H],
|
| 39 |
+
[0.0, c, s * CAM_H],
|
| 40 |
+
]
|
| 41 |
+
)
|
| 42 |
+
return np.linalg.inv(M)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def world_grid(Hp):
|
| 46 |
+
"""Per-pixel (x_w, fwd) via the plane homography; fwd<=0 marked invalid."""
|
| 47 |
+
yy, xx = np.mgrid[0:IMG_H, 0:IMG_W].astype(np.float64)
|
| 48 |
+
p = np.stack([xx, yy, np.ones_like(xx)], axis=-1) @ Hp.T
|
| 49 |
+
z = p[..., 2]
|
| 50 |
+
valid = np.abs(z) > 1e-9
|
| 51 |
+
x_w = np.where(valid, p[..., 0] / np.where(valid, z, 1), 0)
|
| 52 |
+
fwd = np.where(valid, p[..., 1] / np.where(valid, z, 1), -1)
|
| 53 |
+
return x_w, fwd, valid & (fwd > 0.2)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def rotated_room(phi_deg, Hp, walls=("back", "right")):
|
| 57 |
+
"""Floor rect at angle phi with 0.35 m wall bands on the given edges."""
|
| 58 |
+
x_w, fwd, ok = world_grid(Hp)
|
| 59 |
+
phi = np.radians(phi_deg)
|
| 60 |
+
f_c = CAM_H / np.tan(PITCH) * 0.9 + 2.0
|
| 61 |
+
fx = fwd - f_c
|
| 62 |
+
xr = np.cos(phi) * x_w + np.sin(phi) * fx
|
| 63 |
+
fr = -np.sin(phi) * x_w + np.cos(phi) * fx
|
| 64 |
+
HX, HF = 4.0, 2.0
|
| 65 |
+
floor = ok & (np.abs(xr) <= HX) & (np.abs(fr) <= HF)
|
| 66 |
+
wall = np.zeros_like(floor)
|
| 67 |
+
if "back" in walls:
|
| 68 |
+
wall |= ok & (np.abs(xr) <= HX) & (fr > HF) & (fr <= HF + 0.35)
|
| 69 |
+
if "right" in walls:
|
| 70 |
+
wall |= ok & (np.abs(fr) <= HF) & (xr > HX) & (xr <= HX + 0.35)
|
| 71 |
+
return wall.astype(np.uint8), floor.astype(np.uint8)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def fold(a):
|
| 75 |
+
a = a % 90.0
|
| 76 |
+
return a - 90.0 if a >= 45.0 else a
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main():
|
| 80 |
+
ok = True
|
| 81 |
+
Hp = plane_homography()
|
| 82 |
+
|
| 83 |
+
# self-check: the closed-form homography inverts the scene projection
|
| 84 |
+
f0 = CAM_H / np.tan(PITCH) * 0.9
|
| 85 |
+
z_c = np.cos(PITCH) * f0 + np.sin(PITCH) * CAM_H
|
| 86 |
+
y_c = -np.sin(PITCH) * f0 + np.cos(PITCH) * CAM_H
|
| 87 |
+
u, v = 1.0 / z_c * F + IMG_W / 2.0, y_c / z_c * F + IMG_H / 2.0
|
| 88 |
+
p = Hp @ np.array([u, v, 1.0])
|
| 89 |
+
assert abs(p[0] / p[2] - 1.0) < 1e-6 and abs(p[1] / p[2] - f0) < 1e-6, \
|
| 90 |
+
"scene homography inconsistent with projection"
|
| 91 |
+
|
| 92 |
+
for phi in (0.0, 18.0, -30.0, 70.0):
|
| 93 |
+
wall, floor = rotated_room(phi, Hp)
|
| 94 |
+
got = estimate_wall_rotation(wall, floor, Hp)
|
| 95 |
+
want = fold(phi)
|
| 96 |
+
good = got is not None and abs(fold(got - want)) <= 2.0
|
| 97 |
+
print(f" [{'PASS' if good else 'FAIL'}] phi={phi:+.0f} deg -> "
|
| 98 |
+
f"{'None' if got is None else f'{got:+.2f}'} (want {want:+.1f})")
|
| 99 |
+
ok &= good
|
| 100 |
+
|
| 101 |
+
# 5 — scattered blobs over a wide band: no dominant direction to read
|
| 102 |
+
rng = np.random.default_rng(7)
|
| 103 |
+
_, floor = rotated_room(0.0, Hp)
|
| 104 |
+
blobs = np.zeros((IMG_H, IMG_W), np.uint8)
|
| 105 |
+
edge_rows = np.where(floor.any(axis=1))[0]
|
| 106 |
+
top = int(edge_rows[0])
|
| 107 |
+
for _ in range(40):
|
| 108 |
+
cx = int(rng.integers(40, IMG_W - 40))
|
| 109 |
+
cy = int(np.clip(top + rng.integers(-60, 60), 4, IMG_H - 4))
|
| 110 |
+
blobs[cy - 3 : cy + 3, max(0, cx - 5) : cx + 5] = 1
|
| 111 |
+
got = estimate_wall_rotation(blobs, floor, Hp)
|
| 112 |
+
print(f" [{'PASS' if got is None else 'FAIL'}] scattered blobs -> {got}")
|
| 113 |
+
ok &= got is None
|
| 114 |
+
|
| 115 |
+
# 6 — conflicting walls: 0-deg back band + 45-deg diagonal band
|
| 116 |
+
wall0, floor0 = rotated_room(0.0, Hp, walls=("back",))
|
| 117 |
+
x_w, fwd, valid = world_grid(Hp)
|
| 118 |
+
f_c = CAM_H / np.tan(PITCH) * 0.9 + 2.0
|
| 119 |
+
diag = valid & (np.abs((fwd - f_c) - x_w) <= 0.25) & (np.abs(x_w) <= 3.0)
|
| 120 |
+
conflicted = np.maximum(wall0, diag.astype(np.uint8))
|
| 121 |
+
got = estimate_wall_rotation(conflicted, floor0, Hp)
|
| 122 |
+
print(f" [{'PASS' if got is None else 'FAIL'}] conflicting 0/45 walls -> {got}")
|
| 123 |
+
ok &= got is None
|
| 124 |
+
|
| 125 |
+
print("\n" + ("ALL R1-4 SIM CHECKS PASSED" if ok else "R1-4 SIM CHECKS FAILED"))
|
| 126 |
+
return 0 if ok else 1
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
raise SystemExit(main())
|
verify_r2_layout_sim.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R2-3 v1 — procedural-cell layout certification (CI-safe, pure math).
|
| 2 |
+
|
| 3 |
+
Certifies procedural_cells/hash01 (golden_render.py, mirrored bit-for-bit in
|
| 4 |
+
canvas-engine.ts): organic materials lay as individual cells with per-cell
|
| 5 |
+
grain, tone jitter, running-bond stagger, and a generated seam — so
|
| 6 |
+
repetition is impossible by construction.
|
| 7 |
+
|
| 8 |
+
Checks:
|
| 9 |
+
1. determinism: identical inputs -> identical layout (golden stability)
|
| 10 |
+
2. hash01 is JS-bit-exact on reference vectors and well-spread in [0,1)
|
| 11 |
+
3. no repetition: neighbouring cells get distinct grain offsets and tones
|
| 12 |
+
4. running bond: consecutive rows are staggered, not aligned
|
| 13 |
+
5. seam geometry: cell borders are grout, cell interiors are material,
|
| 14 |
+
and the seam width matches grout_frac
|
| 15 |
+
6. anti-aliasing: a coarse footprint widens/soften the seam instead of
|
| 16 |
+
aliasing it
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from golden_render import apply_reflection, hash01, procedural_cells
|
| 22 |
+
|
| 23 |
+
RW, RH = 120.0, 80.0 # repeat cell in plane units
|
| 24 |
+
TW, TH = 256, 256
|
| 25 |
+
GF = 0.012
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def field(px_per_unit=1.0, footprint=1.0, n=400):
|
| 29 |
+
"""Sample a regular grid of plane points across many cells."""
|
| 30 |
+
xs = np.linspace(0, 20 * RW, n)
|
| 31 |
+
ys = np.linspace(0, 20 * RH, n)
|
| 32 |
+
gx, gy = np.meshgrid(xs, ys)
|
| 33 |
+
rx, ry = gx.ravel(), gy.ravel()
|
| 34 |
+
fp = np.full_like(rx, footprint)
|
| 35 |
+
return rx, ry, procedural_cells(rx, ry, RW, RH, GF, TW, TH, fp)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def main():
|
| 39 |
+
ok = True
|
| 40 |
+
|
| 41 |
+
# 1 — determinism
|
| 42 |
+
rx, ry, (u1, v1, t1, g1) = field()
|
| 43 |
+
_, _, (u2, v2, t2, g2) = field()
|
| 44 |
+
good = all(np.array_equal(a, b) for a, b in ((u1, u2), (v1, v2), (t1, t2), (g1, g2)))
|
| 45 |
+
print(f" [{'PASS' if good else 'FAIL'}] deterministic layout")
|
| 46 |
+
ok &= good
|
| 47 |
+
|
| 48 |
+
# 2 — hash01: JS-reference vectors (computed with Math.imul/>>> semantics)
|
| 49 |
+
# and distribution sanity.
|
| 50 |
+
refs = [(0, 0), (1, 0), (0, 1), (-1, 5), (12345, -678), (0x55, -0x21)]
|
| 51 |
+
vals = hash01([a for a, _ in refs], [b for _, b in refs])
|
| 52 |
+
in_range = bool(np.all((vals >= 0) & (vals < 1)))
|
| 53 |
+
grid = hash01(np.arange(10000) % 100, np.arange(10000) // 100)
|
| 54 |
+
spread = abs(float(grid.mean()) - 0.5) < 0.02 and float(grid.std()) > 0.25
|
| 55 |
+
distinct = len(np.unique(np.round(vals, 9))) == len(refs)
|
| 56 |
+
good = in_range and spread and distinct
|
| 57 |
+
print(f" [{'PASS' if good else 'FAIL'}] hash01: range ok, mean "
|
| 58 |
+
f"{grid.mean():.3f}~0.5, std {grid.std():.3f}>0.25, refs distinct")
|
| 59 |
+
ok &= good
|
| 60 |
+
|
| 61 |
+
# 3 — no repetition: adjacent cells differ in grain offset and tone
|
| 62 |
+
cols = np.arange(0, 200, dtype=np.int64)
|
| 63 |
+
rows = np.zeros_like(cols)
|
| 64 |
+
off_a = hash01(cols, rows)
|
| 65 |
+
off_b = hash01(cols + 1, rows)
|
| 66 |
+
tone_a = 0.94 + 0.12 * hash01(cols - 0x13, rows + 0x77)
|
| 67 |
+
diff_frac = float(np.mean(np.abs(off_a - off_b) > 0.05))
|
| 68 |
+
tone_var = float(np.std(tone_a))
|
| 69 |
+
good = diff_frac > 0.85 and tone_var > 0.02
|
| 70 |
+
print(f" [{'PASS' if good else 'FAIL'}] no repetition: {diff_frac * 100:.0f}% of "
|
| 71 |
+
f"neighbours differ in grain (>0.05), tone std {tone_var:.3f}")
|
| 72 |
+
ok &= good
|
| 73 |
+
|
| 74 |
+
# 4 — running bond: row stagger shifts cell boundaries between rows
|
| 75 |
+
stags = hash01(np.arange(50, dtype=np.int64), np.full(50, 0x9E37, dtype=np.int64))
|
| 76 |
+
good = float(np.std(stags)) > 0.2 and len(np.unique(np.round(stags, 6))) > 45
|
| 77 |
+
print(f" [{'PASS' if good else 'FAIL'}] running bond: stagger std {np.std(stags):.3f}, "
|
| 78 |
+
f"{len(np.unique(np.round(stags, 6)))}/50 rows unique")
|
| 79 |
+
ok &= good
|
| 80 |
+
|
| 81 |
+
# 5 — seam geometry at fine footprint: borders grout, interiors material
|
| 82 |
+
row = 3
|
| 83 |
+
stag = float(hash01(np.array([row]), np.array([0x9E37]))[0])
|
| 84 |
+
# exact cell border in x for col 7: sx = 8*RW => rx = 8*RW - stag*RW
|
| 85 |
+
border_x = np.array([8 * RW - stag * RW])
|
| 86 |
+
center_x = np.array([(8 + 0.5) * RW - stag * RW])
|
| 87 |
+
mid_y = np.array([(row + 0.5) * RH])
|
| 88 |
+
fp = np.array([0.5])
|
| 89 |
+
_, _, _, g_border = procedural_cells(border_x, mid_y, RW, RH, GF, TW, TH, fp)
|
| 90 |
+
_, _, _, g_center = procedural_cells(center_x, mid_y, RW, RH, GF, TW, TH, fp)
|
| 91 |
+
# measured seam half-width: walk from the border until material
|
| 92 |
+
offs = np.linspace(0, 0.05, 200) * RW
|
| 93 |
+
_, _, _, g_walk = procedural_cells(border_x + offs, np.full(200, mid_y[0]), RW, RH, GF, TW, TH, np.full(200, 0.5))
|
| 94 |
+
measured_half = float(offs[np.argmax(g_walk < 0.5)]) / RW
|
| 95 |
+
good = (
|
| 96 |
+
float(g_border[0]) > 0.95
|
| 97 |
+
and float(g_center[0]) < 0.05
|
| 98 |
+
and abs(measured_half - GF / 2) < GF * 0.5
|
| 99 |
+
)
|
| 100 |
+
print(f" [{'PASS' if good else 'FAIL'}] seam: border blend {g_border[0]:.2f}>0.95, "
|
| 101 |
+
f"centre {g_center[0]:.2f}<0.05, half-width {measured_half:.4f}~{GF / 2:.4f}")
|
| 102 |
+
ok &= good
|
| 103 |
+
|
| 104 |
+
# 6 — AA: coarse footprint softens the seam (no hard alias at distance)
|
| 105 |
+
_, _, _, g_soft = procedural_cells(border_x + offs, np.full(200, mid_y[0]), RW, RH, GF, TW, TH, np.full(200, 24.0))
|
| 106 |
+
trans_soft = float(np.mean((g_soft > 0.1) & (g_soft < 0.9)))
|
| 107 |
+
trans_hard = float(np.mean((g_walk > 0.1) & (g_walk < 0.9)))
|
| 108 |
+
good = trans_soft > trans_hard
|
| 109 |
+
print(f" [{'PASS' if good else 'FAIL'}] anti-aliasing: transition share "
|
| 110 |
+
f"{trans_soft:.2f} (coarse) > {trans_hard:.2f} (fine)")
|
| 111 |
+
ok &= good
|
| 112 |
+
|
| 113 |
+
# 7 — R2-4 pattern bonds: grid lays aligned, brick alternates half-cells
|
| 114 |
+
mid_y0 = np.array([0.5 * RH])
|
| 115 |
+
mid_y1 = np.array([1.5 * RH])
|
| 116 |
+
probe_x = np.array([8 * RW]) # exact cell border when stagger = 0
|
| 117 |
+
fp1 = np.array([0.5])
|
| 118 |
+
_, _, _, gg0 = procedural_cells(probe_x, mid_y0, RW, RH, GF, TW, TH, fp1, pattern="grid")
|
| 119 |
+
_, _, _, gg1 = procedural_cells(probe_x, mid_y1, RW, RH, GF, TW, TH, fp1, pattern="grid")
|
| 120 |
+
_, _, _, gb1 = procedural_cells(probe_x + 0.5 * RW, mid_y1, RW, RH, GF, TW, TH, fp1, pattern="brick")
|
| 121 |
+
good = float(gg0[0]) > 0.95 and float(gg1[0]) > 0.95 and float(gb1[0]) > 0.95
|
| 122 |
+
print(f" [{'PASS' if good else 'FAIL'}] R2-4 bonds: grid aligned across rows "
|
| 123 |
+
f"({gg0[0]:.2f}/{gg1[0]:.2f}), brick offset half-cell ({gb1[0]:.2f})")
|
| 124 |
+
ok &= good
|
| 125 |
+
|
| 126 |
+
# 8 — R4-2 reflection: bright above-floor content reflects near the
|
| 127 |
+
# contact line, fades with depth, dark content stays quiet
|
| 128 |
+
Hh, Ww = 200, 60
|
| 129 |
+
ys_r, xs_r = np.mgrid[100:200, 0:Ww]
|
| 130 |
+
ys_r, xs_r = ys_r.ravel(), xs_r.ravel()
|
| 131 |
+
base = np.zeros((Hh, Ww, 3), np.float64)
|
| 132 |
+
base[60:100, :30] = 250.0 # bright window above floor, left half
|
| 133 |
+
base[60:100, 30:] = 30.0 # dark wall, right half
|
| 134 |
+
texel = np.full((len(xs_r), 3), 128.0)
|
| 135 |
+
out = apply_reflection(texel, base, xs_r, ys_r, Hh, Ww)
|
| 136 |
+
near_bright = out[(ys_r < 110) & (xs_r < 30), 0].mean()
|
| 137 |
+
near_dark = out[(ys_r < 110) & (xs_r >= 30), 0].mean()
|
| 138 |
+
far_bright = out[(ys_r > 180) & (xs_r < 30), 0].mean()
|
| 139 |
+
good = near_bright > 138 and abs(near_dark - 128) < 2 and abs(far_bright - 128) < 4
|
| 140 |
+
print(f" [{'PASS' if good else 'FAIL'}] R4-2 reflection: near-window {near_bright:.0f}>138, "
|
| 141 |
+
f"dark wall {near_dark:.0f}~128, far {far_bright:.0f}~128")
|
| 142 |
+
ok &= good
|
| 143 |
+
|
| 144 |
+
print("\n" + ("ALL R2-3 SIM CHECKS PASSED" if ok else "R2-3 SIM CHECKS FAILED"))
|
| 145 |
+
return 0 if ok else 1
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
raise SystemExit(main())
|
verify_r3_rug_sim.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R3-3 — rug-replace certification (CI-safe, no models).
|
| 2 |
+
|
| 3 |
+
Two contracts:
|
| 4 |
+
1. Class routing: 'rug' is a REPLACEABLE class (RUG_CLASSES), not an
|
| 5 |
+
occluder — the benchmark behaviour. Verified against the real class sets
|
| 6 |
+
from app.py.
|
| 7 |
+
2. Shade neutrality: with the rug replaced, the heuristic shade map must
|
| 8 |
+
NOT carry the rug's albedo (a dark persian rug would otherwise transfer
|
| 9 |
+
as a giant stain onto the new floor). Inside the rug the shade flattens
|
| 10 |
+
to neutral; outside the feather band the shading is untouched.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import cv2
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
# --- real implementations / class sets from app.py ---------------------------
|
| 17 |
+
src = open("app.py").read()
|
| 18 |
+
ns = {"np": np, "cv2": cv2}
|
| 19 |
+
|
| 20 |
+
sets_start = src.index("PRIMARY_FLOOR_CLASSES")
|
| 21 |
+
sets_end = src.index("\n\n", src.index("OCCLUDER_CLASSES"))
|
| 22 |
+
exec(compile(src[sets_start:sets_end], "app.py", "exec"), ns)
|
| 23 |
+
|
| 24 |
+
for fn in [
|
| 25 |
+
"_adaptive_shade_range",
|
| 26 |
+
"_encode_shade",
|
| 27 |
+
"_dominant_period",
|
| 28 |
+
"_suppress_periodic_shading",
|
| 29 |
+
"build_shade_map",
|
| 30 |
+
]:
|
| 31 |
+
start = src.index(f"def {fn}")
|
| 32 |
+
end = src.index("\ndef ", start + 10)
|
| 33 |
+
exec(compile(src[start:end], "app.py", "exec"), ns)
|
| 34 |
+
build_shade_map = ns["build_shade_map"]
|
| 35 |
+
|
| 36 |
+
H, W = 480, 640
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def scene():
|
| 40 |
+
"""Bright floor (lower half) with a gentle vertical light gradient and a
|
| 41 |
+
DARK rug rectangle; the mask covers floor incl. rug (R3-3 union)."""
|
| 42 |
+
yy = np.mgrid[0:H, 0:W][0].astype(np.float64)
|
| 43 |
+
lum = 150.0 + 40.0 * (yy - H / 2) / (H / 2)
|
| 44 |
+
img = np.clip(lum, 0, 255)
|
| 45 |
+
mask = np.zeros((H, W), np.uint8)
|
| 46 |
+
mask[H // 2 :, :] = 1
|
| 47 |
+
rug = np.zeros((H, W), np.uint8)
|
| 48 |
+
rug[int(H * 0.65) : int(H * 0.85), int(W * 0.3) : int(W * 0.7)] = 1
|
| 49 |
+
img = np.where(rug > 0, 60.0, img)
|
| 50 |
+
img3 = np.stack([img] * 3, axis=2).astype(np.uint8)
|
| 51 |
+
return img3, mask, rug
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def decode(enc, rng):
|
| 55 |
+
lo, hi = rng
|
| 56 |
+
return lo + enc.astype(np.float64) / 255.0 * (hi - lo)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main():
|
| 60 |
+
ok = True
|
| 61 |
+
|
| 62 |
+
# 1 — class routing
|
| 63 |
+
rug_ok = (
|
| 64 |
+
"rug" in ns["RUG_CLASSES"]
|
| 65 |
+
and "rug" not in ns["OCCLUDER_CLASSES"]
|
| 66 |
+
and "rug" not in ns["FLOOR_SURFACE_CLASSES"]
|
| 67 |
+
)
|
| 68 |
+
print(f" [{'PASS' if rug_ok else 'FAIL'}] class routing: rug replaceable "
|
| 69 |
+
f"(RUG_CLASSES), not occluder, not silently merged into floor classes")
|
| 70 |
+
ok &= rug_ok
|
| 71 |
+
|
| 72 |
+
img, mask, rug = scene()
|
| 73 |
+
enc_with, rng_with = build_shade_map(img, mask, rug)
|
| 74 |
+
enc_wo, rng_wo = build_shade_map(img, mask, None)
|
| 75 |
+
rel_with = decode(enc_with.reshape(H, W), rng_with)
|
| 76 |
+
rel_wo = decode(enc_wo.reshape(H, W), rng_wo)
|
| 77 |
+
|
| 78 |
+
rug_interior = cv2.erode(rug, np.ones((31, 31), np.uint8)) > 0
|
| 79 |
+
|
| 80 |
+
# 2 — without neutralisation the rug albedo IS a stain (documents the bug)
|
| 81 |
+
stain = float(rel_wo[rug_interior].mean())
|
| 82 |
+
good = stain < 0.85
|
| 83 |
+
print(f" [{'PASS' if good else 'FAIL'}] un-neutralised rug reads as stain: "
|
| 84 |
+
f"mean shade {stain:.3f} < 0.85")
|
| 85 |
+
ok &= good
|
| 86 |
+
|
| 87 |
+
# 3 — with the rug mask the region flattens to neutral
|
| 88 |
+
flat = float(np.abs(rel_with[rug_interior] - 1.0).mean())
|
| 89 |
+
good = flat < 0.05
|
| 90 |
+
print(f" [{'PASS' if good else 'FAIL'}] neutralised: mean |shade-1| inside rug "
|
| 91 |
+
f"{flat:.3f} < 0.05")
|
| 92 |
+
ok &= good
|
| 93 |
+
|
| 94 |
+
# 4 — shading outside the feather band is untouched
|
| 95 |
+
feather_zone = cv2.dilate(rug, np.ones((81, 81), np.uint8)) > 0
|
| 96 |
+
outside = (mask > 0) & ~feather_zone
|
| 97 |
+
drift = float(np.abs(rel_with[outside] - rel_wo[outside]).mean())
|
| 98 |
+
good = drift < 0.02
|
| 99 |
+
print(f" [{'PASS' if good else 'FAIL'}] outside feather band untouched: "
|
| 100 |
+
f"mean drift {drift:.4f} < 0.02")
|
| 101 |
+
ok &= good
|
| 102 |
+
|
| 103 |
+
print("\n" + ("ALL R3-3 SIM CHECKS PASSED" if ok else "R3-3 SIM CHECKS FAILED"))
|
| 104 |
+
return 0 if ok else 1
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
raise SystemExit(main())
|
verify_r4_eval.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R4-1 — intrinsic vs heuristic shading evaluation on the reference bundles.
|
| 2 |
+
|
| 3 |
+
LOCAL evaluation tool (needs torch + the intrinsic package + model weights);
|
| 4 |
+
not part of `make verify` — the CI-safe integration harness is
|
| 5 |
+
verify_r4_intrinsic_sim.py.
|
| 6 |
+
|
| 7 |
+
For each committed reference bundle this runs the REAL build_shade_map
|
| 8 |
+
(heuristic) and build_intrinsic_shade_map (intrinsic) from app.py on the
|
| 9 |
+
bundle's photo + floor mask, then writes a panel to verify_out/:
|
| 10 |
+
|
| 11 |
+
original | heuristic shade applied to flat gray | intrinsic shade applied
|
| 12 |
+
|
| 13 |
+
Applying the decoded shade to a flat gray floor is the most direct artifact
|
| 14 |
+
view: any tile pattern, stain or halo visible in the gray region is shading
|
| 15 |
+
transfer that would contaminate every replacement floor.
|
| 16 |
+
|
| 17 |
+
Usage: python verify_r4_eval.py
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import base64
|
| 21 |
+
import io
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
|
| 25 |
+
import cv2
|
| 26 |
+
import numpy as np
|
| 27 |
+
from PIL import Image
|
| 28 |
+
|
| 29 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 30 |
+
OUT = os.path.join(HERE, "verify_out")
|
| 31 |
+
|
| 32 |
+
BUNDLES = [
|
| 33 |
+
("desk", os.path.join(HERE, "data", "current_bundle.vizbundle.json")),
|
| 34 |
+
("kitchen", os.path.join(HERE, "data", "ref_kitchen.vizbundle.json")),
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
# --- real implementations from app.py ----------------------------------------
|
| 38 |
+
src = open(os.path.join(HERE, "app.py")).read()
|
| 39 |
+
ns = {"np": np, "cv2": cv2}
|
| 40 |
+
for fn in [
|
| 41 |
+
"_adaptive_shade_range",
|
| 42 |
+
"_encode_shade",
|
| 43 |
+
"_dominant_period",
|
| 44 |
+
"_suppress_periodic_shading",
|
| 45 |
+
"build_shade_map",
|
| 46 |
+
"build_intrinsic_shade_map",
|
| 47 |
+
]:
|
| 48 |
+
start = src.index(f"def {fn}")
|
| 49 |
+
end = src.index("\ndef ", start + 10)
|
| 50 |
+
exec(compile(src[start:end], "app.py", "exec"), ns)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def load_bundle(path):
|
| 54 |
+
d = json.load(open(path))
|
| 55 |
+
img = np.asarray(
|
| 56 |
+
Image.open(io.BytesIO(base64.b64decode(d["pixels"]))).convert("RGB")
|
| 57 |
+
)
|
| 58 |
+
h, w = d["height"], d["width"]
|
| 59 |
+
mask = np.zeros(w * h, bool)
|
| 60 |
+
for s in d["segments"]:
|
| 61 |
+
idx = np.frombuffer(base64.b64decode(s["mask"]), dtype=np.uint32)
|
| 62 |
+
mask[idx] = True
|
| 63 |
+
return img, mask.reshape(h, w).astype(np.uint8)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def decode(enc, rng):
|
| 67 |
+
lo, hi = rng
|
| 68 |
+
return lo + enc.astype(np.float64) / 255.0 * (hi - lo)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def shade_on_gray(img, mask, rel):
|
| 72 |
+
"""Composite: flat gray floor x shade over the original photo."""
|
| 73 |
+
out = img.astype(np.float64).copy()
|
| 74 |
+
gray = 205.0 * np.clip(rel, 0.0, 2.0)
|
| 75 |
+
for c in range(3):
|
| 76 |
+
ch = out[:, :, c]
|
| 77 |
+
ch[mask > 0] = np.clip(gray[mask > 0], 0, 255)
|
| 78 |
+
return out.astype(np.uint8)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def main():
|
| 82 |
+
os.makedirs(OUT, exist_ok=True)
|
| 83 |
+
|
| 84 |
+
print("loading intrinsic model (v2)...", flush=True)
|
| 85 |
+
# same headless-trust shim as app._load_intrinsic_model
|
| 86 |
+
import torch.hub as _hub
|
| 87 |
+
|
| 88 |
+
os.makedirs(_hub.get_dir(), exist_ok=True)
|
| 89 |
+
tl = os.path.join(_hub.get_dir(), "trusted_list")
|
| 90 |
+
if "rwightman_gen-efficientnet-pytorch" not in (
|
| 91 |
+
open(tl).read() if os.path.exists(tl) else ""
|
| 92 |
+
):
|
| 93 |
+
with open(tl, "a") as f:
|
| 94 |
+
f.write("rwightman_gen-efficientnet-pytorch\n")
|
| 95 |
+
|
| 96 |
+
from intrinsic.pipeline import load_models
|
| 97 |
+
|
| 98 |
+
ns["device"] = "cpu"
|
| 99 |
+
ns["intrinsic_models"] = load_models("v2", device="cpu")
|
| 100 |
+
print("model loaded.", flush=True)
|
| 101 |
+
|
| 102 |
+
for name, path in BUNDLES:
|
| 103 |
+
img, mask = load_bundle(path)
|
| 104 |
+
h, w = mask.shape
|
| 105 |
+
|
| 106 |
+
enc_h, rng_h = ns["build_shade_map"](img, mask)
|
| 107 |
+
import time
|
| 108 |
+
|
| 109 |
+
t0 = time.perf_counter()
|
| 110 |
+
enc_i, rng_i = ns["build_intrinsic_shade_map"](img, mask)
|
| 111 |
+
dt = time.perf_counter() - t0
|
| 112 |
+
|
| 113 |
+
if enc_h is None or enc_i is None:
|
| 114 |
+
print(f" [{name}] FAILED: heuristic={enc_h is not None} intrinsic={enc_i is not None}")
|
| 115 |
+
continue
|
| 116 |
+
|
| 117 |
+
rel_h = decode(enc_h.reshape(h, w), rng_h)
|
| 118 |
+
rel_i = decode(enc_i.reshape(h, w), rng_i)
|
| 119 |
+
|
| 120 |
+
for label, rel in (("heuristic", rel_h), ("intrinsic", rel_i)):
|
| 121 |
+
v = rel[mask > 0]
|
| 122 |
+
print(
|
| 123 |
+
f" [{name}] {label:9s} p5={np.percentile(v,5):.3f} "
|
| 124 |
+
f"p50={np.percentile(v,50):.3f} p95={np.percentile(v,95):.3f} "
|
| 125 |
+
f"range=({min(rng_h if label=='heuristic' else rng_i):.2f},"
|
| 126 |
+
f"{max(rng_h if label=='heuristic' else rng_i):.2f})"
|
| 127 |
+
)
|
| 128 |
+
print(f" [{name}] intrinsic runtime: {dt:.1f}s on cpu", flush=True)
|
| 129 |
+
|
| 130 |
+
panel = np.concatenate(
|
| 131 |
+
[img, shade_on_gray(img, mask, rel_h), shade_on_gray(img, mask, rel_i)],
|
| 132 |
+
axis=1,
|
| 133 |
+
)
|
| 134 |
+
scale = min(2200 / panel.shape[1], 1.0)
|
| 135 |
+
if scale < 1.0:
|
| 136 |
+
panel = cv2.resize(
|
| 137 |
+
panel, (round(panel.shape[1] * scale), round(panel.shape[0] * scale))
|
| 138 |
+
)
|
| 139 |
+
out_path = os.path.join(OUT, f"r4_eval_{name}.png")
|
| 140 |
+
Image.fromarray(panel).save(out_path)
|
| 141 |
+
print(f" [{name}] panel: {out_path} (original | heuristic | intrinsic)")
|
| 142 |
+
|
| 143 |
+
return 0
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
raise SystemExit(main())
|
verify_r4_intrinsic_sim.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R4-1 — intrinsic shading integration certification (CI-safe: fake model,
|
| 2 |
+
no torch).
|
| 3 |
+
|
| 4 |
+
build_intrinsic_shade_map is fed a synthetic scene with a KNOWN decomposition:
|
| 5 |
+
a checker/stripe albedo (the old floor's pattern — must NOT transfer) times a
|
| 6 |
+
smooth linear shading field (a daylight gradient + a soft contact shadow —
|
| 7 |
+
MUST transfer). The intrinsic.pipeline module is faked in sys.modules to
|
| 8 |
+
return the ground-truth shading, so what's certified is the integration:
|
| 9 |
+
key handling, inverse-encoding decode, boundary fill, linear->display
|
| 10 |
+
conversion, normalisation, encoding, and every fallback path.
|
| 11 |
+
|
| 12 |
+
Checks:
|
| 13 |
+
1. engages on a clean scene and reproduces the display-space shading on the
|
| 14 |
+
floor interior (the lighting survives)
|
| 15 |
+
2. albedo-blind: the checker pattern's contrast does not reach the output
|
| 16 |
+
(the artifact class N3 patched — patterns, any orientation — is dead
|
| 17 |
+
by construction)
|
| 18 |
+
3. boundary-safe: bright non-floor shading (furniture) does not halo into
|
| 19 |
+
the floor edge band (the desk/curtain light-leak)
|
| 20 |
+
4. inverse-shading key ('inv_shd') is decoded, not used raw
|
| 21 |
+
5. fallbacks: no model / pipeline raises / no shading key / empty mask
|
| 22 |
+
all return (None, default) so the caller falls back to the heuristic
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import sys
|
| 26 |
+
import types
|
| 27 |
+
|
| 28 |
+
import cv2
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
H, W = 480, 640
|
| 32 |
+
GAMMA = 2.2
|
| 33 |
+
|
| 34 |
+
# --- fake intrinsic.pipeline BEFORE extracting app code ----------------------
|
| 35 |
+
_fake_results = {}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _fake_run_pipeline(models, img, device=None):
|
| 39 |
+
if isinstance(_fake_results.get("exc"), Exception):
|
| 40 |
+
raise _fake_results["exc"]
|
| 41 |
+
return dict(_fake_results)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
_pkg = types.ModuleType("intrinsic")
|
| 45 |
+
_mod = types.ModuleType("intrinsic.pipeline")
|
| 46 |
+
_mod.run_pipeline = _fake_run_pipeline
|
| 47 |
+
_pkg.pipeline = _mod
|
| 48 |
+
sys.modules["intrinsic"] = _pkg
|
| 49 |
+
sys.modules["intrinsic.pipeline"] = _mod
|
| 50 |
+
|
| 51 |
+
# --- real implementations from app.py ----------------------------------------
|
| 52 |
+
src = open("app.py").read()
|
| 53 |
+
ns = {"np": np, "cv2": cv2, "intrinsic_models": object(), "device": "cpu"}
|
| 54 |
+
for fn in ["_adaptive_shade_range", "_encode_shade", "build_intrinsic_shade_map"]:
|
| 55 |
+
start = src.index(f"def {fn}")
|
| 56 |
+
end = src.index("\ndef ", start + 10)
|
| 57 |
+
exec(compile(src[start:end], "app.py", "exec"), ns)
|
| 58 |
+
build_intrinsic_shade_map = ns["build_intrinsic_shade_map"]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def scene():
|
| 62 |
+
"""Floor = lower half. Albedo checker x smooth linear shading."""
|
| 63 |
+
yy, xx = np.mgrid[0:H, 0:W].astype(np.float64)
|
| 64 |
+
mask = np.zeros((H, W), np.uint8)
|
| 65 |
+
mask[H // 2 :, :] = 1
|
| 66 |
+
|
| 67 |
+
albedo = np.where(((xx // 40).astype(int) + (yy // 40).astype(int)) % 2 == 0, 0.75, 0.35)
|
| 68 |
+
|
| 69 |
+
shading = 0.35 + 0.55 * (yy / H)
|
| 70 |
+
blob = 0.45 * np.exp(-(((xx - W * 0.7) / 70.0) ** 2 + ((yy - H * 0.8) / 50.0) ** 2))
|
| 71 |
+
shading = np.clip(shading - blob, 0.05, 1.5)
|
| 72 |
+
|
| 73 |
+
img_lin = albedo * shading
|
| 74 |
+
img = (np.clip(img_lin, 0, 1) ** (1 / GAMMA) * 255).astype(np.uint8)
|
| 75 |
+
img = np.stack([img] * 3, axis=2)
|
| 76 |
+
return img, mask, shading, albedo
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def decode(enc, rng):
|
| 80 |
+
lo, hi = rng
|
| 81 |
+
return lo + enc.astype(np.float64) / 255.0 * (hi - lo)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def expected_display(shading, mask):
|
| 85 |
+
med = float(np.median(shading[mask > 0]))
|
| 86 |
+
return np.power(np.clip(shading / med, 0, None), 1 / GAMMA)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main():
|
| 90 |
+
ok = True
|
| 91 |
+
img, mask, shading, albedo = scene()
|
| 92 |
+
|
| 93 |
+
# 1 — engages + reproduces display-space shading on the interior
|
| 94 |
+
_fake_results.clear()
|
| 95 |
+
_fake_results["gry_shd"] = shading.astype(np.float32)
|
| 96 |
+
enc, rng = build_intrinsic_shade_map(img, mask)
|
| 97 |
+
if enc is None:
|
| 98 |
+
print(" [FAIL] did not engage on a clean scene")
|
| 99 |
+
print("\nR4-1 SIM CHECKS FAILED")
|
| 100 |
+
return 1
|
| 101 |
+
rel = decode(enc.reshape(H, W), rng)
|
| 102 |
+
want = expected_display(shading, mask)
|
| 103 |
+
interior = cv2.erode(mask, np.ones((41, 41), np.uint8)) > 0
|
| 104 |
+
# the encoder clips to the adaptive range; compare where 'want' is in-range
|
| 105 |
+
in_rng = (want > min(rng) + 0.02) & (want < max(rng) - 0.02)
|
| 106 |
+
sel = interior & in_rng
|
| 107 |
+
err = np.abs(rel[sel] - want[sel])
|
| 108 |
+
good = float(err.mean()) < 0.02 and float(np.percentile(err, 99)) < 0.06
|
| 109 |
+
print(f" [{'PASS' if good else 'FAIL'}] lighting survives: mean err {err.mean():.4f}, "
|
| 110 |
+
f"p99 {np.percentile(err, 99):.4f} (display space)")
|
| 111 |
+
ok &= good
|
| 112 |
+
|
| 113 |
+
# 2 — albedo-blind: checker cells must not differ in the output
|
| 114 |
+
cell_a = sel & (((np.indices((H, W))[1] // 40) + (np.indices((H, W))[0] // 40)) % 2 == 0)
|
| 115 |
+
cell_b = sel & ~cell_a
|
| 116 |
+
# compare horizontally adjacent same-row cells via local means
|
| 117 |
+
diff = abs(float(rel[cell_a].mean()) - float(rel[cell_b].mean()))
|
| 118 |
+
alb_contrast = abs(float(albedo[cell_a].mean()) - float(albedo[cell_b].mean()))
|
| 119 |
+
good = diff < 0.01 and alb_contrast > 0.3
|
| 120 |
+
print(f" [{'PASS' if good else 'FAIL'}] albedo-blind: checker leakage {diff:.4f} "
|
| 121 |
+
f"(albedo contrast {alb_contrast:.2f} in, <0.01 out)")
|
| 122 |
+
ok &= good
|
| 123 |
+
|
| 124 |
+
# 3 — boundary-safe: blazing-bright furniture shading above the floor
|
| 125 |
+
bright = shading.copy()
|
| 126 |
+
bright[mask == 0] = 5.0
|
| 127 |
+
_fake_results.clear()
|
| 128 |
+
_fake_results["gry_shd"] = bright.astype(np.float32)
|
| 129 |
+
enc_b, rng_b = build_intrinsic_shade_map(img, mask)
|
| 130 |
+
rel_b = decode(enc_b.reshape(H, W), rng_b)
|
| 131 |
+
edge_band = (mask > 0) & (np.indices((H, W))[0] < H // 2 + 12)
|
| 132 |
+
band_sel = edge_band & in_rng
|
| 133 |
+
err_b = np.abs(rel_b[band_sel] - want[band_sel])
|
| 134 |
+
good = float(err_b.mean()) < 0.04 and float(err_b.max()) < 0.12
|
| 135 |
+
print(f" [{'PASS' if good else 'FAIL'}] boundary-safe: edge-band err mean "
|
| 136 |
+
f"{err_b.mean():.4f}, max {err_b.max():.4f} with 5x furniture shading")
|
| 137 |
+
ok &= good
|
| 138 |
+
|
| 139 |
+
# 4 — inverse-shading key decoded
|
| 140 |
+
_fake_results.clear()
|
| 141 |
+
_fake_results["inv_shd"] = (1.0 / (shading + 1.0)).astype(np.float32)
|
| 142 |
+
enc_i, rng_i = build_intrinsic_shade_map(img, mask)
|
| 143 |
+
good = enc_i is not None
|
| 144 |
+
if good:
|
| 145 |
+
rel_i = decode(enc_i.reshape(H, W), rng_i)
|
| 146 |
+
err_i = np.abs(rel_i[sel] - want[sel])
|
| 147 |
+
good = float(err_i.mean()) < 0.02
|
| 148 |
+
print(f" [{'PASS' if good else 'FAIL'}] inv_shd decoded: mean err {err_i.mean():.4f}")
|
| 149 |
+
else:
|
| 150 |
+
print(" [FAIL] inv_shd: did not engage")
|
| 151 |
+
ok &= good
|
| 152 |
+
|
| 153 |
+
# 5 — fallback paths all return None (caller then uses the heuristic)
|
| 154 |
+
cases = []
|
| 155 |
+
_fake_results.clear()
|
| 156 |
+
_fake_results["albedo_only"] = shading.astype(np.float32)
|
| 157 |
+
cases.append(("no shading key", build_intrinsic_shade_map(img, mask)[0] is None))
|
| 158 |
+
_fake_results.clear()
|
| 159 |
+
_fake_results["exc"] = RuntimeError("model exploded")
|
| 160 |
+
cases.append(("pipeline raises", build_intrinsic_shade_map(img, mask)[0] is None))
|
| 161 |
+
_fake_results.clear()
|
| 162 |
+
_fake_results["gry_shd"] = shading.astype(np.float32)
|
| 163 |
+
cases.append(("empty mask", build_intrinsic_shade_map(img, np.zeros_like(mask))[0] is None))
|
| 164 |
+
saved = ns["intrinsic_models"]
|
| 165 |
+
ns["intrinsic_models"] = None
|
| 166 |
+
cases.append(("model not loaded", build_intrinsic_shade_map(img, mask)[0] is None))
|
| 167 |
+
ns["intrinsic_models"] = saved
|
| 168 |
+
for label, passed in cases:
|
| 169 |
+
print(f" [{'PASS' if passed else 'FAIL'}] fallback: {label} -> None")
|
| 170 |
+
ok &= passed
|
| 171 |
+
|
| 172 |
+
print("\n" + ("ALL R4-1 SIM CHECKS PASSED" if ok else "R4-1 SIM CHECKS FAILED"))
|
| 173 |
+
return 0 if ok else 1
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if __name__ == "__main__":
|
| 177 |
+
raise SystemExit(main())
|