|
from datasets import Dataset |
|
import os |
|
import json |
|
import uuid |
|
from PIL import PngImagePlugin |
|
|
|
|
|
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" |
|
|
|
|
|
os.makedirs(image_output_dir, exist_ok=True) |
|
|
|
|
|
dataset = Dataset.from_file(arrow_file_path) |
|
|
|
|
|
def save_image_and_update_path(image_field, image_obj, record_id): |
|
|
|
image_filename = f"{record_id}_{image_field}.png" |
|
image_path = os.path.join(image_output_dir, image_filename) |
|
|
|
|
|
image_obj.save(image_path) |
|
|
|
|
|
return os.path.relpath(image_path, start=image_output_dir) |
|
|
|
|
|
updated_dataset = [] |
|
|
|
|
|
for record in dataset: |
|
updated_record = record.copy() |
|
|
|
|
|
record_id = str(uuid.uuid4()) |
|
|
|
|
|
for image_field in ['image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'image_6']: |
|
if isinstance(record.get(image_field), PngImagePlugin.PngImageFile): |
|
|
|
relative_image_path = save_image_and_update_path(image_field, record[image_field], record_id) |
|
|
|
updated_record[image_field] = relative_image_path |
|
else: |
|
|
|
updated_record[image_field] = None |
|
|
|
|
|
updated_record['id'] = record_id |
|
|
|
|
|
updated_dataset.append(updated_record) |
|
|
|
|
|
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}") |
|
|