Spaces:
Running

File size: 19,695 Bytes
1b9c262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env python3
"""Precompute the small artifacts behind the VoMP viewer Space.

Source: https://huggingface.co/datasets/nvidia/PhysicalAI-Robotics-PhysicalAssets-VoMP
(CC-BY-4.0, NVIDIA Corporation). The Dataset Viewer API is disabled for this
repo, so the viewer ships its own compact index. Outputs:

  data/index.json(.gz.b64)      objects, parts and per-part properties (+ voxel shares)
  data/rationale/<xx>.json.gzip VLM rationale text per part, sharded by id prefix
  thumbs/<id16>.webp       320 px preview of one Cycles render per object
  thumbs/<id16>_e.webp     same camera, voxels coloured by log10 Young's modulus
  assets/colormaps.js      colour LUTs shared by the previews and the browser

Renders, voxels and meshes are never copied: the browser streams them from the
dataset repo at the pinned revision below.

    python scripts/build_index.py --cache /tmp/vomp-cache --out .
"""

import argparse
import base64
import concurrent.futures as cf
import csv
import gzip
import json
import math
import os
import random
import re
import time
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np
import requests
from PIL import Image, ImageDraw

REPO = "nvidia/PhysicalAI-Robotics-PhysicalAssets-VoMP"
REV = "b400b022c04e49993d782aef8a47e325a8e8cc8a"
BASE = f"https://huggingface.co/datasets/{REPO}/resolve/{REV}"

DATASETS = [
    ("simready", "SimReady"),
    ("residential", "Residential"),
    ("commercial", "Commercial"),
    ("vegetation", "Vegetation"),
]
SPLITS = ["train", "val", "test"]

# log10 domains for E and rho; linear for nu.
DOMAINS = {"E": [4.0, 11.7], "nu": [0.0, 0.5], "rho": [1.0, 4.3]}

FAMILIES = [
    ("metal", "Metal", "#4263eb"),
    ("plastic", "Plastic", "#f08c00"),
    ("rubber", "Rubber / elastomer", "#c2255c"),
    ("foam", "Foam", "#f783ac"),
    ("wood", "Wood", "#9c5b2e"),
    ("paper", "Paper / cardboard", "#d4a373"),
    ("glass", "Glass", "#1098ad"),
    ("ceramic", "Ceramic / stone", "#7a828c"),
    ("fabric", "Fabric / leather", "#9c36b5"),
    ("organic", "Organic / plant / food", "#2f9e44"),
    ("other", "Liquid / gel / other", "#343a40"),
]
FAMILY_INDEX = {k: i for i, (k, _, _) in enumerate(FAMILIES)}

# Earliest keyword hit wins; ties go to the family listed first.
FAMILY_PATTERNS = [
    ("foam", r"\bfoam|sponge|expanded polystyrene|\beps\b|\bcushion"),
    ("rubber", r"rubber|elastomer|silicone|neoprene|\bepdm\b|\btpe\b|latex"),
    ("glass", r"\bglass(?!-fib| fib)|soda-lime|borosilicate"),
    ("metal", r"(?<!non)(?<!non-)metal|steel|alumin|\biron\b|brass|copper|bronze|zinc|chrom|titanium|tungsten|nickel|\btin\b|alloy|ferrous|pewter"),
    ("paper", r"paper|cardboard|fiberboard|fibreboard|carton|cellulose"),
    ("wood", r"(?<!box)(?<!dog)wood|plywood|\bmdf\b|particleboard|timber|\boak\b|\bpine\b|maple|walnut|birch|bamboo|veneer|\bcork\b|rattan|wicker|\bbark\b|lumber|teak|beech|cedar|spruce|\bfir\b|mahogany"),
    ("fabric", r"\bfabric(?!at)|textile|cotton|\bwool|upholster|leather|\bfelt\b|woven|linen|velvet|canvas|\bcords?\b|\bropes?\b|twine|knit|suede|yarn|polyester|\bnet\b"),
    ("ceramic", r"ceramic|porcelain|stoneware|earthenware|terracotta|\bstone|marble|granite|concrete|plaster|gypsum|\bclay|mineral|\bcement|\bslate|quartz|\brocks?\b|\bbricks?\b|basalt|sandstone|limestone"),
    ("plastic", r"plastic|polymer|\babs\b|hdpe|ldpe|polyethylene|polypropylene|\bpvc\b|acrylic|polycarbonate|nylon|polystyrene|\bpet\b|resin|vinyl|melamine|polyurethane|pmma|thermoset|epoxy|fiberglass|polyamide|acetal|\bpom\b"),
    ("organic", r"fruit|vegetable|\bfood|\bleaf|\bleaves|foliage|\bplants?\b|soil|growing medium|flesh|\bpeel|\brind|needles|grass|\bmoss|flower|petal|\bseeds?\b|bread|\bwax|\bbones?\b|\bstems?\b|potting|\bdirt\b|conifer|frond|botanical"),
    ("other", r"\bliquid|\bwater\b(?!-)|\bair-filled|\bair\b(?!-)|\bbubbles?\b|\bgel\b|gelatin|granular|\bsalt\b|confection"),
]
FAMILY_RES = [(k, re.compile(p, re.I)) for k, p in FAMILY_PATTERNS]
# Collapse "<modifier> foam/leaves" so the head noun decides (e.g. "polyurethane foam", "maple leaves").
HEAD_NOUN = re.compile(r"\b[\w-]+[\s-]+(foam|leaf|leaves|foliage|needles|flowers?|petals?|bracts?)\b", re.I)
SIMREADY_TYPES = {
    "metal": "metal", "plastic": "plastic", "wood": "wood", "cardboard": "paper",
    "leather": "fabric", "fabric": "fabric", "rubber": "rubber", "organic": "organic",
    "glass": "glass", "concrete": "ceramic", "stone": "ceramic",
}
NEGATION = re.compile(r"\b(rather than|instead of|not a|not an|not the|unlike|despite)\b[^.;:]*", re.I)

