cafca-dataset / scripts /convert_to_webdataset.py
mcbuehler's picture
Add conversion and verification scripts
5d49765 verified
Raw History Blame Contribute Delete
9.2 kB
"""Convert an unzipped Cafca dataset chunk into three WebDataset tiers:
1. view tier key = SUBJECT/EXPR_ENV/CAM -> rgb.png, mask.png, seg.png, cam.json,
landmark.npz, env.json
2. scene-mesh tier key = SUBJECT/EXPR_ENV -> mesh.obj, mesh.mtl, mesh.jpg
3. flame-params tier key = SUBJECT/ENV -> flame.npz
Deliberately excluded (see plan): segmentation_rgb, eval_100/image_grid/*, *.log fitting logs.
Usage:
python convert_to_webdataset.py --input-dir ./data/single_subject_00060 --output-dir ./data/shards_single_subject
"""
import argparse
import io
import re
import sys
from pathlib import Path
import numpy as np
import webdataset as wds
EXPR_ENV_RE = re.compile(r"^(\d{5})_(\d{3})$")
FLAME_DIR_RE = re.compile(r"^flame_2023_(\d{3})$")
CAM_JSON_RE = re.compile(r"^(C\d{2})\.json$")
def find_expr_env_dirs(root: Path):
"""Yields (subject, expr, env, path) for every SUBJECT/EXPR_ENV directory under root."""
for path in sorted(root.rglob("*")):
if not path.is_dir():
continue
m = EXPR_ENV_RE.match(path.name)
if not m:
continue
expr, env = m.group(1), m.group(2)
subject = path.parent.name
if not re.match(r"^\d{5}$", subject):
raise ValueError(f"Expected 5-digit SUBJECT parent dir, got {path.parent} for {path}")
yield subject, expr, env, path
def find_flame_dirs(root: Path):
"""Yields (subject, env, path) for every SUBJECT/flame_2023_ENV directory under root."""
for path in sorted(root.rglob("flame_2023_*")):
if not path.is_dir():
continue
m = FLAME_DIR_RE.match(path.name)
if not m:
continue
env = m.group(1)
subject = path.parent.name
if not re.match(r"^\d{5}$", subject):
raise ValueError(f"Expected 5-digit SUBJECT parent dir, got {path.parent} for {path}")
yield subject, env, path
def load_landmark_npz_normalized(path: Path) -> bytes:
"""STAR landmark npz files have mixed float32/float64 dtypes across the source dataset
(confirmed: bounding_box and face_landmark_2d vary even within the same scene). Normalize
to float32 so the full shard set has one consistent Arrow schema when loaded via HF
`datasets` (it infers schema across all samples upfront, unlike the lazy `webdataset` lib).
This is the one field we don't copy byte-verbatim; documented in the dataset card.
"""
with np.load(path) as d:
arrays = {k: d[k].astype(np.float32) for k in d.files}
buf = io.BytesIO()
np.savez(buf, **arrays)
return buf.getvalue()
def cameras_in(scene_dir: Path):
"""Returns sorted camera names (e.g. ['C00', 'C01', ...]) found in cameras_json/."""
cam_dir = scene_dir / "cameras_json"
cams = []
for f in cam_dir.iterdir():
m = CAM_JSON_RE.match(f.name)
if m:
cams.append(m.group(1))
return sorted(cams)
def convert_view_tier(root: Path, out_dir: Path, shard_size_bytes: int):
seen_keys = set()
(out_dir / "views").mkdir(parents=True, exist_ok=True)
pattern = str(out_dir / "views" / "shard-%06d.tar")
n_written = 0
with wds.ShardWriter(pattern, maxsize=shard_size_bytes) as sink:
for subject, expr, env, scene_dir in find_expr_env_dirs(root):
expr_env = f"{expr}_{env}"
env_json_path = scene_dir / "color_image" / "environment.json"
if not env_json_path.exists():
raise FileNotFoundError(f"Missing environment.json: {env_json_path}")
env_json_bytes = env_json_path.read_bytes()
cams = cameras_in(scene_dir)
if not cams:
raise ValueError(f"No cameras found under {scene_dir}/cameras_json")
for cam in cams:
key = f"{subject}/{expr_env}/{cam}"
if key in seen_keys:
raise ValueError(f"Duplicate view-tier key: {key}")
seen_keys.add(key)
rgb_path = scene_dir / "color_image" / f"{cam}.png"
mask_path = scene_dir / "foreground_mask" / f"{cam}.png"
seg_path = scene_dir / "segmentation" / f"{cam}.png"
cam_json_path = scene_dir / "cameras_json" / f"{cam}.json"
landmark_path = scene_dir / "landmark2d" / "STAR" / f"{cam}.npz"
for p in (rgb_path, mask_path, seg_path, cam_json_path, landmark_path):
if not p.exists():
raise FileNotFoundError(f"Missing expected file for {key}: {p}")
sink.write({
"__key__": key,
"rgb.png": rgb_path.read_bytes(),
"mask.png": mask_path.read_bytes(),
"seg.png": seg_path.read_bytes(),
"cam.json": cam_json_path.read_bytes(),
"landmark.npz": load_landmark_npz_normalized(landmark_path),
"env.json": env_json_bytes,
})
n_written += 1
print(f"[view tier] wrote {n_written} samples, {len(seen_keys)} unique keys")
def convert_scene_mesh_tier(root: Path, out_dir: Path, shard_size_bytes: int):
seen_keys = set()
(out_dir / "scene_mesh").mkdir(parents=True, exist_ok=True)
pattern = str(out_dir / "scene_mesh" / "shard-%06d.tar")
n_written = 0
with wds.ShardWriter(pattern, maxsize=shard_size_bytes) as sink:
for subject, env, flame_dir in find_flame_dirs(root):
mesh_dir = flame_dir / "eval_100" / "mesh"
if not mesh_dir.exists():
raise FileNotFoundError(f"Missing mesh dir: {mesh_dir}")
obj_files = sorted(mesh_dir.glob("frame_*.obj"))
if not obj_files:
raise ValueError(f"No mesh .obj files found under {mesh_dir}")
for obj_path in obj_files:
m = re.match(r"^frame_(\d{5})\.obj$", obj_path.name)
if not m:
raise ValueError(f"Unexpected mesh filename: {obj_path}")
expr = m.group(1)
expr_env = f"{expr}_{env}"
key = f"{subject}/{expr_env}"
if key in seen_keys:
raise ValueError(f"Duplicate scene-mesh-tier key: {key}")
seen_keys.add(key)
mtl_path = mesh_dir / f"frame_{expr}.mtl"
jpg_path = mesh_dir / f"frame_{expr}.jpg"
for p in (mtl_path, jpg_path):
if not p.exists():
raise FileNotFoundError(f"Missing expected mesh file for {key}: {p}")
sink.write({
"__key__": key,
"mesh.obj": obj_path.read_bytes(),
"mesh.mtl": mtl_path.read_bytes(),
"mesh.jpg": jpg_path.read_bytes(),
})
n_written += 1
print(f"[scene-mesh tier] wrote {n_written} samples, {len(seen_keys)} unique keys")
def convert_flame_params_tier(root: Path, out_dir: Path, shard_size_bytes: int):
seen_keys = set()
(out_dir / "flame_params").mkdir(parents=True, exist_ok=True)
pattern = str(out_dir / "flame_params" / "shard-%06d.tar")
n_written = 0
with wds.ShardWriter(pattern, maxsize=shard_size_bytes) as sink:
for subject, env, flame_dir in find_flame_dirs(root):
key = f"{subject}/{env}"
if key in seen_keys:
raise ValueError(f"Duplicate flame-params-tier key: {key}")
seen_keys.add(key)
npz_path = flame_dir / "tracked_flame_params_100.npz"
if not npz_path.exists():
raise FileNotFoundError(f"Missing FLAME params file: {npz_path}")
sink.write({
"__key__": key,
"flame.npz": npz_path.read_bytes(),
})
n_written += 1
print(f"[flame-params tier] wrote {n_written} samples, {len(seen_keys)} unique keys")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input-dir", required=True, type=Path,
help="Root of an unzipped Cafca chunk (searched recursively for SUBJECT/EXPR_ENV and SUBJECT/flame_2023_ENV dirs)")
parser.add_argument("--output-dir", required=True, type=Path,
help="Output dir; will contain views/, scene_mesh/, flame_params/ shard subfolders")
parser.add_argument("--shard-size-mb", type=int, default=500,
help="Target shard size in MB (default: 500)")
args = parser.parse_args()
if not args.input_dir.exists():
print(f"ERROR: input dir does not exist: {args.input_dir}", file=sys.stderr)
sys.exit(1)
args.output_dir.mkdir(parents=True, exist_ok=True)
shard_size_bytes = args.shard_size_mb * 1_000_000
convert_view_tier(args.input_dir, args.output_dir, shard_size_bytes)
convert_scene_mesh_tier(args.input_dir, args.output_dir, shard_size_bytes)
convert_flame_params_tier(args.input_dir, args.output_dir, shard_size_bytes)
if __name__ == "__main__":
main()