File size: 3,715 Bytes
96e7a80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Export RealEstate10K-Cap to per-clip .npy files in the TKCAM directory layout.

    <out_dir>/
        trajectories/<id>.npy     (N, 12) TKCAM format, or (N, 9) universal format; row i = frame i+1
        texts/<id>.txt            "caption#word/POS ..." (TKCAM text loader format)
        untagged_text/<id>.txt    plain caption
        train.txt / val.txt / test.txt
        Mean.npy / Std.npy        (12d only; over all exported clips, as in TKCAM)

Formats:
    12d  [x, y, z, dx, dy, dz, r11, r21, r31, r12, r22, r32]   (as stored)
    9d   [r11, r21, r31, r12, r22, r32, x, y, z]               (CLaTr / benchmark format)

Requirements:  pip install numpy pyarrow

Example:
    python scripts/export_npy.py --data-dir data --out-dir RealEstate10K-Cap_npy --format 12d
    # frames for TKCAM's --frame_dir:
    python scripts/download_frames.py --data-dir data --out-dir RealEstate10K-Cap_frames
"""

import argparse
import glob
import os
import shutil

import numpy as np
import pyarrow.parquet as pq


def to_9d(traj12):
    return np.concatenate([traj12[:, 6:12], traj12[:, 0:3]], axis=1)


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--data-dir", default="data", help="folder with the *.parquet files")
    parser.add_argument("--out-dir", required=True)
    parser.add_argument("--format", choices=["12d", "9d"], default="12d")
    parser.add_argument("--exclude-benchmark", action="store_true",
                        help="drop clips with in_benchmark_test=True from train/val")
    args = parser.parse_args()

    for sub in ("trajectories", "texts", "untagged_text"):
        os.makedirs(os.path.join(args.out_dir, sub), exist_ok=True)

    cols = ["id", "split", "caption", "caption_pos", "trajectory_12d", "in_benchmark_test"]
    splits = {"train": [], "val": [], "test": []}
    for f in sorted(glob.glob(os.path.join(args.data_dir, "*.parquet"))):
        for row in pq.read_table(f, columns=cols).to_pylist():
            if args.exclude_benchmark and row["in_benchmark_test"] and row["split"] != "test":
                continue
            sid = row["id"]
            traj = np.asarray(row["trajectory_12d"], dtype=np.float32)
            np.save(os.path.join(args.out_dir, "trajectories", f"{sid}.npy"),
                    to_9d(traj) if args.format == "9d" else traj)
            with open(os.path.join(args.out_dir, "texts", f"{sid}.txt"), "w") as fh:
                fh.write(f"{row['caption']}#{row['caption_pos']}\n")
            with open(os.path.join(args.out_dir, "untagged_text", f"{sid}.txt"), "w") as fh:
                fh.write(row["caption"] + "\n")
            splits[row["split"]].append(sid)

    for split, ids in splits.items():
        with open(os.path.join(args.out_dir, f"{split}.txt"), "w") as fh:
            fh.write("\n".join(sorted(ids)) + "\n")

    if args.format == "12d":
        stats_dir = os.path.join(os.path.dirname(os.path.abspath(args.data_dir)), "stats")
        if not args.exclude_benchmark and os.path.isdir(stats_dir):
            for name in ("Mean.npy", "Std.npy"):
                shutil.copy2(os.path.join(stats_dir, name), os.path.join(args.out_dir, name))
        else:
            frames = np.concatenate([np.load(os.path.join(args.out_dir, "trajectories", f"{s}.npy"))
                                     for ids in splits.values() for s in ids])
            np.save(os.path.join(args.out_dir, "Mean.npy"), frames.mean(0))
            np.save(os.path.join(args.out_dir, "Std.npy"), frames.std(0))

    print({k: len(v) for k, v in splits.items()}, "->", args.out_dir)


if __name__ == "__main__":
    main()