donut / tools /build_webdataset.py
LouisM2001's picture
Replace obj/ and pcd/ with WebDataset train/test shards (float32/int32); old layout at tag v1-legacy
1e67656 verified
Raw History Blame Contribute Delete
2.42 kB
"""Convert the obj/ + pcd/ + metadata.csv layout into WebDataset tar shards (train/, test/).
Each sample key is the sample id, with members:
{id}.vertices.npy (V, 3) float32
{id}.faces.npy (F, 3) int32
{id}.pcd.npy (8192, 3) float32
{id}.json {"id", "genus", "components", "sample_code"}
"""
import io, json, tarfile
from multiprocessing import Pool
from pathlib import Path
import numpy as np
import pandas as pd
ROOT = Path(__file__).resolve().parents[1]
PER_SHARD = 600 # ~1 GB per shard
SEED = 0
meta = pd.read_csv(ROOT / "metadata.csv").set_index("id")
obj_path = {p.stem: p for p in (ROOT / "obj").glob("*/*.npz")}
pcd_path = {p.stem: p for p in (ROOT / "pcd").glob("*/*.npy")}
def npy_bytes(a: np.ndarray) -> bytes:
buf = io.BytesIO()
np.save(buf, a)
return buf.getvalue()
def add(tar: tarfile.TarFile, name: str, data: bytes):
info = tarfile.TarInfo(name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
def write_shard(args):
out, ids = args
tmp = out.with_suffix(".tar.tmp")
with tarfile.open(tmp, "w", format=tarfile.USTAR_FORMAT) as tar:
for i in ids:
z = np.load(obj_path[i])
row = meta.loc[i]
add(tar, f"{i}.vertices.npy", npy_bytes(z["vertices"].astype(np.float32))) # (V, 3)
add(tar, f"{i}.faces.npy", npy_bytes(z["faces"].astype(np.int32))) # (F, 3)
add(tar, f"{i}.pcd.npy", npy_bytes(np.load(pcd_path[i]).astype(np.float32))) # (8192, 3)
add(tar, f"{i}.json", json.dumps({
"id": i, "genus": int(row.genus), "components": int(row.components),
"sample_code": json.loads(row.sample_code),
}).encode())
tmp.rename(out)
return out.name
if __name__ == "__main__":
jobs = []
for split in ["train", "test"]:
ids = np.array((ROOT / "splits/full" / f"{split}.txt").read_text().split())
ids = ids[np.random.default_rng(SEED).permutation(len(ids))] # shuffle so shards are i.i.d.
(ROOT / split).mkdir(exist_ok=True)
for s, k in enumerate(range(0, len(ids), PER_SHARD)):
out = ROOT / split / f"{split}-{s:05d}.tar"
if not out.exists():
jobs.append((out, ids[k:k + PER_SHARD].tolist()))
with Pool(8) as pool:
for name in pool.imap_unordered(write_shard, jobs):
print(name, flush=True)