interleaved-umm / scripts /save_arrow_locally.py
Caesarrr's picture
feat: add save and restore scripts for image data
52d11c0
"""
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()