Maazwaheed commited on
Commit
2a3bff2
·
verified ·
1 Parent(s): 3356e2c

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +122 -1
README.md CHANGED
@@ -108,7 +108,128 @@ dataset = load_dataset("Maazwaheed/set_SHAPES")
108
  print(f"Dataset size: {len(dataset['train'])}")
109
  print(f"Sample caption: {dataset['train'][0]['caption']}")
110
  ```
111
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  ### Advanced Usage
113
  ```python
114
  # Filter motion scenes
 
108
  print(f"Dataset size: {len(dataset['train'])}")
109
  print(f"Sample caption: {dataset['train'][0]['caption']}")
110
  ```
111
+ ### fast load
112
+ ```python
113
+ import os
114
+ import logging
115
+ from concurrent.futures import ThreadPoolExecutor, as_completed
116
+ from datasets import load_dataset
117
+ from PIL import Image
118
+ import pandas as pd
119
+ from tqdm import tqdm
120
+ import io
121
+ import threading
122
+
123
+ # Configuration
124
+ DATASET_NAME = "Maazwaheed/set_SHAPES"
125
+ OUTPUT_DIR = "advanced_motion_dataset"
126
+ IMAGES_DIR = os.path.join(OUTPUT_DIR, "images")
127
+ MAX_WORKERS = 16 # Adjust based on system capabilities
128
+ HF_TOKEN = os.getenv("HF_TOKEN") # Ensure HF_TOKEN is set in environment
129
+ LOG_DIR = "logs"
130
+ LOG_FILE = os.path.join(LOG_DIR, "download.log")
131
+
132
+ # Setup logging
133
+ os.makedirs(LOG_DIR, exist_ok=True)
134
+ logging.basicConfig(
135
+ filename=LOG_FILE,
136
+ level=logging.INFO,
137
+ format="%(asctime)s - %(levelname)s - %(message)s"
138
+ )
139
+
140
+ # Thread-safe counter for tracking downloaded images
141
+ download_counter = 0
142
+ counter_lock = threading.Lock()
143
+
144
+ def setup_directories():
145
+ """Create output directories if they don't exist."""
146
+ try:
147
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
148
+ os.makedirs(IMAGES_DIR, exist_ok=True)
149
+ logging.info(f"Created directories: {OUTPUT_DIR}, {IMAGES_DIR}")
150
+ except Exception as e:
151
+ logging.error(f"Failed to create directories: {e}")
152
+ raise
153
+
154
+ def download_image(item, index):
155
+ """Download and save a single image with its filename."""
156
+ try:
157
+ image = item["image"]
158
+ filename = item.get("filename", f"{str(index+1).zfill(5)}.jpg")
159
+ image_path = os.path.join(IMAGES_DIR, filename)
160
+
161
+ # Convert to RGB if needed and save as JPEG
162
+ if image.mode != "RGB":
163
+ image = image.convert("RGB")
164
+ image.save(image_path, "JPEG", quality=95)
165
+
166
+ # Increment counter thread-safely
167
+ global download_counter
168
+ with counter_lock:
169
+ download_counter += 1
170
+
171
+ return filename, item.get("caption", ""), None
172
+ except Exception as e:
173
+ logging.error(f"Failed to download image at index {index}: {e}")
174
+ return None, None, str(e)
175
+
176
+ def download_dataset():
177
+ """Download the dataset efficiently using parallel processing."""
178
+ try:
179
+ # Load dataset
180
+ logging.info(f"Loading dataset: {DATASET_NAME}")
181
+ dataset = load_dataset(DATASET_NAME, split="train", use_auth_token=HF_TOKEN)
182
+ logging.info(f"Dataset loaded with {len(dataset)} items")
183
+
184
+ # Setup directories
185
+ setup_directories()
186
+
187
+ # Prepare metadata
188
+ metadata = []
189
+
190
+ # Download images in parallel
191
+ logging.info(f"Starting parallel download with {MAX_WORKERS} workers")
192
+ with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
193
+ future_to_index = {executor.submit(download_image, dataset[i], i): i for i in range(len(dataset))}
194
+ progress_bar = tqdm(total=len(dataset), desc="Downloading images")
195
+
196
+ for future in as_completed(future_to_index):
197
+ index = future_to_index[future]
198
+ filename, caption, error = future.result()
199
+ if filename and caption is not None:
200
+ metadata.append([filename, caption])
201
+ else:
202
+ logging.warning(f"Skipped item at index {index} due to error: {error}")
203
+ progress_bar.update(1)
204
+
205
+ progress_bar.close()
206
+
207
+ # Save captions.csv
208
+ try:
209
+ csv_path = os.path.join(OUTPUT_DIR, "captions.csv")
210
+ with open(csv_path, "w", newline="", encoding="utf-8") as f:
211
+ writer = pd.DataFrame(metadata, columns=["filename", "caption"])
212
+ writer.to_csv(f, index=False)
213
+ logging.info(f"Saved captions to {csv_path}")
214
+ except Exception as e:
215
+ logging.error(f"Failed to save captions.csv: {e}")
216
+ raise
217
+
218
+ logging.info(f"Downloaded {download_counter} images to {IMAGES_DIR}")
219
+ print(f"Dataset downloaded successfully! {download_counter} images saved to {IMAGES_DIR}, captions saved to {csv_path}")
220
+
221
+ except Exception as e:
222
+ logging.error(f"Dataset download failed: {e}")
223
+ raise
224
+
225
+ if __name__ == "__main__":
226
+ try:
227
+ download_dataset()
228
+ except Exception as e:
229
+ print(f"Error downloading dataset: {e}")
230
+ logging.error(f"Main execution failed: {e}")
231
+ raise
232
+ ```
233
  ### Advanced Usage
234
  ```python
235
  # Filter motion scenes