niuniandaji commited on
Commit
9fea522
·
verified ·
1 Parent(s): 09b56d6

Upload create_nano_dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. create_nano_dataset.py +227 -0
create_nano_dataset.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import random
4
+ import shutil
5
+ from tqdm import tqdm
6
+ import webdataset as wds
7
+ from huggingface_hub import HfApi, HfFolder
8
+
9
+ def sample_and_copy_files(source_dir, output_dir, num_samples, seed, scan_report_interval):
10
+ """
11
+ Scans a source directory, randomly samples image files, and copies them
12
+ to an output directory, preserving the original structure.
13
+
14
+ IMPORTANT: This script is currently hardcoded to only sample images from
15
+ corruption severity level 5.
16
+ """
17
+ print(f"1. Scanning for image files in '{source_dir}'...")
18
+ all_files = []
19
+ count = 0
20
+ for root, _, files in os.walk(source_dir):
21
+ # HARDCODED FILTER: Only include files from severity level 5 directories.
22
+ # We check if '5' is a component of the directory path.
23
+ path_parts = root.split(os.sep)
24
+ if '5' in path_parts:
25
+ for file in files:
26
+ if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
27
+ all_files.append(os.path.join(root, file))
28
+ count += 1
29
+ if count > 0 and count % scan_report_interval == 0:
30
+ print(f" ...scanned {count} images (from severity 5)...")
31
+
32
+ if not all_files:
33
+ print(f"Error: No image files found for severity level 5 in '{source_dir}'. Exiting.")
34
+ return False
35
+
36
+ print(f"Found {len(all_files)} total images.")
37
+
38
+ # Sort the file list to ensure reproducibility across different systems.
39
+ # The order of files returned by os.walk is not guaranteed to be the same.
40
+ all_files.sort()
41
+
42
+ print(f"2. Randomly sampling {num_samples} images (seed={seed})...")
43
+ # Set the random seed for reproducibility.
44
+ # Note: For 100% identical results, the same version of Python should be used
45
+ # (e.g., this script was created using Python 3.10.14), as the underlying
46
+ # algorithm for the 'random' module can change between versions.
47
+ random.seed(seed)
48
+ num_to_sample = min(num_samples, len(all_files))
49
+ sampled_files = random.sample(all_files, num_to_sample)
50
+ print(f"Selected {len(sampled_files)} files to copy.")
51
+
52
+ print(f"3. Copying files to '{output_dir}'...")
53
+ if os.path.exists(output_dir):
54
+ print(f"Output directory '{output_dir}' already exists. Removing it.")
55
+ shutil.rmtree(output_dir)
56
+ os.makedirs(output_dir)
57
+
58
+ for file_path in tqdm(sampled_files, desc="Copying files"):
59
+ relative_path = os.path.relpath(file_path, source_dir)
60
+ dest_path = os.path.join(output_dir, relative_path)
61
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
62
+ shutil.copy(file_path, dest_path)
63
+
64
+ print("File copying complete.")
65
+ return True
66
+
67
+ def generate_readme_content(repo_id, seed, python_version, tar_filename, script_filename):
68
+ """
69
+ Generates the content for the README.md file for the Hugging Face dataset.
70
+ """
71
+ return f"""---
72
+ license: mit
73
+ tags:
74
+ - image-classification
75
+ - computer-vision
76
+ - imagenet-c
77
+ ---
78
+
79
+ # Nano ImageNet-C (Severity 5)
80
+
81
+ This is a randomly sampled subset of the ImageNet-C dataset, containing 5,000 images exclusively from corruption **severity level 5**. It is designed for efficient testing and validation of model robustness.
82
+
83
+ 这是一个从 ImageNet-C 数据集中随机抽样的子集,包含 5000 张仅来自损坏等级为 **5** 的图像。它旨在用于高效地测试和验证模型的鲁棒性。
84
+
85
+ ## How to Generate / 如何生成
86
+
87
+ This dataset was generated using the `{script_filename}` script included in this repository. To ensure reproducibility, the following parameters were used:
88
+
89
+ 本数据集使用此仓库中包含的 `{script_filename}` 脚本生成。为确保可复现性,生成时使用了以下参数:
90
+
91
+ - **Source Dataset / 源数据集**: The full ImageNet-C dataset is required. / 需要完整的 ImageNet-C 数据集。
92
+ - **Random Seed / 随机种子**: `{seed}`
93
+ - **Python Version / Python 版本**: `{python_version}`
94
+
95
+ ## Dataset Structure / 数据集结构
96
+
97
+ The dataset is provided as a single `.tar` file named `{tar_filename}` in the `webdataset` format. The internal structure preserves the original ImageNet-C hierarchy: `corruption_type/class_name/image.jpg`.
98
+
99
+ 数据集以 `webdataset` 格式打包在名为 `{tar_filename}` 的单个 `.tar` 文件中。其内部结构保留了原始 ImageNet-C 的层次结构:`corruption_type/class_name/image.jpg`。
100
+
101
+ ## Citation / 引用
102
+
103
+ If you use this dataset, please cite the original ImageNet-C paper:
104
+
105
+ 如果您使用此数据集,请引用原始 ImageNet-C 的论文:
106
+
107
+ ```bibtex
108
+ @inproceedings{{danhendrycks2019robustness,
109
+ title={{Benchmarking Neural Network Robustness to Common Corruptions and Perturbations}},
110
+ author={{Dan Hendrycks and Thomas Dietterich}},
111
+ booktitle={{International Conference on Learning Representations}},
112
+ year={{2019}},
113
+ url={{https://openreview.net/forum?id=HJz6tiCqYm}},
114
+ }}
115
+ ```
116
+ """
117
+
118
+ def package_with_webdataset(output_dir, tar_path):
119
+ """
120
+ Packages the contents of a directory into a single .tar file using webdataset.
121
+ """
122
+ print(f"4. Packaging '{output_dir}' into '{tar_path}'...")
123
+
124
+ with wds.TarWriter(tar_path) as sink:
125
+ for root, _, files in tqdm(list(os.walk(output_dir)), desc="Packaging files"):
126
+ for file in files:
127
+ file_path = os.path.join(root, file)
128
+ with open(file_path, "rb") as stream:
129
+ content = stream.read()
130
+
131
+ relative_path = os.path.relpath(file_path, output_dir)
132
+ key, ext = os.path.splitext(relative_path)
133
+ extension = ext.lstrip('.')
134
+
135
+ sink.write({
136
+ "__key__": key,
137
+ extension: content
138
+ })
139
+
140
+ print("Packaging complete.")
141
+
142
+ def upload_to_hf(tar_path, readme_path, script_path, repo_id):
143
+ """
144
+ Uploads a file to a specified Hugging Face Hub repository.
145
+ """
146
+ print(f"5. Uploading files to Hugging Face Hub repository: {repo_id}...")
147
+
148
+ if HfFolder.get_token() is None:
149
+ print("Hugging Face token not found. Please log in using `huggingface-cli login` first.")
150
+ return
151
+
152
+ try:
153
+ api = HfApi()
154
+ print(f"Creating repository '{repo_id}' (if it doesn't exist)...")
155
+ api.create_repo(repo_id, repo_type="dataset", exist_ok=True)
156
+
157
+ print("Uploading README.md...")
158
+ api.upload_file(
159
+ path_or_fileobj=readme_path,
160
+ path_in_repo="README.md",
161
+ repo_id=repo_id,
162
+ repo_type="dataset"
163
+ )
164
+
165
+ script_filename = os.path.basename(script_path)
166
+ print(f"Uploading generation script '{script_filename}'...")
167
+ api.upload_file(
168
+ path_or_fileobj=script_path,
169
+ path_in_repo=script_filename,
170
+ repo_id=repo_id,
171
+ repo_type="dataset"
172
+ )
173
+
174
+ tar_filename = os.path.basename(tar_path)
175
+ print(f"Uploading dataset file '{tar_filename}'...")
176
+ api.upload_file(
177
+ path_or_fileobj=tar_path,
178
+ path_in_repo=tar_filename,
179
+ repo_id=repo_id,
180
+ repo_type="dataset"
181
+ )
182
+ print("Upload successful!")
183
+ print(f"Dataset available at: https://huggingface.co/datasets/{repo_id}")
184
+ except Exception as e:
185
+ print(f"An error occurred during upload: {e}")
186
+
187
+ def main():
188
+ """
189
+ Main function to orchestrate the dataset creation, packaging, and upload process.
190
+ """
191
+ parser = argparse.ArgumentParser(description="Create, package, and upload a smaller version of an image dataset.")
192
+ parser.add_argument("--source_dir", type=str, default="./data/ImageNet-C", help="Path to the source dataset.")
193
+ parser.add_argument("--output_dir", type=str, default="./data/nano-ImageNet-C", help="Path to save the new sampled dataset.")
194
+ parser.add_argument("--num_samples", type=int, default=5000, help="Number of images to sample.")
195
+ parser.add_argument("--seed", type=int, default=7600, help="Random seed for reproducibility.")
196
+ parser.add_argument("--repo_id", type=str, default="niuniandaji/nano-imagenet-c", help="The Hugging Face Hub repository ID.")
197
+ parser.add_argument("--tar_path", type=str, default="./data/nano-ImageNet-C.tar", help="Path to save the final webdataset archive.")
198
+ parser.add_argument("--scan_report_interval", type=int, default=50000, help="How often to report progress during file scanning.")
199
+ args = parser.parse_args()
200
+
201
+ print("--- Starting Dataset Creation Process ---")
202
+ print("IMPORTANT: The script is configured to sample ONLY from severity level 5.")
203
+
204
+ # Generate README content
205
+ script_filename = os.path.basename(__file__)
206
+ readme_content = generate_readme_content(
207
+ args.repo_id,
208
+ args.seed,
209
+ "3.10.14",
210
+ os.path.basename(args.tar_path),
211
+ script_filename
212
+ )
213
+
214
+ # Write README to a local file
215
+ readme_path = "README.md"
216
+ with open(readme_path, "w", encoding="utf-8") as f:
217
+ f.write(readme_content)
218
+ print(f"Generated README.md for the dataset.")
219
+
220
+ if sample_and_copy_files(args.source_dir, args.output_dir, args.num_samples, args.seed, args.scan_report_interval):
221
+ package_with_webdataset(args.output_dir, args.tar_path)
222
+ upload_to_hf(args.tar_path, readme_path, script_filename, args.repo_id)
223
+
224
+ print("--- Process Finished ---")
225
+
226
+ if __name__ == "__main__":
227
+ main()