JeffreyJsam commited on
Commit
3ebd901
·
verified ·
1 Parent(s): 34ab979

Delete download_swim.py

Browse files
Files changed (1) hide show
  1. download_swim.py +0 -112
download_swim.py DELETED
@@ -1,112 +0,0 @@
1
- import argparse
2
- from io import BytesIO
3
- from pathlib import Path
4
- from huggingface_hub import list_repo_tree, hf_hub_url, HfFileSystem
5
- from huggingface_hub.hf_api import RepoFile
6
- import fsspec
7
- from PIL import Image
8
- from tqdm import tqdm
9
-
10
- def enumerate_chunks(repo_id, images_parent):
11
- """
12
- Lists all immediate chunk subdirs under the images parent using HfFileSystem.
13
- Returns sorted list of subdir names (e.g. ['000', '001', ...]).
14
- """
15
- fs = HfFileSystem()
16
- repo_path = f"datasets/{repo_id}/{images_parent}"
17
- entries = fs.ls(repo_path, detail=True)
18
- subdirs = [entry['name'].split('/')[-1] for entry in entries if entry['type'] == 'directory']
19
- subdirs.sort()
20
- return subdirs
21
-
22
- def sample_dataset(
23
- repo_id: str,
24
- images_parent: str,
25
- labels_parent: str,
26
- output_dir: str,
27
- # max_files: int = 500,
28
- flatten: bool = True,
29
- chunks: list = None
30
- ):
31
- total_downloaded = 0
32
- all_chunks = chunks
33
- if all_chunks is None:
34
- all_chunks = enumerate_chunks(repo_id, images_parent)
35
- print(f"Found chunks: {all_chunks}")
36
- for chunk in all_chunks:
37
- image_subdir = f"{images_parent}/{chunk}"
38
- label_subdir = f"{labels_parent}/{chunk}"
39
-
40
- # List only in the specified chunk
41
- image_files = list_repo_tree(
42
- repo_id=repo_id,
43
- path_in_repo=image_subdir,
44
- repo_type="dataset",
45
- recursive=True,
46
- )
47
-
48
- for img_file in tqdm(image_files, desc=f"Downloading {chunk}", leave=False):
49
- if not isinstance(img_file, RepoFile) or not img_file.path.lower().endswith(".png"):
50
- continue
51
-
52
- rel_path = Path(img_file.path).relative_to(image_subdir)
53
- label_path = f"{label_subdir}/{rel_path.with_suffix('.txt')}"
54
-
55
- if flatten:
56
- parts = img_file.path.split('/')
57
- # print(parts)
58
- # Remove the chunk dir (second last)
59
- flat_path = '/'.join(parts[:-2] + [parts[-1]])
60
- # For labels, also strip the chunk and substitute extension
61
- flat_label_path = flat_path.replace('.png', '.txt').replace('images', 'labels')
62
- local_image_path = Path(output_dir) / flat_path
63
- local_label_path = Path(output_dir) / flat_label_path
64
- else:
65
- local_image_path = Path(output_dir) / img_file.path
66
- local_label_path = Path(output_dir) / label_path
67
-
68
- local_image_path.parent.mkdir(parents=True, exist_ok=True)
69
- local_label_path.parent.mkdir(parents=True, exist_ok=True)
70
-
71
- image_url = hf_hub_url(repo_id=repo_id, filename=img_file.path, repo_type="dataset")
72
- label_url = hf_hub_url(repo_id=repo_id, filename=label_path, repo_type="dataset")
73
- try:
74
- with fsspec.open(image_url) as f:
75
- image = Image.open(BytesIO(f.read()))
76
- image.save(local_image_path)
77
- with fsspec.open(label_url) as f:
78
- txt_content = f.read()
79
- with open(local_label_path, "wb") as out_f:
80
- out_f.write(txt_content)
81
- total_downloaded += 1
82
- except Exception as e:
83
- print(f"Failed {rel_path}: {e}")
84
-
85
-
86
-
87
-
88
- print(f"Downloaded {total_downloaded} image/txt pairs.")
89
- print(f"Saved under: {Path(output_dir).resolve()}")
90
-
91
- def parse_args():
92
- parser = argparse.ArgumentParser(description="Stream and sample paired images + txt labels from a Hugging Face folder-structured dataset, optionally across multiple chunks.")
93
- parser.add_argument("--repo-id", default="JeffreyJsam/SWiM-SpacecraftWithMasks", help="Hugging Face dataset repo ID.")
94
- parser.add_argument("--images-parent", default="Baseline/images/val", help="Parent directory for image chunks.")
95
- parser.add_argument("--labels-parent", default="Baseline/labels/val", help="Parent directory for label chunks.")
96
- parser.add_argument("--output-dir", default="./SWiM", help="Where to save sampled data.")
97
- #parser.add_argument("--count", type=int, default=500, help="How many samples to download in total.")
98
- parser.add_argument("--flatten", default=True, type=bool, help="Save all samples in a single folder without subdirectories.")
99
- parser.add_argument("--chunks", nargs="*", default=None, help="Specific chunk names to sample (e.g. 000 001). Leave empty to process all.")
100
- return parser.parse_args()
101
-
102
- if __name__ == "__main__":
103
- args = parse_args()
104
- sample_dataset(
105
- repo_id=args.repo_id,
106
- images_parent=args.images_parent,
107
- labels_parent=args.labels_parent,
108
- output_dir=args.output_dir,
109
- # max_files=args.count,
110
- flatten=args.flatten,
111
- chunks=args.chunks
112
- )