COLORMAPS = {"E": ("turbo", 0.04, 0.96), "nu": ("viridis", 0.0, 1.0), "rho": ("plasma", 0.0, 0.92)}


MIN_DENSITY = {"metal": 1500, "glass": 1500, "ceramic": 1200}


def _classify(analysis, mat_type, name, banned):
    def first_hit(text):
        text = NEGATION.sub(" ", text)
        text = re.sub(r"\bdoor leaf", "door panel", text, flags=re.I)
        text = HEAD_NOUN.sub(r"\1", text)
        best = None
        for rank, (fam, rx) in enumerate(FAMILY_RES):
            if fam in banned or fam == "other":
                continue
            m = rx.search(text)
            if m and (best is None or (m.start(), rank) < best[:2]):
                best = (m.start(), rank, fam)
        if best:
            return best[2]
        return "other" if FAMILY_RES[-1][1].search(text) else None

    for text in re.findall(r"Step\s*[13]:(.*)", analysis):
        fam = first_hit(text)
        if fam:
            return fam
    if SIMREADY_TYPES.get(mat_type) not in (None, *banned):
        return SIMREADY_TYPES[mat_type]
    return first_hit(f"{mat_type} {name}") or first_hit(analysis) or "other"


def classify_family(analysis, mat_type, name, rho=None):
    """Keyword heuristic over the VLM rationale; implausible densities trigger a retry."""
    banned = set()
    while True:
        fam = _classify(analysis, mat_type, name, banned)
        if rho is None or rho >= MIN_DENSITY.get(fam, 0) or len(banned) > 3:
            return fam
        banned.add(fam)


def make_luts():
    from matplotlib import colormaps

    luts = {}
    for key, (name, lo, hi) in COLORMAPS.items():
        cmap = colormaps[name]
        luts[key] = [
            "%02x%02x%02x" % tuple(int(round(c * 255)) for c in cmap(lo + (hi - lo) * i / 255)[:3])
            for i in range(256)
        ]
    return luts


def lut_colors(lut_hex, t):
    arr = np.array([[int(h[i:i + 2], 16) for i in (0, 2, 4)] for h in lut_hex], np.float32) / 255
    idx = np.clip(np.round(np.asarray(t) * 255), 0, 255).astype(int)
    return arr[idx]


def norm_e(E):
    lo, hi = DOMAINS["E"]
    return np.clip((np.log10(np.maximum(E, 1e-9)) - lo) / (hi - lo), 0, 1)


def rel_path(path, dataset):
    for marker in (f"/raw/{dataset}/", "/simready_content/"):
        if marker in path:
            return path.split(marker, 1)[1]
    return path


def sig(x, digits=4):
    if x is None:
        return None
    x = float(x)
    if x == 0 or not math.isfinite(x):
        return x
    return float(f"{x:.{digits}g}")


_session = None


def session():
    global _session
    if _session is None:
        _session = requests.Session()
        tok = os.environ.get("HF_TOKEN")
        if not tok:
            try:
                from huggingface_hub import get_token
                tok = get_token()
            except Exception:
                tok = None
        if tok:
            _session.headers["Authorization"] = f"Bearer {tok}"
    return _session


