Download SpatialGen_exported/kits/convert_spatialgen.py from BillLin66/3D_Room_Collections: direct link, hf CLI and curl.
- Browser
- Download file 19.7 kB
-
https://huggingface.co/datasets/BillLin66/3D_Room_Collections/resolve/main/SpatialGen_exported/kits/convert_spatialgen.py
- Command line
-
hf download hf://datasets/BillLin66/3D_Room_Collections/SpatialGen_exported/kits/convert_spatialgen.py
-
curl -L -o convert_spatialgen.py https://huggingface.co/datasets/BillLin66/3D_Room_Collections/resolve/main/SpatialGen_exported/kits/convert_spatialgen.py
19.7 kB
| #!/usr/bin/env python3 | |
| """SpatialGen-Testset layouts -> the unified room-layout schema. | |
| One scene -> one record with a single room. The only input is each scene's | |
| ``room_layout.json`` plus the caption JSONL; the 4,800 rendered images and the | |
| 48 ``cameras.json`` are not downloaded, because the schema has no field for a | |
| view or a camera pose. Why each value is what it is -- which published export | |
| it copies, and which choices are ours -- is in the README. | |
| conda run -n base python kits/convert_spatialgen.py [--limit N] | |
| """ | |
| from __future__ import annotations | |
| import argparse, collections, json, math | |
| from pathlib import Path | |
| DATASET = "SpatialGen" | |
| SPLIT = "test" | |
| LICENSE_TAG = "CC BY-NC 4.0 (attribution, non-commercial)" | |
| # floor[] and ceil[] are millimetres, bboxes[] are metres -- the two units live | |
| # in one file. The factor is the source's own: layout_utils.py sets SCALE=0.001 | |
| # before touching floor or ceil, and never scales a box. | |
| MILLIMETRE = 0.001 | |
| # PROJECT DECISION (approved 2026-09-09): three labels are renamed, written as | |
| # "new(source)" so the source string stays readable in the value itself. | |
| # | |
| # bboxes[].class comes from an ADE20K label set: 60 of the 62 labels in | |
| # layout_utils.py carry the exact RGB of an ADE20K-150 class, byte for byte | |
| # (only "nightstand" and "other" are the authors' own). ADE20K is a general | |
| # scene-parsing vocabulary with no class for a recessed or track-mounted light, | |
| # so 372 internal ids collapse onto those 62 labels and the indoor fixtures land | |
| # on outdoor words. Checked by projecting the eight corners of each box into | |
| # the official renders with the released camera parameters: "traffic light" is | |
| # ceiling downlights and track spots (261 boxes, 26.7%), "screen door, screen" | |
| # is ordinary interior doors (82), "street lamp" is table and floor lamps (6). | |
| CATEGORY_RENAMES = { | |
| "traffic light": "ceiling lamp", | |
| "screen door, screen": "door", | |
| "street lamp": "lamp", | |
| } | |
| # "chandelier" (ring pendants) and "other" (a genuine mixed bag: vents, chair | |
| # groups, plants) were checked the same way and are right, so they stay. So | |
| # does "crt screen" -- its one instance is a slatted wall panel that no label in | |
| # the vocabulary describes, and inventing one for a single box helps nobody. | |
| # Openings are matched on the SOURCE string, before the rename. | |
| OPENING_LABELS = {"screen door, screen": "doors", "window": "windows"} | |
| # PROJECT DECISION (approved 2026-09-09): room_type read from the caption. | |
| # | |
| # room_layout.json has no room-type field and room_uid is just "scene_00000", | |
| # so the caption is the only place the room is named. Every one of the 48 | |
| # captions names it in the first sentence, but a regex tuned to 48 samples is a | |
| # lookup table that hides its judgement, so the table is written out instead. | |
| # The caption itself is published verbatim in `description`, so every entry here | |
| # can be checked against the record that carries it. Values follow IL3D's | |
| # vocabulary, the one this project's 3D-FRONT export already normalises to. | |
| # | |
| # The type is whatever the first sentence calls the room, never the furniture it | |
| # goes on to list: scene_00019 opens with "a modern, open-concept living area" | |
| # and only later mentions a dining table and a kitchen area, so it is a living | |
| # room. A first sentence that declares a blend of living and dining gets IL3D's | |
| # compound value: the renders for scene_00012, scene_00044 and scene_00046 all | |
| # show a dining table and a seating area in the same space, so the compound is | |
| # what the room is, not a wording artefact. | |
| ROOM_TYPES = { | |
| "scene_00000": "living room", "scene_00001": "bedroom", | |
| "scene_00002": "bedroom", "scene_00003": "bathroom", | |
| "scene_00004": "bedroom", "scene_00005": "kitchen", | |
| "scene_00006": "living room", "scene_00007": "kitchen", | |
| "scene_00008": "bedroom", "scene_00009": "living room", | |
| "scene_00010": "bedroom", "scene_00011": "bedroom", | |
| "scene_00012": "living dining room", "scene_00013": "bedroom", | |
| "scene_00014": "bedroom", "scene_00015": "office", | |
| "scene_00016": "bathroom", "scene_00017": "living room", | |
| "scene_00018": "bedroom", "scene_00019": "living room", | |
| "scene_00020": "bedroom", "scene_00021": "bedroom", | |
| "scene_00022": "kitchen", "scene_00023": "bedroom", | |
| "scene_00024": "office", "scene_00025": "kitchen", | |
| "scene_00026": "kitchen", "scene_00027": "living room", | |
| "scene_00029": "bedroom", "scene_00030": "bedroom", | |
| "scene_00031": "bedroom", "scene_00032": "bedroom", | |
| "scene_00033": "bedroom", "scene_00034": "kitchen", | |
| "scene_00035": "bedroom", "scene_00036": "bathroom", | |
| "scene_00037": "bedroom", "scene_00038": "bedroom", | |
| "scene_00039": "bedroom", "scene_00040": "kitchen", | |
| "scene_00041": "kitchen", "scene_00042": "kitchen", | |
| "scene_00043": "living room", "scene_00044": "living dining room", | |
| "scene_00045": "bedroom", "scene_00046": "living dining room", | |
| "scene_00047": "bedroom", "scene_00048": "bathroom", | |
| } | |
| # scene_00028 does not exist: the release numbers 00000-00048 and skips it. | |
| # room_type_source per scene. 41 captions name the room with the vocabulary | |
| # word itself in their first sentence, which is exactly what this collection | |
| # already calls "description_explicit_keyword" (M3DLayout writes it for the | |
| # Infinigen and Matterport3D room types it reads out of a description). | |
| # | |
| # PROJECT DECISION (approved 2026-09-09): the seven below say what the room is | |
| # without using that word -- "living space" / "living area" for a living room, | |
| # "hotel suite or guest room" for a bedroom, and three first sentences that | |
| # declare a blend of dining and living the vocabulary has one compound word for. | |
| # The root README's room_type_source table lists "inferred_from_description" for | |
| # exactly this -- a room type read out of a description rather than quoted from | |
| # it. The published data does not carry that value anywhere (the export the | |
| # README attributes it to writes "description_explicit_keyword"), so it is taken | |
| # from the documented enum, not from a sibling export. The alternative was the | |
| # collection's "unavailable" plus room_type "unknown", which throws away seven | |
| # room types the caption does state. | |
| ROOM_TYPE_INFERRED = frozenset({ | |
| "scene_00006", # "a modern, open-concept living space" | |
| "scene_00009", # "a modern living space featuring a cozy seating area" | |
| "scene_00011", # "a modern, comfortable hotel suite or guest room" | |
| "scene_00012", # "blends the kitchen, dining area, and living room" | |
| "scene_00019", # "a modern, open-concept living area" | |
| "scene_00044", # "blends a dining area with a living room" | |
| "scene_00046", # "a modern dining and living area" | |
| }) | |
| EXPLICIT_KEYWORD = "description_explicit_keyword" | |
| INFERRED = "inferred_from_description" | |
| COORDINATE_SYSTEM = ( | |
| "meter; right-handed; Z-up; scene-local origin; source axes unchanged; " | |
| "furniture_position=box center; furniture_size=instance-scaled local XYZ " | |
| "full extents; furniture_rotation=yaw about +Z in degrees, x/y=0 when " | |
| "upright and null when tilted, z=null when yaw is undefined; " | |
| "source_fields.floor/ceil retain source millimeters" | |
| ) | |
| # -------------------------------------------------------------------------- | |
| # Geometry helpers (standard library only) | |
| # -------------------------------------------------------------------------- | |
| def matrix_of(flat): | |
| """The 16 numbers of `transform` as 4 rows of 4.""" | |
| return [[float(flat[r * 4 + c]) for c in range(4)] for r in range(4)] | |
| def column_norms(matrix): | |
| return [math.sqrt(sum(matrix[r][c] ** 2 for r in range(3))) for c in range(3)] | |
| def determinant(m): | |
| return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) | |
| - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) | |
| + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])) | |
| def yaw_and_tilt(matrix): | |
| """Yaw about the output +Z and a tilt flag. IL3D's rule, and this project's | |
| 3D-FRONT converter uses the same function. | |
| It reads column 0 for the yaw and column 2 for the tilt, and never reads | |
| column 1 -- which is why the 36.8% of source frames whose determinant is -1 | |
| need no repair. A negative determinant means the designer mirrored the | |
| instance; a box is symmetric about each of its own axes, so the mirror moves | |
| none of its eight corners and only flips the sign of an axis this rule does | |
| not use. The unmodified transform is kept in source_fields either way. | |
| """ | |
| horizontal = math.hypot(matrix[0][0], matrix[1][0]) | |
| yaw = None | |
| if horizontal > 1e-8: | |
| yaw = math.degrees(math.atan2(matrix[1][0], matrix[0][0])) | |
| yaw = ((yaw + 180.0) % 360.0) - 180.0 | |
| yaw = round(yaw, 6) | |
| up = [matrix[i][2] for i in range(3)] | |
| has_tilt = math.sqrt(up[0] ** 2 + up[1] ** 2 + (up[2] - 1.0) ** 2) > 1e-4 | |
| return yaw, has_tilt | |
| def chain_loops(segments, tol=1e-6): | |
| """Wall segments -> closed loops of XY points. | |
| The source lists the segments in no particular order, so they are chained | |
| end to end. Each loop is returned without the repeated closing vertex, or | |
| None in place of a loop that does not close. | |
| """ | |
| remaining = list(segments) | |
| used = [False] * len(remaining) | |
| def same(p, q): | |
| return abs(p[0] - q[0]) <= tol and abs(p[1] - q[1]) <= tol | |
| loops = [] | |
| for seed in range(len(remaining)): | |
| if used[seed]: | |
| continue | |
| used[seed] = True | |
| points = [remaining[seed][0], remaining[seed][1]] | |
| growing = True | |
| while growing: | |
| growing = False | |
| for i, (a, b) in enumerate(remaining): | |
| if used[i]: | |
| continue | |
| if same(points[-1], a): | |
| points.append(b) | |
| elif same(points[-1], b): | |
| points.append(a) | |
| elif same(points[0], b): | |
| points.insert(0, a) | |
| elif same(points[0], a): | |
| points.insert(0, b) | |
| else: | |
| continue | |
| used[i] = True | |
| growing = True | |
| loops.append(points[:-1] if same(points[0], points[-1]) else None) | |
| return loops | |
| def signed_area(points): | |
| """Shoelace. Positive when the ring is counter-clockwise.""" | |
| total = 0.0 | |
| for i, (x, y) in enumerate(points): | |
| nx, ny = points[(i + 1) % len(points)] | |
| total += x * ny - nx * y | |
| return total / 2.0 | |
| def canonical_ring(points): | |
| """Counter-clockwise, starting at the lexicographically smallest vertex. | |
| A ring has as many encodings as it has vertices, times two for the winding. | |
| Pinning one of them is what lets a value be compared between runs; it is a | |
| choice of encoding, not a change of shape. Matches the 3D-FRONT converter, | |
| whose hull also starts at the smallest vertex. | |
| """ | |
| if signed_area(points) < 0: | |
| points = points[::-1] | |
| start = min(range(len(points)), key=lambda i: points[i]) | |
| return points[start:] + points[:start] | |
| # -------------------------------------------------------------------------- | |
| # Records | |
| # -------------------------------------------------------------------------- | |
| def category_of(raw): | |
| """Renamed labels keep the source string in brackets; the rest are the | |
| source string with its whitespace trimmed -- the window label carries a | |
| trailing space, an artefact of shortening ADE20K's "windowpane;window".""" | |
| new = CATEGORY_RENAMES.get(raw) | |
| return f"{new}({raw})" if new else raw.strip() | |
| def furniture_record(box, index, scene_id, counters): | |
| matrix = matrix_of(box["transform"]) | |
| norms = column_norms(matrix) | |
| frame = [[matrix[r][c] / norms[c] for c in range(3)] for r in range(3)] | |
| yaw, has_tilt = yaw_and_tilt(frame) | |
| mirrored = determinant(frame) < 0 | |
| # Rounded once, so the counter below and the published record agree on | |
| # what "flat" means; counting the unrounded value disagrees on one box. | |
| size = [round(float(box["size"][i]) * norms[i], 6) for i in range(3)] | |
| counters["furniture_mirrored_frame"] += mirrored | |
| counters["furniture_tilted"] += has_tilt | |
| counters["furniture_flat"] += min(size) < 0.02 | |
| counters["furniture_renamed"] += box["class"] in CATEGORY_RENAMES | |
| return { | |
| "furniture_category": category_of(box["class"]), | |
| # No source carries an object id: bboxes[] entries hold class, transform | |
| # and size and nothing else, so the index in that list is the only | |
| # handle the source gives. | |
| "furniture_instance_id": f"{scene_id}::obj_{index}", | |
| "furniture_position": dict(zip("xyz", (round(matrix[i][3], 6) for i in range(3)))), | |
| # x and y are 0.0 for an upright box and null for a tilted one, rather | |
| # than an invented angle -- IL3D aggregate_scenes.py:245. | |
| "furniture_rotation": {"x": None if has_tilt else 0.0, | |
| "y": None if has_tilt else 0.0, | |
| "z": yaw}, | |
| "furniture_size": dict(zip(("width", "length", "height"), size)), | |
| # Every source key, unmodified, plus the two derived numbers needed to | |
| # read the published values back: the scale that separates size from | |
| # furniture_size, and the handedness that furniture_rotation drops. | |
| "source_fields": { | |
| "class": box["class"], | |
| "transform": box["transform"], | |
| "size": box["size"], | |
| "index": index, | |
| "transform_scale": [round(v, 9) for v in norms], | |
| "transform_mirrored": mirrored, | |
| }, | |
| } | |
| def convert_scene(scene_id, layout, caption, counters): | |
| prefixed = f"spatialgen_{scene_id}" | |
| boxes = layout["bboxes"] | |
| counters["boxes_total"] += len(boxes) | |
| furniture, openings = [], collections.defaultdict(list) | |
| for index, box in enumerate(boxes): | |
| furniture.append(furniture_record(box, index, prefixed, counters)) | |
| field = OPENING_LABELS.get(box["class"].strip()) | |
| if field: | |
| openings[field].append({"furniture_index": index}) | |
| for field in ("doors", "windows"): | |
| counters[f"empty_{field}"] += not openings[field] | |
| segments = [((round(s["start"]["x"] * MILLIMETRE, 9), round(s["start"]["y"] * MILLIMETRE, 9)), | |
| (round(s["end"]["x"] * MILLIMETRE, 9), round(s["end"]["y"] * MILLIMETRE, 9))) | |
| for s in layout["floor"]] | |
| loops = chain_loops(segments) | |
| if len(loops) == 1 and loops[0] is not None and len(loops[0]) >= 3: | |
| # Rounded first, then canonicalised, so the published ring really does | |
| # start at its own smallest vertex: ordering the full-precision points | |
| # and rounding afterwards can put two vertices that tie at six decimals | |
| # the other way round. The area follows the published ring for the same | |
| # reason -- recomputing it from room_boundary has to give room_area_m2. | |
| ring = canonical_ring([(round(x, 6), round(y, 6)) for x, y in loops[0]]) | |
| boundary = [[x, y] for x, y in ring] | |
| area = round(abs(signed_area(ring)), 6) | |
| boundary_type = "polygon" | |
| else: | |
| # Not reached on the 48 released scenes; every one closes into a single | |
| # loop. A future release that does not gets null, not a hull. | |
| boundary, area, boundary_type = None, None, None | |
| counters["scenes_without_single_loop"] += 1 | |
| # The source's own room height: layout_utils.py averages the two rings and | |
| # subtracts. Per-segment z is kept in source_fields, so the spread stays | |
| # visible even though only the mean is published. | |
| floor_z = [s[end]["z"] for s in layout["floor"] for end in ("start", "end")] | |
| ceil_z = [s[end]["z"] for s in layout["ceil"] for end in ("start", "end")] | |
| height = round((sum(ceil_z) / len(ceil_z) - sum(floor_z) / len(floor_z)) * MILLIMETRE, 6) | |
| room = { | |
| "room_id": f"{prefixed}::room_0", | |
| "room_index": 0, | |
| "room_type": ROOM_TYPES.get(scene_id), | |
| "room_type_source": (INFERRED if scene_id in ROOM_TYPE_INFERRED | |
| else EXPLICIT_KEYWORD), | |
| "room_boundary": boundary, | |
| "room_boundary_type": boundary_type, | |
| "room_area_m2": area, | |
| "room_height": height, | |
| "coordinate_system": COORDINATE_SYSTEM, | |
| "doors": openings["doors"], | |
| "windows": openings["windows"], | |
| "furniture_quantity": len(furniture), | |
| "furniture": furniture, | |
| "source_fields": { | |
| "room_uid": layout.get("room_uid"), | |
| # Consumed into room_boundary and room_height, but lossily: the | |
| # segment pairing and the per-segment z do not survive either. | |
| "floor": layout["floor"], | |
| "ceil": layout["ceil"], | |
| }, | |
| } | |
| counters["room_type_null"] += room["room_type"] is None | |
| counters["room_type_inferred"] += scene_id in ROOM_TYPE_INFERRED | |
| return { | |
| "scene_id": prefixed, | |
| "sample_id": prefixed, | |
| "dataset": DATASET, | |
| "source_dataset": DATASET, | |
| "source_subset": SPLIT, | |
| "room_count": 1, | |
| "total_area": area, | |
| "building_style": None, | |
| "description": caption, | |
| # Every published export writes null here, and the one that does not | |
| # (M3DLayout) writes the parsed source description object, not a path. | |
| # The caption itself is already published verbatim in `description`. | |
| "description_source": None, | |
| "provenance": { | |
| "source_file": f"data/{scene_id}/room_layout.json", | |
| "split": SPLIT, | |
| "license_tag": LICENSE_TAG, | |
| }, | |
| "rooms": [room], | |
| } | |
| def main(): | |
| here = Path(__file__).resolve().parent.parent | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--data-root", type=Path, default=here / "data") | |
| ap.add_argument("--out", type=Path, default=here / "spatialgen.jsonl") | |
| ap.add_argument("--limit", type=int, help="stop after N scenes -- use before any full run") | |
| args = ap.parse_args() | |
| captions = {} | |
| with open(args.data_root / "test_split_caption.jsonl", encoding="utf-8") as handle: | |
| for line in handle: | |
| if line.strip(): | |
| captions.update(json.loads(line)) | |
| split_file = args.data_root / "test_split.txt" | |
| scenes = [line.strip() for line in split_file.read_text().splitlines() if line.strip()] | |
| if args.limit: | |
| scenes = scenes[:args.limit] | |
| counters = collections.Counter() | |
| written = 0 | |
| tmp = args.out.with_suffix(args.out.suffix + ".part") | |
| with open(tmp, "w", encoding="utf-8") as out: | |
| for scene_id in scenes: | |
| path = args.data_root / scene_id / "room_layout.json" | |
| if not path.exists(): | |
| counters["scenes_missing_layout"] += 1 | |
| continue | |
| layout = json.loads(path.read_text(encoding="utf-8")) | |
| caption = captions.get(scene_id) | |
| counters["captions_missing"] += caption is None | |
| record = convert_scene(scene_id, layout, caption, counters) | |
| out.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| written += 1 | |
| tmp.replace(args.out) | |
| counters["scenes_written"] = written | |
| print(json.dumps(dict(sorted(counters.items())), indent=2)) | |
| if __name__ == "__main__": | |
| main() | |