File size: 4,182 Bytes
0ede4b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ccd4bb
 
 
 
 
 
0ede4b0
 
 
7ccd4bb
 
0ede4b0
 
 
 
 
 
 
 
 
 
 
 
7ccd4bb
 
 
 
 
 
 
 
 
 
 
 
 
0ede4b0
7ccd4bb
 
 
 
 
 
 
0ede4b0
 
 
 
 
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
109
110
111
112
113
114
import argparse
import json
import re
from pathlib import Path

import pyarrow.parquet as pq

DATASET = "FutureCAD"
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)
    parser.add_argument("--format", choices=["history", "descriptions"], default="history")
    parser.add_argument(
        "--description-level", choices=["overall", "detail"], default="detail"
    )
    args = parser.parse_args()
    split = "validation" if args.split == "val" else args.split
    splits = ["train", "validation", "test"] if split == "all" else [split]
    count = 0
    descriptions = {}
    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
                    if not re.fullmatch("\\d{8}", row["id"]):
                        raise ValueError("Invalid CAD ID")
                    if args.format == "descriptions":
                        text = row[args.description_level + "_description"]
                        if not isinstance(text, str) or not text.strip():
                            raise ValueError(f"Missing description for {row['id']}")
                        if row["id"] in descriptions:
                            raise ValueError(f"Duplicate CAD ID: {row['id']}")
                        descriptions[row["id"]] = text
                    else:
                        json.loads(row["history"])
                        write_file(
                            args.output / (row["id"] + ".json"),
                            (row["history"] + "\n").encode("utf-8"),
                        )
                    count += 1
    if not count:
        raise ValueError(f"No matching sample: {args.sample_id}")
    if args.format == "descriptions":
        write_file(
            args.output / "descriptions.json",
            (json.dumps(descriptions, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
        )
    print(f"Exported {count} {DATASET} samples to {args.output.resolve()}")


if __name__ == "__main__":
    main()