File size: 3,837 Bytes
8a8f710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import argparse
import re
import zipfile
from collections import defaultdict
from pathlib import Path

import pyarrow.parquet as pq

DATASET = "BRepGround"
DEFAULT_REPO = "jhlee11/" + DATASET


def get_file(source, relative, cache_dir):
    if Path(source).is_dir():
        return Path(source) / relative
    from huggingface_hub import hf_hub_download

    return Path(
        hf_hub_download(source, relative, repo_type="dataset", cache_dir=cache_dir)
    )


def metadata_files(source, split):
    if Path(source).is_dir():
        return [
            p.relative_to(source).as_posix()
            for p in sorted(Path(source).glob(f"data/{split}-*.parquet"))
        ]
    from huggingface_hub import HfApi

    return sorted(
        p
        for p in HfApi().list_repo_files(source, repo_type="dataset")
        if p.startswith(f"data/{split}-") and p.endswith(".parquet")
    )


def write_file(path, payload):
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        if path.read_bytes() != payload:
            raise FileExistsError(f"Refusing to replace different content: {path}")
        return
    temporary = path.with_suffix(path.suffix + ".partial")
    temporary.write_bytes(payload)
    temporary.replace(path)


def main():
    parser = argparse.ArgumentParser(
        description="Download or locally export the dataset into individual files."
    )
    parser.add_argument(
        "--source",
        default=DEFAULT_REPO,
        help="Hub dataset ID or local repository directory",
    )
    parser.add_argument(
        "--split", choices=["train", "validation", "val", "test", "all"], default="all"
    )
    parser.add_argument(
        "--id",
        dest="sample_id",
        help="Export one exact ID; searches the selected splits",
    )
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--cache-dir", type=Path)
    args = parser.parse_args()
    split = "validation" if args.split == "val" else args.split
    splits = ["train", "validation", "test"] if split == "all" else [split]
    assets = defaultdict(set)
    count = 0
    for split in splits:
        files = metadata_files(args.source, split)
        if not files:
            raise FileNotFoundError(f"No Parquet files for {split} in {args.source}")
        for filename in files:
            path = get_file(args.source, filename, args.cache_dir)
            for batch in pq.ParquetFile(path).iter_batches(batch_size=128):
                for row in batch.to_pylist():
                    if args.sample_id and row["id"] != args.sample_id:
                        continue
                    assets[row["asset_archive"]].update(
                        [row["step_path"], row["label_path"]]
                    )
                    count += 1
    if not count:
        raise ValueError(f"No matching sample: {args.sample_id}")
    for archive, members in sorted(assets.items()):
        if not re.fullmatch(
            "assets/(train|validation|test)-\\d{5}-of-\\d{5}\\.zip", archive
        ):
            raise ValueError(f"Unexpected archive: {archive}")
        path = get_file(args.source, archive, args.cache_dir)
        with zipfile.ZipFile(path) as z:
            for member in sorted(members):
                if not re.fullmatch(
                    "(steps|labels)/\\d{8}_[a-z]+_\\d+\\.(step|json)", member
                ):
                    raise ValueError(f"Unexpected asset path: {member}")
                write_file(args.output / member, z.read(member))
        print(f"Exported {len(members)} files from {archive}", flush=True)
    print(f"Exported {count} {DATASET} samples to {args.output.resolve()}")


if __name__ == "__main__":
    main()