#!/usr/bin/env python3 """Independent acceptance gate for the 3D-FRONT export. This script never imports convert_3dfront or unify_3dfront and never reuses their record builders. Everything it checks is either recounted from the two published JSON files or recomputed from the raw house JSON with a second, deliberately different implementation for the two that carry real algorithms (gift-wrapping instead of monotone chain for the hull, a hand-written scanner instead of the regex for the room type), so that a shared bug cannot hide behind itself. furniture_size and furniture_position are transcriptions, not independent derivations: they gate the wiring, not the axis order. There is no independent area computation any more, because room_area_m2 is no longer computed from geometry: it is the raw scene.room[].size scalar, and it is gated against that scalar in both directions. Any failed gate exits non-zero. Usage: python kits/verify_3dfront.py --data-dir data \ --room json_room.json --merged multiroom/json_multi_merged.json """ from __future__ import annotations import argparse import json import math import random import sys from collections import Counter from pathlib import Path # -------------------------------------------------------------------------- # Acceptance baselines (measured on the raw houses, see README.md) # -------------------------------------------------------------------------- BASELINES = { "room_scenes": 56129, "merged_scenes": 6813, "merged_room_total": 56129, "placements_room_view": 533837, "placements_merged_view": 533837, # Direct counts of the raw scene.room[].size values, no geometry involved: # 33,116 rooms state a positive area. Everything else is null -- 4,695 rooms # state 0 and 18,318 carry no size key at all. 33,116 + 23,013 = 56,129. "area_from_source": 33116, "area_null": 23013, "boundary_convex_hull": 50903, "boundary_null": 5226, "room_height_non_null": 49799, "room_height_null": 6330, # room_type is the raw scene.room[].type string normalised through IL3D's # table plus IL3D's own split rule. Every one of the 56,129 rooms states a # type, so nothing is null. Pinned from the 2026-09-03 full run; check_samples # additionally re-derives room_type from raw with an independent scanner. "room_type_non_null": 56129, "room_type_null": 0, # furniture_category is furniture[].category and nothing else; model_info.json # belongs to 3D-FUTURE and disagrees with it on 39% of the placements where # both exist. furniture_size is furniture[].size or the flat furniture[].bbox # -- one quantity under two keys, identical to the last digit over the 2,387 # definitions carrying both -- times children[].scale. Both counts changed with those decisions # and are pinned from the first full run under them. # 236,352 of the 533,837 placements (44.3%) reference a furniture uid the # house does not define, so they carry no category and no extent at all. "category_non_null": 46124, "category_null": 487713, "size_non_null": 182794, "size_null": 351043, "position_non_null": 533432, "position_null": 405, "rotation_no_tilt": 527710, # 6,127 records have null x/y: 5,695 retain yaw and 432 also have null z. # This bucket combines tilted placements and unusable source quaternions; # the converter counts those two cases separately. "rotation_tilt": 6127, "rotation_tilt_yaw_null": 432, # Opening totals interact with the "fewer than four footprint points" filter # (audit: Door 678, Window 579, BayWindow 1911 such meshes, dropped before # grouping). If the observed # numbers differ, the filter interaction must be resolved before release -- # do not quietly relax the gate. "doors_total": 28731, # 47,671 = 23,638 Window + 24,033 BayWindow. Six fewer than the briefing's # 47,677 because a group whose 2D hull collapses to under four points cannot # produce a profile polygon and is now rejected instead of published: # opening_Window_group_hull_under_four 1 + opening_BayWindow_... 5 = 6. Exact, # so the delta is resolved rather than relaxed. "windows_total": 47671, } # The four bulk geometry arrays, and nothing else. "material" and "materialList" # used to be in this set by mistake: on a mesh, material is a uid string, not # geometry. No mesh record is published at all now -- only the type strings, in # source_fields.mesh_types -- so this gate is what proves no geometry leaked in. FORBIDDEN_KEYS = {"xyz", "faces", "normal", "uv"} # Exact key order, checked with == so an added or dropped field fails the gate. # These are the root README schema blocks verbatim, plus source_fields for the # source fields the schema has no slot for. source_fields holds exactly ten keys, # each one a source field that says something about the layout and that no schema # field consumed -- three on the room, seven on a placement. Both lists are # asserted below, per room and per placement, not merely described here. CORE_ROOM_KEYS = [ "room_id", "room_index", "room_type", "room_type_source", "room_boundary", "room_boundary_type", "room_area_m2", "room_height", "coordinate_system", "doors", "windows", "furniture_quantity", "furniture", "source_fields", ] CORE_FURNITURE_KEYS = [ "furniture_category", "furniture_instance_id", "furniture_position", "furniture_rotation", "furniture_size", "source_fields", ] # The twelve root README scene keys, in the README's own order. CORE_SCENE_KEYS = [ "scene_id", "sample_id", "dataset", "source_dataset", "source_subset", "room_count", "total_area", "building_style", "description", "description_source", "provenance", "rooms", ] ROOM_SOURCE_FIELD_KEYS = ["extension_door", "mesh_types", "scene_boundingBox"] FURNITURE_SOURCE_FIELD_KEYS = [ "jid", "title", "bbox", "sourceCategoryId", "valid", "replace_bbox", "parentJid", ] # IL3D's table restated, not imported: this script never imports the converter. ROOM_TYPE_TABLE = { "Aisle": "aisle", "Balcony": "balcony", "BathRoom": "bathroom", "BedRoom": "bedroom", "CloakRoom": "cloakroom", "DiningRoom": "dining room", "ElderlyRoom": "elderly room", "Garage": "garage", "KidsRoom": "kids room", "Kitchen": "kitchen", "LaundryRoom": "laundry room", "Library": "library", "LivingDiningRoom": "living dining room", "LivingRoom": "living room", "OfficeRoom": "office", "OtherRoom": "other room", "RecreationRoom": "recreation room", "StorageRoom": "storage room", } # -------------------------------------------------------------------------- # Independent geometry (different algorithms on purpose) # -------------------------------------------------------------------------- def hull_gift_wrapping(points): """Jarvis march. Independent of the monotone chain used by the converter.""" pts = sorted(set(points)) if len(pts) < 3: return pts start = pts[0] hull, current = [], start while True: hull.append(current) candidate = pts[0] if pts[0] != current else pts[1] for p in pts: if p == current: continue cross = ((candidate[0] - current[0]) * (p[1] - current[1]) - (candidate[1] - current[1]) * (p[0] - current[0])) # Collinearity needs the same tolerance the converter uses (1e-12). # A floor edge sampled at even spacing -- e.g. Bathroom-54893 of house # 0003d406, whose bottom edge carries a vertex at x=1.1575 exactly # between x=0.7575 and x=1.5575 -- is collinear in exact arithmetic but # evaluates to a cross of ~1e-19 in floating point. Testing cross == 0 # made this march keep that mid-edge vertex while the monotone chain # dropped it, and the two hulls then disagreed on a room that is not # actually ambiguous. The algorithms stay different; only the # degeneracy threshold is shared. if cross < -1e-12: candidate = p elif abs(cross) <= 1e-12: far = ((p[0] - current[0]) ** 2 + (p[1] - current[1]) ** 2) near = ((candidate[0] - current[0]) ** 2 + (candidate[1] - current[1]) ** 2) if far > near: candidate = p current = candidate if current == start: return hull if len(hull) > len(pts): raise RuntimeError("gift wrapping did not terminate") def room_type_scan(raw): r"""The converter's normalisation, scanned by hand instead of by regex. convert_3dfront.py splits with re.findall(r"[A-Z][a-z]*|[a-z]+|\d+"); this walks the string. Same partition, different code. """ if not isinstance(raw, str) or not raw.strip(): return None if raw in ROOM_TYPE_TABLE: return ROOM_TYPE_TABLE[raw] words, current, kind = [], "", None for ch in raw: if "A" <= ch <= "Z": starts, k = True, "alpha" elif "a" <= ch <= "z": starts, k = kind != "alpha", "alpha" elif "0" <= ch <= "9": starts, k = kind != "digit", "digit" else: starts, k = True, None if starts and current: words.append(current) current = "" current = current + ch if k else "" kind = k if current: words.append(current) return " ".join(words).lower() if words else raw.lower() def vec3(value): return (isinstance(value, list) and len(value) == 3 and all(isinstance(v, (int, float)) and math.isfinite(float(v)) for v in value)) def size_from_raw(child, defn): """furniture_size re-derived from raw: asset extent x placement scale.""" defn = defn or {} base = None for key in ("size", "bbox"): if vec3(defn.get(key)): base = [float(v) for v in defn[key]] break if base is None or not vec3(child.get("scale")): return None scale = [abs(float(v)) for v in child["scale"]] width, height, length = base[0] * scale[0], base[1] * scale[1], base[2] * scale[2] if any((not math.isfinite(v)) or v <= 0.0 for v in (width, height, length)): return None out = {"width": round(width, 6), "length": round(length, 6), "height": round(height, 6)} return None if any(v <= 0.0 for v in out.values()) else out def same_ring(a, b, tol=1e-6): """Compare two rings ignoring start offset and winding direction.""" if len(a) != len(b): return False n = len(a) for direction in (b, list(reversed(b))): for shift in range(n): rotated = direction[shift:] + direction[:shift] if all(abs(p[0] - q[0]) <= tol and abs(p[1] - q[1]) <= tol for p, q in zip(a, rotated)): return True return False # -------------------------------------------------------------------------- # Streaming readers # -------------------------------------------------------------------------- def iter_json_array(path): """Yield the top-level objects of a large JSON array without loading it.""" decoder = json.JSONDecoder() buffer = "" started = False with open(path, encoding="utf-8") as handle: for line in handle: stripped = line.strip() if not started: if stripped.startswith("["): started = True stripped = stripped[1:].strip() if not stripped: continue else: continue if stripped in ("]", ""): continue buffer += stripped while buffer: buffer = buffer.lstrip(", \t") if not buffer or buffer[0] == "]": buffer = "" break try: obj, end = decoder.raw_decode(buffer) except ValueError: break yield obj buffer = buffer[end:] if buffer.strip(" ,]\n"): raise ValueError(f"{path}: trailing content could not be parsed") def scan_forbidden(node, path, findings): """Publication allowlist: no raw mesh arrays, no local absolute paths. Every node of every merged scene, no sampling. The room view is not scanned separately: its room objects are asserted equal to the merged ones. """ if isinstance(node, dict): for key, value in node.items(): if key in FORBIDDEN_KEYS: findings.append(f"{path}.{key}: forbidden raw-geometry key") scan_forbidden(value, f"{path}.{key}", findings) elif isinstance(node, list): for index, value in enumerate(node): scan_forbidden(value, f"{path}[{index}]", findings) elif isinstance(node, str): if node.startswith("/Users/") or node.startswith("/home/"): findings.append(f"{path}: local absolute path leaked") # -------------------------------------------------------------------------- # Gate 1 + 2 + 5: recount the published files, check invariants, cross-view # -------------------------------------------------------------------------- def walk_views(room_path, merged_path, sample_size, rng): """Single parallel pass over both views. The room view is ordered house-by-house and room-by-room, the merged view house-by-house, so the two can be zipped without holding either in memory. """ stats = Counter() failures = [] scene_ids_room, scene_ids_merged = set(), set() furniture_ids = set() reservoir = [] seen_rooms = 0 forbidden = [] room_iter = iter_json_array(room_path) for merged in iter_json_array(merged_path): stats["merged_scenes"] += 1 scene_ids_merged.add(merged["scene_id"]) if merged["room_count"] != len(merged["rooms"]): failures.append(f"{merged['scene_id']}: room_count != len(rooms)") scan_forbidden(merged, merged["scene_id"], forbidden) known_areas = [r["room_area_m2"] for r in merged["rooms"] if r["room_area_m2"] is not None] expected_total = round(sum(known_areas), 6) if known_areas else None if merged["total_area"] != expected_total: failures.append(f"{merged['scene_id']}: total_area != sum(room_area_m2)") room_ids = [r["room_id"] for r in merged["rooms"]] if len(set(room_ids)) != len(room_ids): failures.append(f"{merged['scene_id']}: duplicate room_id inside scene") for index, room in enumerate(merged["rooms"]): stats["merged_room_total"] += 1 try: single = next(room_iter) except StopIteration: failures.append("room view ended before the merged view") return stats, failures, reservoir, forbidden stats["room_scenes"] += 1 scene_ids_room.add(single["scene_id"]) # --- cross-view identity (this is what B1 protects) -------------- if single["room_count"] != 1 or len(single["rooms"]) != 1: failures.append(f"{single['scene_id']}: room view must hold exactly one room") single_room = None else: single_room = single["rooms"][0] if single_room != room: failures.append(f"{single['scene_id']}: room object differs between views") if list(single.keys()) != CORE_SCENE_KEYS: failures.append(f"{single['scene_id']}: scene key order/set differs from contract") expected_id = f"{merged['scene_id']}::{room['room_id']}" if single["scene_id"] != expected_id: failures.append(f"{single['scene_id']}: scene_id != {expected_id}") # --- field presence and order ----------------------------------- if list(room.keys()) != CORE_ROOM_KEYS: failures.append(f"{single['scene_id']}: room key order/set differs from contract") if list(room["source_fields"].keys()) != ROOM_SOURCE_FIELD_KEYS: failures.append(f"{single['scene_id']}: room source_fields key order/set differs") # interiorgs_agg.py:182 gives sill_height to windows only. if any(d["sill_height"] is not None for d in room["doors"]): failures.append(f"{single['scene_id']}: door carries a sill_height") # --- recount ---------------------------------------------------- btype = room["room_boundary_type"] stats["boundary_convex_hull" if btype == "floor_mesh_convex_hull" else "boundary_null" if btype is None else f"boundary_other:{btype}"] += 1 stats["room_height_non_null" if room["room_height"] is not None else "room_height_null"] += 1 stats["area_null" if room["room_area_m2"] is None else "area_from_source"] += 1 stats["room_type_non_null" if room["room_type"] is not None else "room_type_null"] += 1 stats["doors_total"] += len(room["doors"]) stats["windows_total"] += len(room["windows"]) if room["furniture_quantity"] != len(room["furniture"]): failures.append(f"{single['scene_id']}: furniture_quantity != len(furniture)") # Counted from each file separately, but what actually gates the two # views against each other is the deep equality above; these two can # only diverge on a run that already failed there. stats["placements_merged_view"] += len(room["furniture"]) if single_room is not None: stats["placements_room_view"] += len(single_room["furniture"]) for item in room["furniture"]: if list(item.keys()) != CORE_FURNITURE_KEYS: failures.append(f"{single['scene_id']}: furniture key order differs") if list(item["source_fields"].keys()) != FURNITURE_SOURCE_FIELD_KEYS: failures.append( f"{single['scene_id']}: furniture source_fields key order/set differs") furniture_ids.add(item["furniture_instance_id"]) stats["category_non_null" if item["furniture_category"] is not None else "category_null"] += 1 stats["size_non_null" if item["furniture_size"] is not None else "size_null"] += 1 stats["position_non_null" if item["furniture_position"] is not None else "position_null"] += 1 rot = item["furniture_rotation"] if rot["x"] is None and rot["y"] is None: stats["rotation_tilt"] += 1 if rot["z"] is None: stats["rotation_tilt_yaw_null"] += 1 else: stats["rotation_no_tilt"] += 1 seen_rooms += 1 if len(reservoir) < sample_size: reservoir.append(single) else: j = rng.randrange(seen_rooms) if j < sample_size: reservoir[j] = single if next(room_iter, None) is not None: failures.append("room view has more records than the merged view") if len(scene_ids_room) != stats["room_scenes"]: failures.append("duplicate scene_id in json_room.json") if len(scene_ids_merged) != stats["merged_scenes"]: failures.append("duplicate scene_id in the merged view") if len(furniture_ids) != stats["placements_merged_view"]: failures.append("duplicate furniture_instance_id across the dataset") return stats, failures, reservoir, forbidden # -------------------------------------------------------------------------- # Gate 3 + 4: recompute sampled rooms from the raw house JSON # -------------------------------------------------------------------------- def recompute_room(house_path, source_room_id): """Rebuild from raw everything the sampled gate compares against. Boundary, room_type, and per-placement position / category / size. Nothing here reads the published files, and nothing imports the converter. """ with open(house_path, encoding="utf-8") as handle: data = json.load(handle) mesh_by_uid = {m["uid"]: m for m in data.get("mesh", []) if m.get("uid") is not None} # First definition wins, the way the converter indexes them. furniture_by_uid = {} for defn in data.get("furniture", []): uid = defn.get("uid") if uid is not None and uid not in furniture_by_uid: furniture_by_uid[uid] = defn room = next((r for r in (data.get("scene") or {}).get("room", []) or [] if r.get("instanceid") == source_room_id), None) if room is None: return None floor_xy = [] positions, categories, sizes = {}, {}, {} for child in room.get("children", []): instanceid = child.get("instanceid") or "" if instanceid.startswith("furniture/"): defn = furniture_by_uid.get(child.get("ref")) pos = child.get("pos") if vec3(pos): positions[instanceid] = { "x": round(float(pos[0]), 6), "y": round(-float(pos[2]), 6), "z": round(float(pos[1]), 6), } else: positions[instanceid] = None categories[instanceid] = (defn or {}).get("category") or None sizes[instanceid] = size_from_raw(child, defn) continue mesh = mesh_by_uid.get(child.get("ref")) if mesh is not None and mesh.get("type") == "Floor": xyz = mesh.get("xyz") or [] floor_xy.extend((float(xyz[i]), -float(xyz[i + 2])) for i in range(0, len(xyz) - 2, 3)) hull = hull_gift_wrapping(floor_xy) if floor_xy else [] boundary = ([[round(p[0], 6), round(p[1], 6)] for p in hull] if len(hull) >= 3 else None) return {"boundary": boundary, "positions": positions, "categories": categories, "sizes": sizes, "source_area": room.get("size"), "room_type": room_type_scan(room.get("type"))} def check_samples(house_dir, samples, failures, stats): for scene in samples: room = scene["rooms"][0] # str.removeprefix is 3.9+; the project env is 3.8, so slice it. house_uid = scene["scene_id"].split("::")[0] if house_uid.startswith("3dfront_"): house_uid = house_uid[len("3dfront_"):] recomputed = recompute_room(house_dir / f"{house_uid}.json", scene["provenance"]["source_room_id"]) stats["sampled_rooms"] += 1 if recomputed is None: failures.append(f"{scene['scene_id']}: source room not found in raw house") continue if (recomputed["boundary"] is None) != (room["room_boundary"] is None): failures.append(f"{scene['scene_id']}: boundary presence differs from raw") elif recomputed["boundary"] is not None: if not same_ring(room["room_boundary"], recomputed["boundary"]): failures.append(f"{scene['scene_id']}: recomputed hull differs") # room_type carries no pinned baseline yet, so this is what gates it: the # published string must equal the one an independent scanner derives from # raw scene.room[].type. if room["room_type"] != recomputed["room_type"]: failures.append( f"{scene['scene_id']}: room_type {room['room_type']!r} " f"!= {recomputed['room_type']!r} re-derived from raw") # room_area_m2 is the raw scene.room[].size scalar or nothing. Both # directions are gated: a published value must equal the raw one, and a # null must be backed by a raw value that is absent or non-positive -- so # this can never quietly swallow a room that did state an area. raw = recomputed["source_area"] raw_positive = (isinstance(raw, (int, float)) and not isinstance(raw, bool) and math.isfinite(raw) and raw > 0) if room["room_area_m2"] is not None: if not raw_positive or abs(room["room_area_m2"] - round(float(raw), 6)) > 1.5e-6: failures.append( f"{scene['scene_id']}: room_area_m2 {room['room_area_m2']} " f"!= raw scene.room[].size {raw}") elif raw_positive and round(float(raw), 6) > 0: failures.append( f"{scene['scene_id']}: room_area_m2 null but raw size is {raw}") # Conservation: every furniture placement of the room must be published, # with the position the raw pos maps to. The raw placement id is the tail # of furniture_instance_id, so a dropped or duplicated placement fails # here even though no source object is retained any more. recomputed # carries None for a placement whose raw pos is unusable, so a position # that was dropped while the source had one fails the same comparison. def raw_id(item): return item["furniture_instance_id"].split("::", 1)[-1] published = [raw_id(f) for f in room["furniture"]] if len(published) != len(set(published)): failures.append(f"{scene['scene_id']}: duplicate placement ids in one room") if set(published) != set(recomputed["positions"]): failures.append(f"{scene['scene_id']}: furniture placement set differs from raw") # category and size have no pinned baseline either; like room_type they # are gated per sampled placement against a re-derivation from raw. for item in room["furniture"]: sid = raw_id(item) stats["sampled_placements"] += 1 if item["furniture_position"] != recomputed["positions"].get(sid): failures.append(f"{scene['scene_id']}/{sid}: position differs") if item["furniture_category"] != recomputed["categories"].get(sid): failures.append(f"{scene['scene_id']}/{sid}: furniture_category differs from raw") if item["furniture_size"] != recomputed["sizes"].get(sid): failures.append(f"{scene['scene_id']}/{sid}: furniture_size differs from raw") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data-dir", type=Path, default=Path("data")) parser.add_argument("--room", type=Path, default=Path("json_room.json")) parser.add_argument("--merged", type=Path, default=Path("multiroom/json_multi_merged.json")) parser.add_argument("--sample", type=int, default=300, help="rooms recomputed from raw house JSON") parser.add_argument("--seed", type=int, default=0) parser.add_argument("--subset", action="store_true", help="skip absolute count baselines (smoke runs)") args = parser.parse_args() rng = random.Random(args.seed) stats, failures, samples, forbidden = walk_views( args.room, args.merged, args.sample, rng) check_samples(args.data_dir / "3D-FRONT", samples, failures, stats) failures.extend(forbidden) baseline_report = {} if not args.subset: for key, expected in BASELINES.items(): actual = stats.get(key, 0) if expected is None: # Not yet measured on a full run. Reported so the number can be # pinned, but it cannot gate anything until it is. baseline_report[key] = {"expected": None, "actual": actual, "ok": None, "note": "unpinned"} continue baseline_report[key] = {"expected": expected, "actual": actual, "ok": actual == expected} if actual != expected: failures.append(f"baseline {key}: expected {expected}, got {actual}") report = { "counts": dict(sorted(stats.items())), "baselines": baseline_report, "failures": failures[:50], "failure_count": len(failures), "verdict": "PASS" if not failures else "FAIL", } print(json.dumps(report, ensure_ascii=False, indent=2)) return 0 if not failures else 1 if __name__ == "__main__": sys.exit(main())