#!/usr/bin/env python3 """List the USD models actually reachable from the scene configs. Seeds from every ``usd_path`` in ``assets/scenes/*.json``, then follows the references *inside* those USD files transitively, because a scene rarely names more than a wrapper. ``model_dishwasher_v2.usd`` is a typical case: the scene points at the wrapper, while the articulation links live in a companion folder the scene never mentions. Deleting on the scene list alone strips those and the model stops loading. Reference following, no third-party libraries: * ``.usda`` (and any USD saved as text) is parsed for ``@asset/path@``. * ``.usdc`` is binary with a compressed token table, so its strings are mined and kept only when they resolve to a file that exists — a heuristic. * A file ``X.usd`` sitting next to a folder ``X/`` pulls in that whole folder. This is the packaging convention used throughout these assets and it is what catches what the binary scan cannot. Because the binary side is heuristic, this errs toward keeping files. Usage: python scripts/usd_cleaner/usd_models_cleaner.py # -> used_usds.json python scripts/usd_cleaner/usd_models_cleaner.py --unused # -> unused_usds.json """ from __future__ import annotations import argparse import json import re from pathlib import Path SCRIPT_DIR = Path(__file__).resolve().parent REPO_ROOT = SCRIPT_DIR.parent.parent KEY = "usd_path" USD_SUFFIXES = {".usd", ".usda", ".usdc", ".usdz"} # @path@ and the @@@path@@@ form used when a path contains an @. ASSET_REF = re.compile(r"@@@(.+?)@@@|@([^@\n]+)@") PRINTABLE = re.compile(rb"[ -~]{4,}") # A mined string is only a candidate if it looks like a file name. LOOKS_LIKE_PATH = re.compile(r"[\w./\\-]+\.\w{1,6}$") # Set False via --aggressive: see the sibling-directory rule in expand(). PROTECT_SIBLING_DIRS = True def iter_values(node, key: str): """Yield every value stored under ``key``, at any depth.""" if isinstance(node, dict): for name, value in node.items(): if name == key and isinstance(value, str): yield value else: yield from iter_values(value, key) elif isinstance(node, list): for item in node: yield from iter_values(item, key) def scene_seeds(scenes_dir: Path) -> dict: """Map each scene-declared usd_path to the scene files declaring it.""" refs: dict = {} for scene_file in sorted(scenes_dir.glob("*.json")): try: data = json.loads(scene_file.read_text()) except (OSError, json.JSONDecodeError) as exc: print(f"# WARNING: skipping {scene_file.name}: {exc}") continue for value in iter_values(data, KEY): refs.setdefault(value, set()).add(scene_file.name) return refs def candidates(raw: str, origin: Path): """Resolve a raw reference string against the file that contained it.""" raw = raw.strip().strip("'\"") # usdc strings often carry a leading marker, and a target prim is appended # to a reference as path.usd. raw = raw.lstrip("#").split(" X/** companion = path.parent / path.stem if companion.is_dir(): found.update(f.resolve() for f in companion.rglob("*") if f.is_file()) # A binary USD hides its references, so a reachable one also protects the # asset directories sitting beside it (kitchen_background.usd next to # localized/). Sibling *files* stay deletable; only sub-trees are kept. if not is_text and PROTECT_SIBLING_DIRS: for sibling in path.parent.iterdir(): if sibling.is_dir() and not sibling.name.startswith("."): found.update(f.resolve() for f in sibling.rglob("*") if f.is_file()) return found def closure(seeds: set, models_dir: Path) -> set: """Transitively expand ``seeds`` through USD references and companions.""" reached, frontier = set(), list(seeds) while frontier: current = frontier.pop() if current in reached or not current.is_file(): continue reached.add(current) for nxt in expand(current, models_dir): if nxt not in reached: frontier.append(nxt) return reached def write_json(paths: list, out: str) -> None: out_path = Path(out) if not out_path.is_absolute(): out_path = ( SCRIPT_DIR / out_path if out_path.parent == Path(".") else REPO_ROOT / out_path ) out_path.write_text(json.dumps(paths, indent=2) + "\n") print(f"# wrote {len(paths)} paths to {out_path}") def main() -> None: parser = argparse.ArgumentParser( description="List the USD models reachable from the scene configs" ) parser.add_argument("--scenes_dir", default="assets/scenes") parser.add_argument("--models_dir", default="assets/usd_models") parser.add_argument( "--unused", action="store_true", help="Invert: list USD files nothing reaches (the delete list)", ) parser.add_argument( "--no_follow", action="store_true", help="Scene JSONs only, do not follow references (UNSAFE, for comparison)", ) parser.add_argument( "--aggressive", action="store_true", help="Do not protect directories beside a reachable binary USD (riskier)", ) parser.add_argument("--verbose", action="store_true") parser.add_argument("--out", metavar="PATH") parser.add_argument("--no_out", action="store_true") args = parser.parse_args() global PROTECT_SIBLING_DIRS PROTECT_SIBLING_DIRS = not args.aggressive scenes_dir = REPO_ROOT / args.scenes_dir models_dir = (REPO_ROOT / args.models_dir).resolve() if not scenes_dir.is_dir(): raise SystemExit(f"Scenes directory not found: {scenes_dir}") if not models_dir.is_dir(): raise SystemExit(f"Models directory not found: {models_dir}") declared = scene_seeds(scenes_dir) seeds = set() for value in declared: path = Path(value) path = path if path.is_absolute() else REPO_ROOT / path if path.is_file(): seeds.add(path.resolve()) else: print(f"# WARNING: scene references a missing file: {value}") reached = seeds if args.no_follow else closure(seeds, models_dir) reached_usd = sorted( p for p in reached if p.suffix.lower() in USD_SUFFIXES ) if not args.unused: for path in reached_usd: rel = path.relative_to(REPO_ROOT) if args.verbose: scenes = declared.get(str(rel), set()) tag = ", ".join(sorted(scenes)) if scenes else "via reference" print(f"{rel} # {tag}") else: print(rel) print( f"\n# {len(seeds)} scene-declared -> {len(reached_usd)} USD files reachable " f"({len(reached)} files total incl. textures)" ) if not args.no_out: write_json([str(p.relative_to(REPO_ROOT)) for p in reached_usd], args.out or "used_usds.json") return unused = [ f for f in sorted(models_dir.rglob("*")) if f.is_file() and f.suffix.lower() in USD_SUFFIXES and f.resolve() not in reached ] rel = [str(f.relative_to(REPO_ROOT)) for f in unused] for path in rel: print(path) print( f"\n# {len(rel)} unreachable USD files under {models_dir.relative_to(REPO_ROOT)} " f"({len(reached_usd)} reachable, kept)" ) if not args.no_out: write_json(rel, args.out or "unused_usds.json") if __name__ == "__main__": main()