cafca-dataset / scripts /verify_shards.py
mcbuehler's picture
Add conversion and verification scripts
5d49765 verified
Raw History Blame Contribute Delete
6.38 kB
"""Local verification of the converted WebDataset shards (Step 5 of the plan):
1. Decode a sample of each tier through both `webdataset` and HF `datasets` loaders.
2. Build the FLAME-params in-memory dict and confirm it joins to every view-tier scene via
ENV = EXPR_ENV[5:] (not a prefix match).
3. Confirm scene-mesh key is a true prefix of the corresponding view-tier keys.
4. Test itertools.groupby scene (30-view) and subject assembly, single-process/no-shuffle.
"""
import glob
import io
import itertools
import sys
import numpy as np
import trimesh
import webdataset as wds
from datasets import load_dataset
SHARD_DIR = sys.argv[1] if len(sys.argv) > 1 else "./data/shards_single_subject"
def view_key_parts(key):
subject, expr_env, cam = key.split("/")
expr, env = expr_env.split("_")
return subject, expr, env, cam
def check_decode_both_loaders():
print("=" * 60)
print("1. Decode check (webdataset lib + HF datasets) per tier")
print("=" * 60)
view_shards = sorted(glob.glob(f"{SHARD_DIR}/views/*.tar"))
mesh_shards = sorted(glob.glob(f"{SHARD_DIR}/scene_mesh/*.tar"))
flame_shards = sorted(glob.glob(f"{SHARD_DIR}/flame_params/*.tar"))
print(f"\n--- view tier: webdataset lib, first 3 samples ---")
ds = wds.WebDataset(view_shards, shardshuffle=False).decode()
for i, s in enumerate(ds):
rgb = np.array(s["rgb.png"]) if hasattr(s["rgb.png"], "shape") else None
print(f" key={s['__key__']} cam.json keys={list(s['cam.json'].keys())[:3]} "
f"landmark keys={list(s['landmark.npz'].keys())}")
if i >= 2:
break
print(f"\n--- view tier: HF datasets, first sample features ---")
hf_ds = load_dataset("webdataset", data_files=view_shards, split="train")
print(" features:", {k: str(v)[:60] for k, v in hf_ds.features.items()})
sample = hf_ds[0]
print(f" seg.png mode={sample['seg.png'].mode} size={sample['seg.png'].size}")
print(f" rgb.png mode={sample['rgb.png'].mode} size={sample['rgb.png'].size}")
assert sample["seg.png"].mode == "I;16", "segmentation did not decode as 16-bit!"
print(f"\n--- scene-mesh tier: webdataset lib ---")
ds = wds.WebDataset(mesh_shards, shardshuffle=False).decode()
for i, s in enumerate(ds):
mesh = trimesh.load(io.BytesIO(s["mesh.obj"] if isinstance(s["mesh.obj"], bytes) else s["mesh.obj"]), file_type="obj")
print(f" key={s['__key__']} mesh vertices={mesh.vertices.shape}")
if i >= 1:
break
print(f"\n--- flame-params tier: HF datasets ---")
hf_flame = load_dataset("webdataset", data_files=flame_shards, split="train")
print(" count:", len(hf_flame))
for row in hf_flame:
shape = np.array(row["flame.npz"]["expr"]).shape
print(f" key={row['__key__']} expr shape={shape}")
return view_shards, mesh_shards, flame_shards
def check_flame_join(view_shards, flame_shards):
print("\n" + "=" * 60)
print("2. FLAME-params join via ENV = EXPR_ENV[5:] (dict lookup, not prefix)")
print("=" * 60)
flame_ds = wds.WebDataset(flame_shards, shardshuffle=False).decode()
flame_by_key = {s["__key__"]: s["flame.npz"] for s in flame_ds}
print(f" loaded {len(flame_by_key)} flame-params entries: {list(flame_by_key.keys())}")
view_ds = wds.WebDataset(view_shards, shardshuffle=False)
scenes_seen = set()
missing = []
for s in view_ds:
subject, expr, env, cam = view_key_parts(s["__key__"])
expr_env = f"{expr}_{env}"
scene_key = f"{subject}/{expr_env}"
if scene_key in scenes_seen:
continue
scenes_seen.add(scene_key)
flame_key = f"{subject}/{env}"
if flame_key not in flame_by_key:
missing.append((scene_key, flame_key))
print(f" checked {len(scenes_seen)} distinct scenes")
if missing:
print(f" MISSING flame entries for: {missing}")
else:
print(" OK: every scene's FLAME-params entry found via env slice")
def check_scene_mesh_prefix(view_shards, mesh_shards):
print("\n" + "=" * 60)
print("3. Scene-mesh key is a true prefix of view-tier keys")
print("=" * 60)
mesh_keys = {s["__key__"] for s in wds.WebDataset(mesh_shards, shardshuffle=False)}
view_ds = wds.WebDataset(view_shards, shardshuffle=False)
bad = []
checked = 0
for s in view_ds:
subject, expr, env, cam = view_key_parts(s["__key__"])
scene_key = f"{subject}/{expr}_{env}"
checked += 1
if not s["__key__"].startswith(scene_key + "/"):
bad.append(s["__key__"])
if scene_key not in mesh_keys:
bad.append((s["__key__"], "no matching mesh key"))
print(f" checked {checked} view samples against {len(mesh_keys)} mesh keys")
print(" OK: prefix relationship holds" if not bad else f" FAILURES: {bad[:10]}")
def check_groupby(view_shards):
print("\n" + "=" * 60)
print("4. itertools.groupby scene (30-view) and subject assembly")
print(" (single-process, no shuffle, sequential read)")
print("=" * 60)
ds = wds.WebDataset(view_shards, shardshuffle=False)
def scene_key(sample):
subject, expr, env, cam = view_key_parts(sample["__key__"])
return f"{subject}/{expr}_{env}"
def subject_key(sample):
subject, expr, env, cam = view_key_parts(sample["__key__"])
return subject
scene_sizes = []
for key, group in itertools.groupby(ds, key=scene_key):
scene_sizes.append((key, len(list(group))))
print(f" found {len(scene_sizes)} scene groups")
bad_scenes = [(k, n) for k, n in scene_sizes if n != 30]
print(" OK: every scene has exactly 30 views" if not bad_scenes
else f" FAILURES (expected 30 views each): {bad_scenes}")
ds2 = wds.WebDataset(view_shards, shardshuffle=False)
subject_sizes = []
for key, group in itertools.groupby(ds2, key=subject_key):
subject_sizes.append((key, len(list(group))))
print(f" found {len(subject_sizes)} subject groups: {[(k, n) for k, n in subject_sizes]}")
if __name__ == "__main__":
view_shards, mesh_shards, flame_shards = check_decode_both_loaders()
check_flame_join(view_shards, flame_shards)
check_scene_mesh_prefix(view_shards, mesh_shards)
check_groupby(view_shards)
print("\nAll checks completed.")