File size: 2,416 Bytes
1e67656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)