File size: 6,897 Bytes
52d11c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
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  # Rename to HFImage to avoid conflict with PIL.Image

# =================================================================
# 1. Dataset Creation and Saving Logic
# =================================================================

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}'...")

    # Recursively find all files and filter for common image extensions.
    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"):
            # --- Robustness Check: Validate each image file before adding it ---
            try:
                # Open the image file with PIL.
                img = Image.open(image_path)
                # `verify()` checks for file integrity. This is the most likely
                # place to catch corrupted or malformed image files.
                img.verify()
            except UnidentifiedImageError:
                # This specific error means PIL cannot identify the image format,
                # often indicating file corruption.
                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)  # Exit the script immediately.
            except Exception as e:
                # Catch any other unexpected errors during file processing.
                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)  # Exit the script immediately.
            # --------------------------------------------------------------------

            # Calculate the relative path from the base folder. This is crucial
            # for reconstructing the original directory structure later.
            relative_path = os.path.relpath(image_path, base_folder)
            yield {
                "image": image_path,
                "relative_path": relative_path
            }

    # Define the dataset's structure (schema).
    # "image" will be of type Image, and "relative_path" will be a string.
    features = Features({
        "image": HFImage(),
        "relative_path": Value('string')
    })

    # Create the dataset from the generator. `cache_dir=None` is often used
    # with generators to avoid creating a large cache file locally.
    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

    # 1. Create the dataset from the local image files.
    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)))

    # 2. Save the dataset to the local disk.
    try:
        print(f"\nPreparing to save the dataset to '{args.save_path}'...")
        
        # This command saves the dataset. It will create the directory if it doesn't exist.
        # The dataset is saved in the Arrow format by default.
        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()