Spaces:
Running
Running
File size: 15,055 Bytes
cfea9b4 0aefd10 cfea9b4 7d7939d 0aefd10 cfea9b4 7d7939d cfea9b4 7d7939d cfea9b4 7d7939d cfea9b4 7d7939d cfea9b4 9f23d2d cfea9b4 7d7939d 9f23d2d cfea9b4 2d77bd6 9feba35 2d77bd6 267fde5 3522659 15fac9f 86f8e0b 15fac9f cfea9b4 0aefd10 7d7939d cfea9b4 5874da5 cfea9b4 5874da5 cfea9b4 3522659 cfea9b4 3522659 cfea9b4 9f23d2d cfea9b4 0aefd10 cfea9b4 267fde5 cfea9b4 0aefd10 4c90380 86f8e0b 267fde5 5874da5 9f23d2d cfea9b4 2d77bd6 cfea9b4 15fac9f cfea9b4 0aefd10 3522659 cfea9b4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | # /// 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()
|