Spaces:
Running
Running
Download tools/build_catalog.py from projectsim/simready-library: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/spaces/projectsim/simready-library/resolve/main/tools/build_catalog.py
- Command line
-
hf download hf://spaces/projectsim/simready-library/tools/build_catalog.py
-
curl -L -o build_catalog.py https://huggingface.co/spaces/projectsim/simready-library/resolve/main/tools/build_catalog.py
15.1 kB
| # /// script | |
| # requires-python = ">=3.10" | |
| # dependencies = ["usd-core"] | |
| # /// | |
| """Build data/catalog.json for the projectsim SimReady Library Space. | |
| Source: the public Hugging Face dataset projectsim/simready-assets (read only), one | |
| SimReady package per top-level folder. Per asset we read com.nvidia.simready.packaging.json | |
| (package id and version) and the root layer of simready_usd/<asset>.usd (SimReady_Metadata, | |
| semantic class, joints). Assets with a file in previews/ (tools/make_previews.py) get the | |
| 3D viewer. | |
| Root USD files are 1-35 MB, so their metadata is cached in tools/meta_cache.json, keyed | |
| by package id. A rebuild only downloads packages that are new or have a new version. | |
| Run from the Space folder: HF_TOKEN=$(hf auth token) uv run tools/build_catalog.py | |
| Previews first (optional): uv run tools/make_previews.py | |
| Then upload: hf upload projectsim/simready-library . --repo-type space | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import tempfile | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| from concurrent.futures import ThreadPoolExecutor | |
| from datetime import datetime, timezone | |
| from pxr import Sdf | |
| HF = "https://huggingface.co" | |
| def urlopen(url, tries=6): | |
| """GET with HF_TOKEN when set (higher rate limits) and backoff when HF throttles (429/499/5xx).""" | |
| headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.environ.get("HF_TOKEN") else {} | |
| for attempt in range(tries): | |
| try: | |
| return urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=120) | |
| except urllib.error.HTTPError as e: | |
| if e.code not in (429, 499, 500, 502, 503, 504) or attempt == tries - 1: | |
| raise | |
| time.sleep(2 ** attempt) | |
| def get_json(url): | |
| with urlopen(url) as r: | |
| return json.load(r) | |
| def list_files(dataset): | |
| """Every file in the dataset at main, plus the main commit sha.""" | |
| sha = get_json(f"{HF}/api/datasets/{dataset}")["sha"] | |
| url, files = f"{HF}/api/datasets/{dataset}/tree/{sha}?recursive=true&limit=1000", [] | |
| while url: | |
| with urlopen(url) as r: | |
| files += [x for x in json.load(r) if x["type"] == "file"] | |
| m = re.search(r'<([^>]+)>;\s*rel="next"', r.headers.get("Link") or "") | |
| url = m.group(1) if m else None | |
| return sha, files | |
| def read_root_layer(path): | |
| """SimReady metadata, semantic class and joints from the asset's root layer.""" | |
| layer = Sdf.Layer.FindOrOpen(path) | |
| meta = dict(layer.customLayerData.get("SimReady_Metadata", {})) | |
| prim = layer.GetPrimAtPath("/" + layer.defaultPrim) | |
| def label(attr): | |
| spec = prim.attributes.get(attr) if prim else None | |
| value = list(spec.default or []) if spec else [] | |
| return value[0] if value else None | |
| joints, mounted = [], False | |
| def visit(p): | |
| nonlocal mounted | |
| spec = layer.GetObjectAtPath(p) | |
| if not isinstance(spec, Sdf.PrimSpec) or not spec.typeName.startswith("Physics") or "Joint" not in spec.typeName: | |
| return | |
| bodies = [list(spec.relationships[r].targetPathList.GetAddedOrExplicitItems()) if r in spec.relationships else [] | |
| for r in ("physics:body0", "physics:body1")] | |
| if spec.typeName == "PhysicsFixedJoint": | |
| mounted = mounted or not bodies[0] or not bodies[1] | |
| return | |
| kind = {"PhysicsRevoluteJoint": "hinge", "PhysicsPrismaticJoint": "slider"}.get(spec.typeName, "joint") | |
| lim = [spec.attributes[a].default if a in spec.attributes else None | |
| for a in ("physics:lowerLimit", "physics:upperLimit")] | |
| joints.append({"name": spec.name, "type": kind, "lower": lim[0], "upper": lim[1]}) | |
| layer.Traverse(Sdf.Path.absoluteRootPath, visit) | |
| extents = [float(x) for x in re.findall(r"[-\d.eE+]+", str(meta.get("asset_extents", "")))][:3] | |
| return { | |
| "category": meta.get("category"), | |
| "qcode": meta.get("qcode") or label("semantics:labels:wikidata_qcode"), | |
| "class": label("semantics:labels:class"), | |
| "mass": meta.get("mass"), | |
| "rigid_bodies": meta.get("rigid_body_count"), | |
| "extents": extents or None, | |
| "license": meta.get("asset_license"), | |
| "date": meta.get("usd_date_generated"), | |
| "joints": sorted(joints, key=lambda j: j["name"]), | |
| "mounted": mounted, | |
| "materials": material_variants(prim), | |
| } | |
| def material_variants(prim): | |
| """The "Material" variant set on the default prim, if the asset has one (the fasteners do). | |
| Each choice sets the mass and adds a reference from one Material prim (the "look") to a | |
| file in materials/. The values in those files (colour, density, friction) are read later | |
| by read_material(). Returns None when there is no such variant set.""" | |
| vset = prim.variantSets.get("Material") if prim else None | |
| if vset is None: | |
| return None | |
| options, look = [], None | |
| for name in sorted(vset.variants.keys()): | |
| spec = vset.variants[name].primSpec | |
| mass = round(spec.attributes["physics:mass"].default, 7) if "physics:mass" in spec.attributes else None | |
| ref = None | |
| todo = [spec] | |
| while todo and ref is None: | |
| s = todo.pop() | |
| for item in s.referenceList.GetAddedOrExplicitItems(): | |
| if "/materials/" in item.assetPath: | |
| ref, look = item.assetPath, s.name | |
| todo.extend(s.nameChildren) | |
| options.append({"id": name, "mass": mass, "ref": ref}) | |
| return {"default": prim.variantSelections.get("Material"), "look": look, "options": options} | |
| def read_material(path): | |
| """Preview colour (linear RGB), metallic, roughness and physics values of a materials/*.usda file.""" | |
| layer = Sdf.Layer.FindOrOpen(path) | |
| mat = layer.GetPrimAtPath("/" + layer.defaultPrim) | |
| def value(spec, name): | |
| a = spec.attributes.get(name) if spec else None | |
| v = a.default if a else None | |
| return round(float(v), 4) if isinstance(v, float) else v | |
| preview = next((c for c in mat.nameChildren if value(c, "info:id") == "UsdPreviewSurface"), None) | |
| color = value(preview, "inputs:diffuseColor") | |
| return { | |
| "color": [round(float(c), 4) for c in color] if color is not None else None, | |
| "metallic": value(preview, "inputs:metallic"), | |
| "roughness": value(preview, "inputs:roughness"), | |
| "density": value(mat, "physics:density"), | |
| "static_friction": value(mat, "physics:staticFriction"), | |
| "dynamic_friction": value(mat, "physics:dynamicFriction"), | |
| "restitution": value(mat, "physics:restitution"), | |
| } | |
| def fetch_asset(dataset, sha, asset, root_path): | |
| base = f"{HF}/datasets/{dataset}/resolve/{sha}/{asset}" | |
| with tempfile.TemporaryDirectory() as tmp: | |
| local = os.path.join(tmp, f"{asset}.usd") | |
| with urlopen(f"{base}/{root_path}") as r, open(local, "wb") as f: | |
| while chunk := r.read(1 << 20): | |
| f.write(chunk) | |
| meta = read_root_layer(local) | |
| for opt in (meta["materials"] or {}).get("options", []): | |
| ref = opt.pop("ref") | |
| if not ref: | |
| continue | |
| rel = os.path.normpath(os.path.join(os.path.dirname(root_path), ref)) | |
| mat = os.path.join(tmp, os.path.basename(rel)) | |
| with urlopen(f"{base}/{rel}") as r, open(mat, "wb") as f: | |
| f.write(r.read()) | |
| opt.update(read_material(mat)) | |
| return meta | |
| def scene_records(previews): | |
| """Scenes from tools/scenes.json (gated dataset projectsim/scenes-and-worlds).""" | |
| path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scenes.json") | |
| if not os.path.exists(path): | |
| return [] | |
| cfg = json.load(open(path)) | |
| return [{ | |
| "id": s["id"], "name": s["name"], "kind": "scene", "group": "Scenes", "category": "indoor rooms", | |
| "class": "indoor scene", "qcode": None, "mass": None, "extents": s["extents"], "rigid_bodies": None, | |
| "joints": [], "mounted": False, "license": "CC-BY-4.0", "date": None, "version": None, "glass": False, | |
| "scene": s["scene"], "scene_dataset": cfg["dataset"], "objects": s["objects"], "triangles": s["triangles"], | |
| "splat": s["splat"], "room": s.get("room", True), "summary": s["summary"], | |
| "preview": os.path.exists(os.path.join(previews, "scenes", f"{s['scene']}.glb")), | |
| "thumb": os.path.exists(os.path.join(previews, "thumbs", f"{s['id']}.webp")), | |
| } for s in cfg["scenes"]] | |
| FASTENER_STANDARDS = {"iso4017": "ISO 4017", "iso4032": "ISO 4032", "din125a": "DIN 125-A", "iso7089": "ISO 7089"} | |
| def display_name(asset): | |
| """Card title: the folder name in words ("folding_scooter" -> "Folding scooter"), except | |
| fasteners, whose ids encode a standard and a size: | |
| bolt_iso4017_m10x1p5_l30 -> "Hex bolt ISO 4017 M10×1.5, 30 mm", nut_iso4032_m10x1p5 -> | |
| "Hex nut ISO 4032 M10×1.5", washer_din125a_m14 -> "Washer DIN 125-A M14".""" | |
| m = re.fullmatch(r"(bolt|nut)_(iso4017|iso4032)_m(\d+)x(\d+(?:p\d+)?)(?:_l(\d+))?", asset) | |
| if m: | |
| kind, std, size, pitch, length = m.groups() | |
| name = f"Hex {kind} {FASTENER_STANDARDS[std]} M{size}×{pitch.replace('p', '.')}" | |
| return f"{name}, {length} mm" if length else name | |
| m = re.fullmatch(r"washer_(din125a|iso7089)_m(\d+)", asset) | |
| if m: | |
| return f"Washer {FASTENER_STANDARDS[m.group(1)]} M{m.group(2)}" | |
| return asset.replace("_", " ").capitalize() | |
| def hidden_assets(): | |
| """Packages listed in tools/hidden.json are left out of the Library.""" | |
| path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hidden.json") | |
| return set(json.load(open(path))["assets"]) if os.path.exists(path) else set() | |
| def thumbs_rev(previews): | |
| """Newest thumbnail time (dark or light), so browsers refetch after a re-render.""" | |
| times = [os.path.getmtime(os.path.join(previews, d, f)) for d in ("thumbs", "thumbs-light") | |
| if os.path.isdir(os.path.join(previews, d)) for f in os.listdir(os.path.join(previews, d))] | |
| return str(int(max(times))) if times else "" | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--dataset", default="projectsim/simready-assets") | |
| ap.add_argument("--out", default="data/catalog.json") | |
| ap.add_argument("--cache", default="tools/meta_cache.json") | |
| ap.add_argument("--groups", default="tools/groups.json") | |
| ap.add_argument("--previews", default="previews") | |
| ap.add_argument("--workers", type=int, default=4) | |
| args = ap.parse_args() | |
| groups = json.load(open(args.groups)) | |
| cache = json.load(open(args.cache)) if os.path.exists(args.cache) else {} | |
| sha, files = list_files(args.dataset) | |
| by_asset, sizes = {}, {} | |
| for f in files: | |
| if "/" in f["path"]: | |
| top = f["path"].split("/")[0] | |
| by_asset.setdefault(top, []).append(f["path"]) | |
| if "/.metadata/" not in f["path"]: # the Download zip leaves out the reports | |
| sizes[top] = sizes.get(top, 0) + (f.get("size") or 0) | |
| assets, todo, hidden = {}, [], hidden_assets() | |
| for asset, paths in sorted(by_asset.items()): | |
| if asset in hidden: | |
| continue | |
| root = f"simready_usd/{asset}.usd" | |
| if f"{asset}/{root}" not in paths or f"{asset}/com.nvidia.simready.packaging.json" not in paths: | |
| print(f"skip {asset}: not a SimReady package", file=sys.stderr) | |
| continue | |
| assets[asset] = {"root": root, "paths": paths} | |
| def package_id(asset): | |
| return get_json(f"{HF}/datasets/{args.dataset}/resolve/{sha}/{asset}/com.nvidia.simready.packaging.json")["package_id"] | |
| with ThreadPoolExecutor(args.workers) as pool: | |
| ids = dict(zip(assets, pool.map(package_id, assets))) | |
| # also re-read cached packages from before the "materials" field if they ship .usda materials | |
| todo = [a for a in assets if ids[a] not in cache or ("materials" not in cache[ids[a]] and any( | |
| "/simready_usd/materials/" in p and p.endswith(".usda") for p in assets[a]["paths"]))] | |
| print(f"{len(assets)} packages, {len(todo)} new or changed", file=sys.stderr) | |
| def load(a): | |
| return a, fetch_asset(args.dataset, sha, a, assets[a]["root"]) | |
| for i, (a, meta) in enumerate(pool.map(load, todo), 1): | |
| cache[ids[a]] = meta | |
| if i % 25 == 0 or i == len(todo): | |
| print(f" read {i}/{len(todo)}", file=sys.stderr) | |
| json.dump(cache, open(args.cache, "w"), indent=0, sort_keys=True) | |
| unmapped, records = set(), [] | |
| for a in sorted(assets): | |
| m = cache[ids[a]] | |
| raw = (m["category"] or "").strip().lower() | |
| category = groups.get("aliases", {}).get(raw, raw) | |
| group = groups["categories"].get(category) | |
| if group is None: | |
| unmapped.add(m["category"]) | |
| group = "Other" | |
| paths = assets[a]["paths"] | |
| records.append({ | |
| "id": a, | |
| "name": display_name(a), | |
| "group": group, | |
| "category": category, | |
| "class": m["class"], | |
| "qcode": m["qcode"], | |
| "mass": m["mass"], | |
| "extents": m["extents"], | |
| "rigid_bodies": m["rigid_bodies"], | |
| "joints": m["joints"], | |
| "mounted": m["mounted"], | |
| "license": m["license"], | |
| "date": m["date"], | |
| "version": ids[a].split(f".{a}.", 1)[-1], | |
| "preview": os.path.exists(os.path.join(args.previews, f"{a}.glb")), | |
| "thumb": os.path.exists(os.path.join(args.previews, "thumbs", f"{a}.webp")), | |
| "thumb_light": os.path.exists(os.path.join(args.previews, "thumbs-light", f"{a}.webp")), | |
| "glass": any("/simready_usd/materials/" in p and p.endswith(".mdl") for p in paths), # MDL shaders, not plain .usda materials | |
| "size": sizes.get(a, 0), # bytes in the package folder (the Download zip) | |
| "materials": m.get("materials"), # the Material variant set, if any (see material_variants) | |
| }) | |
| records += scene_records(args.previews) | |
| out = { | |
| "dataset": args.dataset, | |
| "commit": sha, | |
| "built": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), | |
| "groups": groups["order"], | |
| # changes whenever any thumbnail is re-rendered, so browsers fetch the new images | |
| "thumbs_rev": thumbs_rev(args.previews), | |
| "assets": records, | |
| } | |
| os.makedirs(os.path.dirname(args.out), exist_ok=True) | |
| json.dump(out, open(args.out, "w"), separators=(",", ":")) | |
| json.dump(cache, open(args.cache, "w"), indent=0, sort_keys=True) | |
| print(f"wrote {args.out}: {len(records)} assets, {sum(r['preview'] for r in records)} with a 3D preview", file=sys.stderr) | |
| if hidden: | |
| print(f"left out (tools/hidden.json): {sorted(hidden)}", file=sys.stderr) | |
| if unmapped: | |
| print(f"warning: add these categories to {args.groups}: {sorted(unmapped)}", file=sys.stderr) | |
| if __name__ == "__main__": | |
| main() | |