def fetch(path, dest):
    dest = Path(dest)
    if dest.exists() and dest.stat().st_size > 0:
        return dest
    dest.parent.mkdir(parents=True, exist_ok=True)
    for attempt in range(8):
        try:
            r = session().get(f"{BASE}/{path}", timeout=90)
            if r.status_code == 404:
                raise FileNotFoundError(path)
            if r.status_code in (429, 500, 502, 503, 504):
                raise IOError(f"HTTP {r.status_code}")
            r.raise_for_status()
            tmp = dest.with_name(dest.name + ".part")
            tmp.write_bytes(r.content)
            tmp.replace(dest)
            return dest
        except FileNotFoundError:
            raise
        except Exception:
            time.sleep(min(90, 2 ** attempt + random.random() * 2))
    raise RuntimeError(f"failed to fetch {path}")


def camera_project(P, T, f, cx):
    R, c = T[:3, :3], T[:3, 3]
    pc = (P - c) @ R
    z = -pc[..., 2]
    return cx + f * pc[..., 0] / z, cx - f * pc[..., 1] / z


def choose_view(frames, up, P, fx):
    Ts = np.array([fr["transform_matrix"] for fr in frames], float)
    C = Ts[:, :3, 3]
    d = C / np.linalg.norm(C, axis=1, keepdims=True)
    el = np.degrees(np.arcsin(np.clip(d @ up, -1, 1)))
    cand = np.where((el >= 15) & (el <= 40))[0]
    if len(cand) < 3:
        cand = np.where((el >= 5) & (el <= 55))[0]
    if len(cand) == 0:
        cand = np.arange(len(frames))
    res = 64
    sub = P[:: max(1, len(P) // 20000)]
    best, best_area = int(cand[0]), -1
    for i in cand:
        u, v = camera_project(sub, Ts[i], fx * res / 512, res / 2)
        ok = (u >= 0) & (u < res) & (v >= 0) & (v < res)
        area = len(np.unique(v[ok].astype(int) * res + u[ok].astype(int)))
        if area > best_area:
            best, best_area = int(i), area
    return best, Ts[best]


AXIS_UV = [(1, 2), (2, 0), (0, 1)]


def render_field(P, rgb, T, fx, size=512, ss=2, out=320):
    """Painter's-algorithm voxel render (exposed faces only) from a render camera."""
    R, c = T[:3, :3], T[:3, 3]
    W = size * ss
    f, cx = fx * ss, W / 2
    h = 0.5 / 64
    grid = np.clip(np.round((P + 0.5) * 64 - 0.5), 0, 63).astype(int)
    occ = np.zeros((64, 64, 64), bool)
    occ[grid[:, 0], grid[:, 1], grid[:, 2]] = True
    light = R @ np.array([-0.35, 0.8, 0.5])
    light /= np.linalg.norm(light)
    to_cam = c[None] - P
    quads, shades, keep = [], [], []
    for ax in range(3):
        s = np.where(to_cam[:, ax] >= 0, 1, -1)
        nb = grid.copy()
        nb[:, ax] += s
        inside = (nb[:, ax] >= 0) & (nb[:, ax] < 64)
        hidden = np.zeros(len(P), bool)
        hidden[inside] = occ[nb[inside, 0], nb[inside, 1], nb[inside, 2]]
        n = np.zeros((len(P), 3))
        n[:, ax] = s
        ua, va = AXIS_UV[ax]
        du = np.zeros(3)
        du[ua] = h
        dv = np.zeros(3)
        dv[va] = h
        ctr = P + n * h
        quads.append(np.stack([ctr - du - dv, ctr + du - dv, ctr + du + dv, ctr - du + dv], 1))
        shades.append(0.58 + 0.42 * np.clip(n @ light, 0, 1))
        keep.append(~hidden)
    quads = np.stack(quads, 1)
    shades = np.stack(shades, 1)
    keep = np.stack(keep, 1)
    u, v = camera_project(quads, T * 1.0, f, cx)
    depth = ((P - c) @ R)[:, 2]
    cols = (np.clip(rgb[:, None, :] * shades[..., None], 0, 1) * 255).astype(np.uint8)
    img = Image.new("RGBA", (W, W), (0, 0, 0, 0))
    dr = ImageDraw.Draw(img)
    for i in np.argsort(depth):
        for k in range(3):
            if keep[i, k]:
                dr.polygon(
                    [(u[i, k, j], v[i, k, j]) for j in range(4)],
                    fill=(int(cols[i, k, 0]), int(cols[i, k, 1]), int(cols[i, k, 2]), 255),
                )
    return img.resize((out, out), Image.LANCZOS)


def process_object(job):
    sha, cache, thumbs, lut_e = job
    cdir = Path(cache) / sha
    tr = json.loads(fetch(f"renders/{sha}/transforms.json", cdir / "transforms.json").read_text())
    z = np.load(fetch(f"voxels/{sha}_with_materials.npz", cdir / "mat.npz"))
    vd = z["voxel_data"]
    P = np.stack([vd["x"], vd["y"], vd["z"]], 1).astype(np.float64)
    seg = vd["segment_id"]
    keys, counts = np.unique(seg, return_counts=True)
    up = np.array([0.0, 0.0, 1.0]) if tr.get("stage_up_axis", "Z").upper() == "Z" else np.array([0.0, 1.0, 0.0])
    rot = (tr.get("normalization") or {}).get("rotation_matrix")
    if rot is not None:
        up = np.array(rot, float) @ up
    fx = tr["camera_intrinsics"]["pixels"][0][0]
    view, T = choose_view(tr["frames"], up, P, fx)
    png = fetch(f"renders/{sha}/{tr['frames'][view]['file_path']}", cdir / "view.png")
    stem = sha[:16]
    photo = Image.open(png).convert("RGBA").resize((320, 320), Image.LANCZOS)
    photo.save(Path(thumbs) / f"{stem}.webp", "WEBP", quality=80, method=6)
    rgb = lut_colors(lut_e, norm_e(vd["youngs_modulus"].astype(np.float64)))
    render_field(P, rgb, T, fx).save(Path(thumbs) / f"{stem}_e.webp", "WEBP", quality=80, method=6)
    return {
        "sha": sha,
        "up": tr.get("stage_up_axis", "Z").upper(),
        "tv": view,
        "cam": [round(float(x), 4) for x in T[:3, 3]],
        "seg_counts": {str(k): int(n) for k, n in zip(keys, counts)},
        "n_vox": int(len(vd)),
        "interior": int(z["interior_voxel_count"]) if "interior_voxel_count" in z.files else None,
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--cache", default="/tmp/vomp-cache")
    ap.add_argument("--out", default=".")
    ap.add_argument("--workers", type=int, default=12)
    ap.add_argument("--limit", type=int, default=0)
    args = ap.parse_args()
    cache, out = Path(args.cache), Path(args.out)
    (out / "data" / "rationale").mkdir(parents=True, exist_ok=True)
    (out / "thumbs").mkdir(parents=True, exist_ok=True)
    (out / "assets").mkdir(parents=True, exist_ok=True)

    meta_csv = fetch("metadata_with_vegetation_subset.csv", cache / "metadata_with_vegetation_subset.csv")
    ann_json = fetch("material_annotations.json", cache / "material_annotations.json")
    rows = list(csv.DictReader(open(meta_csv)))
    annotations = json.load(open(ann_json))

    base = [r for r in rows if not r["base_sha256"]]
    augs = defaultdict(list)
    for r in rows:
        if r["base_sha256"]:
            augs[r["base_sha256"]].append(r)
    ann_by_path = {}
    for a in annotations:
        ds = a["dataset_type"]
        ann_by_path[(ds, a["file_path"].split(f"datasets/raw/{ds}/", 1)[1])] = a

    luts = make_luts()
    (out / "assets" / "colormaps.js").write_text(
        "// Generated by scripts/build_index.py (matplotlib LUTs, 256 entries).\n"
        f"export const COLORMAPS = {json.dumps(luts, separators=(',', ':'))};\n"
        f"export const DOMAINS = {json.dumps(DOMAINS)};\n"
    )

    rendered = [r["sha256"] for r in base if r["dataset"] != "vegetation"]
    if args.limit:
        rendered = rendered[: args.limit]
    results = {}
    jobs = [(s, str(cache), str(out / "thumbs"), luts["E"]) for s in rendered]
    t0 = time.time()
    with cf.ProcessPoolExecutor(args.workers) as ex:
        futs = {ex.submit(process_object, j): j[0] for j in jobs}
        for n, fut in enumerate(cf.as_completed(futs), 1):
            sha = futs[fut]
            try:
                results[sha] = fut.result()
            except Exception as e:
                print(f"!! {sha}: {e!r}", flush=True)
            if n % 50 == 0 or n == len(jobs):
                print(f"[{n}/{len(jobs)}] {time.time() - t0:.0f}s", flush=True)

    mesh_sizes = {}
    try:
        from huggingface_hub import HfApi

        api = HfApi()
        paths = [f"renders/{s}/mesh.ply" for s in results]
        for i in range(0, len(paths), 200):
            for info in api.get_paths_info(REPO, paths[i:i + 200], repo_type="dataset", revision=REV):
                mesh_sizes[info.path.split("/")[1]] = info.size
    except Exception as e:
        print("mesh size lookup failed:", e)

    ds_index = {k: i for i, (k, _) in enumerate(DATASETS)}
    objects, rationale, fam_counter, unmatched = [], defaultdict(dict), Counter(), 0
    for r in base:
        ds = r["dataset"]
        if args.limit and ds != "vegetation" and r["sha256"] not in results:
            continue
        rp = rel_path(r["local_path"], ds)
        ann = ann_by_path.get((ds, rp))
        if ann is None:
            unmatched += 1
            continue
        res = results.get(r["sha256"])
        if ds == "simready":
            cat, sub = r["class"], ""
        else:
            parts_path = rp.split("/")[:-1]
            cat, sub = (parts_path[0] if parts_path else ds), "/".join(parts_path[1:])
        seg_counts = res["seg_counts"] if res else {}
        total = sum(seg_counts.values()) or 0
        parts, texts = [], []
        for key, s in ann["segments"].items():
            fam = classify_family(s["vlm_analysis"], s["material_type"], s["name"], s["density"])
            fam_counter[fam] += 1
            extras = None
            if "static_friction" in s:
                extras = [sig(s.get("static_friction"), 3), sig(s.get("dynamic_friction"), 3),
                          sig(s.get("restitution"), 3), s.get("opacity")]
            frac = round(seg_counts.get(key, 0) / total, 4) if total else None
            parts.append([
                s["semantic_usage"], s["name"], s["material_type"],
                sig(s["youngs_modulus"], 4), sig(s["poissons_ratio"], 4), sig(s["density"], 4),
                FAMILY_INDEX[fam], frac, key.rsplit("__", 1)[-1], extras,
            ])
            texts.append(s["vlm_analysis"].strip())
        order = sorted(range(len(parts)), key=lambda i: -(parts[i][7] or 0))
        parts = [parts[i] for i in order]
        texts = [texts[i] for i in order]
        hashes = [p[8] for p in parts]
        if len(set(hashes)) != len(hashes):
            for p, key in zip(parts, [list(ann["segments"])[i] for i in order]):
                p[8] = key
        obj = {
            "id": r["sha256"],
            "n": ann["object_name"] if ds == "simready" else rp.rsplit("/", 1)[-1].rsplit(".", 1)[0],
            "d": ds_index[ds],
            "c": cat,
            "s": SPLITS.index(r["split"]) if r["split"] in SPLITS else -1,
            "p": parts,
        }
        if sub:
            obj["sub"] = sub
        if res:
            obj.update({
                "v": res["n_vox"], "iv": res["interior"], "up": res["up"], "tv": res["tv"],
                "cam": res["cam"], "ms": mesh_sizes.get(r["sha256"]),
                "a": [[a["sha256"], int(float(a["augmentation_index"] or 0)),
                       *[round(float(a[k]), 5) for k in ("rotation_w", "rotation_x", "rotation_y", "rotation_z")]]
                      for a in sorted(augs.get(r["sha256"], []), key=lambda a: a["augmentation_index"])],
            })
        objects.append(obj)
        rationale[r["sha256"][:2]][r["sha256"]] = texts

    objects.sort(key=lambda o: (o["d"], o["n"].lower()))
    index = {
        "v": 1,
        "repo": REPO,
        "rev": REV,
        "generated": time.strftime("%Y-%m-%d"),
        "datasets": DATASETS,
        "splits": SPLITS,
        "families": FAMILIES,
        "domains": DOMAINS,
        "objects": objects,
    }
    index_bytes = json.dumps(index, separators=(",", ":"), ensure_ascii=False).encode()
    (out / "data" / "index.json").write_bytes(index_bytes)
    # The static Space host does not compress responses; the browser gunzips these itself.
    # ".gzip" (not ".gz") keeps the small shards out of the Space's LFS rules, so they are served
    # without a CDN redirect; the larger index goes as base64 text because big binaries land in LFS.
    (out / "data" / "index.json.gz.b64").write_bytes(base64.b64encode(gzip.compress(index_bytes, 9, mtime=0)))
    for prefix, items in rationale.items():
        payload = json.dumps(items, separators=(",", ":"), ensure_ascii=False).encode()
        (out / "data" / "rationale" / f"{prefix}.json.gzip").write_bytes(gzip.compress(payload, 9, mtime=0))
    print(f"objects={len(objects)} rendered={len(results)} unmatched={unmatched}")
    print("families:", fam_counter.most_common())


if __name__ == "__main__":
    main()