Spaces:
Running
Running
Download tools/make_previews.py from projectsim/simready-library: direct link, hf CLI and curl.
- Browser
- Download file 8.83 kB
-
https://huggingface.co/spaces/projectsim/simready-library/resolve/main/tools/make_previews.py
- Command line
-
hf download hf://spaces/projectsim/simready-library/tools/make_previews.py
-
curl -L -o make_previews.py https://huggingface.co/spaces/projectsim/simready-library/resolve/main/tools/make_previews.py
8.83 kB
| # /// script | |
| # requires-python = ">=3.10" | |
| # dependencies = ["usd-core"] | |
| # /// | |
| """Make the 3D previews the Space's viewer loads: previews/<asset>.glb + previews/<asset>.json. | |
| For each package in projectsim/simready-assets (read-only; nothing is written to the | |
| dataset) this downloads simready_usd/ (without thumbnails) to a temporary folder, converts | |
| the USD to a small Draco GLB with Blender (tools/blender_glb.py), and writes the rig: one | |
| entry per hinge or slider joint with its parent and child part, pivot, axis and range, | |
| in the GLB's Y-up metres. Parts are matched to GLB nodes by USD prim name. | |
| Previews are cached in tools/preview_cache.json by package id, so a rerun only converts | |
| new or changed packages. | |
| Run from the Space folder: HF_TOKEN=$(hf auth token) uv run tools/make_previews.py [asset ...] | |
| (the token only raises Hugging Face's download rate limit; nothing is uploaded) | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import struct | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import urllib.error | |
| import urllib.parse | |
| import urllib.request | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pxr import Gf, Usd, UsdGeom, UsdPhysics | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from build_catalog import HF, get_json, hidden_assets, list_files # noqa: E402 | |
| BLENDER = "/Applications/Blender.app/Contents/MacOS/Blender" | |
| AXES = {"X": Gf.Vec3d(1, 0, 0), "Y": Gf.Vec3d(0, 1, 0), "Z": Gf.Vec3d(0, 0, 1)} | |
| def rig(usd_path): | |
| """Hinge and slider joints with pivot and axis in GLB space (Y-up metres).""" | |
| stage = Usd.Stage.Open(usd_path) | |
| mpu = UsdGeom.GetStageMetersPerUnit(stage) or 1.0 | |
| zup = UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z | |
| to_gltf = (lambda v: [v[0], v[2], -v[1]]) if zup else (lambda v: [v[0], v[1], v[2]]) | |
| cache = UsdGeom.XformCache() | |
| joints = [] | |
| for prim in stage.Traverse(Usd.TraverseInstanceProxies()): | |
| if prim.IsA(UsdPhysics.RevoluteJoint): | |
| kind, typed = "hinge", UsdPhysics.RevoluteJoint(prim) | |
| elif prim.IsA(UsdPhysics.PrismaticJoint): | |
| kind, typed = "slider", UsdPhysics.PrismaticJoint(prim) | |
| else: | |
| continue | |
| j = UsdPhysics.Joint(prim) | |
| b0 = j.GetBody0Rel().GetTargets() | |
| b1 = j.GetBody1Rel().GetTargets() | |
| if not b1: | |
| continue | |
| world0 = cache.GetLocalToWorldTransform(stage.GetPrimAtPath(b0[0])) if b0 else Gf.Matrix4d(1) | |
| pos = Gf.Vec3d(j.GetLocalPos0Attr().Get() or Gf.Vec3f(0)) | |
| rot = j.GetLocalRot0Attr().Get() or Gf.Quatf(1) | |
| axis_local = Gf.Rotation(Gf.Quatd(rot)).TransformDir(AXES.get(typed.GetAxisAttr().Get(), AXES["X"])) | |
| pivot = world0.Transform(pos) * mpu | |
| axis = world0.TransformDir(axis_local).GetNormalized() | |
| lo, hi = typed.GetLowerLimitAttr().Get(), typed.GetUpperLimitAttr().Get() | |
| limited = lo is not None and hi is not None and abs(hi - lo) < 1e6 | |
| scale = 1.0 if kind == "hinge" else mpu | |
| joints.append({ | |
| "name": prim.GetName(), "type": kind, | |
| "parent": b0[0].name if b0 else None, "child": b1[0].name, | |
| "pivot": [round(x, 6) for x in to_gltf(pivot)], | |
| "axis": [round(x, 6) for x in to_gltf(axis)], | |
| "lower": round(lo * scale, 6) if limited else None, | |
| "upper": round(hi * scale, 6) if limited else None, | |
| }) | |
| # parents before children, so the viewer can chain joints in one pass | |
| order, placed = [], set() | |
| while len(order) < len(joints): | |
| before = len(order) | |
| for jt in joints: | |
| if jt["name"] not in placed and (jt["parent"] is None or jt["parent"] not in {k["child"] for k in joints if k["name"] not in placed}): | |
| order.append(jt); placed.add(jt["name"]) | |
| if len(order) == before: # a loop: keep the rest as they are | |
| order += [jt for jt in joints if jt["name"] not in placed] | |
| break | |
| return order | |
| def download(url, dest, tries=6): | |
| """GET with an optional HF_TOKEN (higher rate limits) and backoff on 429/5xx.""" | |
| headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.environ.get("HF_TOKEN") else {} | |
| for attempt in range(tries): | |
| try: | |
| with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=300) as r, open(dest, "wb") as f: | |
| while chunk := r.read(1 << 20): | |
| f.write(chunk) | |
| return | |
| except urllib.error.HTTPError as e: | |
| if e.code not in (429, 500, 502, 503, 504) or attempt == tries - 1: | |
| raise | |
| wait = int(e.headers.get("Retry-After") or 0) or 15 * (attempt + 1) | |
| time.sleep(min(wait, 300)) | |
| def glb_node_names(path): | |
| data = open(path, "rb").read() | |
| n = struct.unpack_from("<I", data, 12)[0] | |
| return {node.get("name") for node in json.loads(data[20:20 + n]).get("nodes", [])} | |
| def make_one(dataset, sha, asset, paths, out_dir, blender, max_px): | |
| with tempfile.TemporaryDirectory() as tmp: | |
| for p in paths: | |
| if "/simready_usd/" not in p or "/.thumbs/" in p: | |
| continue | |
| dest = os.path.join(tmp, p) | |
| os.makedirs(os.path.dirname(dest), exist_ok=True) | |
| download(f"{HF}/datasets/{dataset}/resolve/{sha}/{urllib.parse.quote(p)}", dest) | |
| usd = os.path.join(tmp, asset, "simready_usd", f"{asset}.usd") | |
| glb = os.path.join(out_dir, f"{asset}.glb") | |
| run = subprocess.run([blender, "-b", "--factory-startup", "--python", | |
| os.path.join(os.path.dirname(os.path.abspath(__file__)), "blender_glb.py"), | |
| "--", usd, glb, str(max_px)], capture_output=True, text=True) | |
| if "PREVIEW_OK" not in run.stdout or not os.path.exists(glb): | |
| raise RuntimeError(f"Blender failed: {(run.stdout + run.stderr)[-600:]}") | |
| joints = rig(usd) | |
| names = glb_node_names(glb) | |
| missing = sorted({j["child"] for j in joints if j["child"] not in names}) | |
| json.dump({"joints": joints}, open(os.path.join(out_dir, f"{asset}.json"), "w"), separators=(",", ":")) | |
| return {"bytes": os.path.getsize(glb), "joints": len(joints), "missing_parts": missing} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("assets", nargs="*", help="only these assets (default: all that need a preview)") | |
| ap.add_argument("--dataset", default="projectsim/simready-assets") | |
| ap.add_argument("--out", default="previews") | |
| ap.add_argument("--cache", default="tools/preview_cache.json") | |
| ap.add_argument("--blender", default=BLENDER) | |
| ap.add_argument("--max-texture", type=int, default=1024) | |
| ap.add_argument("--workers", type=int, default=4) | |
| args = ap.parse_args() | |
| os.makedirs(args.out, exist_ok=True) | |
| cache = json.load(open(args.cache)) if os.path.exists(args.cache) else {} | |
| sha, files = list_files(args.dataset) | |
| by_asset = {} | |
| for f in files: | |
| if "/" in f["path"]: | |
| by_asset.setdefault(f["path"].split("/")[0], []).append(f["path"]) | |
| wanted = args.assets or sorted(set(by_asset) - hidden_assets()) | |
| def package_id(a): | |
| return get_json(f"{HF}/datasets/{args.dataset}/resolve/{sha}/{a}/com.nvidia.simready.packaging.json")["package_id"] | |
| with ThreadPoolExecutor(args.workers) as pool: | |
| ids = dict(zip(wanted, pool.map(package_id, wanted))) | |
| todo = [a for a in wanted if args.assets or ids[a] not in cache | |
| or not os.path.exists(os.path.join(args.out, f"{a}.glb"))] | |
| print(f"{len(wanted)} packages, {len(todo)} previews to make", file=sys.stderr) | |
| def work(a): | |
| try: | |
| return a, make_one(args.dataset, sha, a, by_asset[a], args.out, args.blender, args.max_texture), None | |
| except Exception as e: # keep going; report at the end | |
| return a, None, str(e) | |
| failed = {} | |
| for i, (a, info, err) in enumerate(pool.map(work, todo), 1): | |
| if err: | |
| failed[a] = err | |
| else: | |
| cache[ids[a]] = {"asset": a, **info} | |
| if info["missing_parts"]: | |
| print(f" {a}: parts not found in GLB: {info['missing_parts']}", file=sys.stderr) | |
| if i % 20 == 0 or i == len(todo): | |
| print(f" {i}/{len(todo)}", file=sys.stderr) | |
| json.dump(cache, open(args.cache, "w"), indent=0, sort_keys=True) | |
| total = sum(os.path.getsize(os.path.join(args.out, f)) for f in os.listdir(args.out) if f.endswith(".glb")) | |
| print(f"done: {len(todo) - len(failed)} made, {len(failed)} failed, previews total {total / 1e6:.0f} MB", file=sys.stderr) | |
| for a, e in failed.items(): | |
| print(f" FAILED {a}: {e[:300]}", file=sys.stderr) | |
| if __name__ == "__main__": | |
| main() | |