from datasets import Dataset import os import json import uuid from PIL import PngImagePlugin # Define the paths arrow_file_path = "/home/yiyangai/stephenqs/datasets/mehrankazemi___re_mi/default/0.0.0/0bfa8c66979923a58bcca667181def86fb98c22a/re_mi-test-00001-of-00002.arrow" image_output_dir = "/home/yiyangai/stephenqs/datasets/mehrankazemi___re_mi/default/0.0.0/images" output_json_path = "/home/yiyangai/stephenqs/datasets/mehrankazemi___re_mi/default/0.0.0/re_mi-test-02.json" # Ensure the image output directory exists os.makedirs(image_output_dir, exist_ok=True) # Load the dataset from the arrow file dataset = Dataset.from_file(arrow_file_path) # Function to save images and update their paths def save_image_and_update_path(image_field, image_obj, record_id): # Generate a unique image filename using UUID image_filename = f"{record_id}_{image_field}.png" image_path = os.path.join(image_output_dir, image_filename) # Save the image to the local directory image_obj.save(image_path) # Return the relative path of the saved image return os.path.relpath(image_path, start=image_output_dir) # List to hold the updated dataset updated_dataset = [] # Iterate through the dataset records for record in dataset: updated_record = record.copy() # Copy the record to modify # Generate a unique UUID for the record if 'id' is missing record_id = str(uuid.uuid4()) # Process each image field for image_field in ['image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'image_6']: if isinstance(record.get(image_field), PngImagePlugin.PngImageFile): # Save the image and get the relative path relative_image_path = save_image_and_update_path(image_field, record[image_field], record_id) # Update the record with the new relative path updated_record[image_field] = relative_image_path else: # If there's no image, set the value to None updated_record[image_field] = None # Add the record ID to the record updated_record['id'] = record_id # Append the updated record to the list updated_dataset.append(updated_record) # Save the updated dataset to a JSON file with open(output_json_path, 'w') as json_file: json.dump(updated_dataset, json_file, indent=4) print(f"Images saved to {image_output_dir} and dataset saved to {output_json_path}")