File size: 9,963 Bytes
4c20479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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</Prim>.
    raw = raw.lstrip("#").split("</")[0].strip()
    if not raw or raw.startswith(("<", "/World")):
        return
    if raw.startswith("./") or raw.startswith("../") or not raw.startswith("/"):
        yield origin.parent / raw
    else:
        # An absolute-looking path is usually anchored at the repo, not at /.
        yield Path(raw)
        yield REPO_ROOT / raw.lstrip("/")


def refs_from_text(path: Path, data: bytes):
    try:
        text = data.decode("utf-8", "replace")
    except Exception:
        return
    for triple, single in ASSET_REF.findall(text):
        yield triple or single


def refs_from_binary(path: Path, data: bytes):
    """Mine printable strings; the caller keeps only those that exist on disk."""
    for chunk in PRINTABLE.findall(data):
        token = chunk.decode("ascii", "ignore")
        # A token blob may hold several concatenated names.
        for piece in re.split(r"[\x00\s,;]+", token):
            piece = piece.lstrip("#")
            if LOOKS_LIKE_PATH.match(piece):
                yield piece


_RESOLVED: dict = {}


def _accept(candidate: Path, models_dir: Path):
    """Resolve + existence check, memoised — the same names recur constantly."""
    key = str(candidate)
    if key not in _RESOLVED:
        try:
            resolved = candidate.resolve()
            ok = resolved.is_file() and resolved.is_relative_to(models_dir)
        except OSError:
            resolved, ok = None, False
        _RESOLVED[key] = resolved if ok else None
    return _RESOLVED[key]


def expand(path: Path, models_dir: Path):
    """Every file ``path`` pulls in: its references, plus its companion folder."""
    found = set()
    try:
        data = path.read_bytes()
    except OSError:
        return found

    is_text = data[:5] == b"#usda" or path.suffix.lower() == ".usda"
    raw_refs = refs_from_text(path, data) if is_text else refs_from_binary(path, data)

    # Dedupe first: a big usdc yields the same token thousands of times.
    for raw in set(raw_refs):
        for candidate in candidates(raw, path):
            # Text refs are authoritative; mined binary strings must exist.
            resolved = _accept(candidate, models_dir)
            if resolved is not None:
                found.add(resolved)

    # Companion folder: X.usd  ->  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()