| """ |
| This script scans a local directory for images, creates a Hugging Face Dataset, |
| and saves it locally to disk. |
| |
| It preserves the original directory structure by storing the relative path of each image. |
| The script also includes robust error handling to detect and report corrupted image files |
| before processing begins. |
| |
| Usage: |
| Run this script from the project's root directory. |
| |
| Example: |
| python scripts/save_parquet_locally.py data/selected/descriptio_style_new images/description_style_new |
| """ |
|
|
| import os |
| import glob |
| import argparse |
| import sys |
| from tqdm import tqdm |
| from PIL import Image, UnidentifiedImageError |
| from datasets import Dataset, Features, Value |
| from datasets import Image as HFImage |
|
|
| |
| |
| |
|
|
| def create_image_dataset(base_folder: str) -> Dataset or None: |
| """ |
| Scans a directory recursively for images and creates a Hugging Face Dataset. |
| |
| The dataset is constructed using a generator to minimize memory usage, making it |
| suitable for very large collections of images. Each record in the dataset |
| contains the image and its relative path from the base folder. |
| |
| Args: |
| base_folder (str): The path to the root directory containing the images. |
| |
| Returns: |
| Dataset or None: A Hugging Face Dataset object if images are found, |
| otherwise None. |
| """ |
| print(f"Scanning for all image files in '{base_folder}'...") |
|
|
| |
| all_files = glob.glob(os.path.join(base_folder, '**/*'), recursive=True) |
| image_files = [ |
| f for f in all_files if os.path.isfile(f) and |
| f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')) |
| ] |
|
|
| if not image_files: |
| print(f"Error: No image files were found in the directory '{base_folder}'.") |
| return None |
|
|
| print(f"Found {len(image_files)} images. Preparing to create the dataset...") |
|
|
| def data_generator(): |
| """ |
| A memory-efficient generator that yields image data one file at a time. |
| This approach avoids loading the entire dataset into memory. |
| """ |
| for image_path in tqdm(image_files, desc="Processing images"): |
| |
| try: |
| |
| img = Image.open(image_path) |
| |
| |
| img.verify() |
| except UnidentifiedImageError: |
| |
| |
| print(f"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!! FATAL ERROR !!!!!!!!!!!!!!!!!!!!!!!!!!!") |
| print(f"A corrupted or unidentified image file was detected.") |
| print(f"Problematic File: {image_path}") |
| print(f"Aborting script to prevent creating an incomplete dataset.") |
| print(f"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") |
| sys.exit(1) |
| except Exception as e: |
| |
| print(f"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!! FATAL ERROR !!!!!!!!!!!!!!!!!!!!!!!!!!!") |
| print(f"An unexpected error occurred while processing a file.") |
| print(f"Problematic File: {image_path}") |
| print(f"Error Details: {e}") |
| print(f"Aborting script.") |
| print(f"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") |
| sys.exit(1) |
| |
|
|
| |
| |
| relative_path = os.path.relpath(image_path, base_folder) |
| yield { |
| "image": image_path, |
| "relative_path": relative_path |
| } |
|
|
| |
| |
| features = Features({ |
| "image": HFImage(), |
| "relative_path": Value('string') |
| }) |
|
|
| |
| |
| return Dataset.from_generator( |
| data_generator, |
| features=features, |
| cache_dir=None |
| ) |
|
|
|
|
| def main(): |
| """ |
| Main function to parse command-line arguments and orchestrate the |
| dataset creation and saving process. |
| """ |
| parser = argparse.ArgumentParser( |
| description=f"Create a Hugging Face dataset from a folder of images and save it locally." |
| ) |
|
|
| parser.add_argument( |
| 'data_path', |
| type=str, |
| help="Relative path to the root folder containing the images " |
| "(e.g., 'data/selected')." |
| ) |
| parser.add_argument( |
| 'save_path', |
| type=str, |
| help="Path to save the dataset locally (e.g., 'images/my_dataset')." |
| ) |
| args = parser.parse_args() |
|
|
| if not os.path.exists(args.data_path): |
| print(f"Error: The provided path '{args.data_path}' does not exist.") |
| return |
|
|
| |
| dataset = create_image_dataset(args.data_path) |
|
|
| if dataset is None: |
| print("Dataset creation failed. Aborting.") |
| return |
|
|
| print("\nDataset structure:") |
| print(dataset) |
| print("\nExample record:") |
| print(next(iter(dataset))) |
|
|
| |
| try: |
| print(f"\nPreparing to save the dataset to '{args.save_path}'...") |
| |
| |
| |
| dataset.save_to_disk( |
| args.save_path, |
| max_shard_size="1GB", |
| ) |
| |
| print("\nSave successful!") |
| print(f"You can find your dataset at: {os.path.abspath(args.save_path)}") |
| print(f"To load it back, use: `from datasets import load_from_disk; loaded_dataset = load_from_disk('{os.path.abspath(args.save_path)}')`") |
|
|
| except Exception as e: |
| print(f"\nAn error occurred while saving the dataset: {e}") |
| import traceback |
| traceback.print_exc() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|