File size: 2,117 Bytes
70f07a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from io import BytesIO
from PIL import Image
import argparse

import dask.dataframe as dd

def save_image(row, image_column, format, save_folder, print_logs):
    row_id = row.name

    try:
        byte_string = row[image_column]
        img = Image.open(BytesIO(byte_string))
        img_path = os.path.join(save_folder, f'image_{row_id}.{format}')
        img.save(img_path)
        if print_logs:
            print(f"Saving image to {img_path}")
    except Exception as e:
        return f'Error saving image for row {row_id}: {str(e)}'


def main():
    parser = argparse.ArgumentParser(description='Download and save images from a Parquet file.')
    parser.add_argument('--parquet_file',
                        type=str,
                        help='Path to the Parquet file or folder containing the images')
    parser.add_argument('--save_folder',
                        type=str,
                        help='The folder where to save the images to')
    parser.add_argument('--image_column',
                        type=str,
                        default="data",
                        required=False,
                        help='Name of the column containing image byte strings, defaults to "data"')
    parser.add_argument('--format',
                        type=str,
                        default="jpg",
                        required=False,
                        help='Image format (e.g., png, jpg), defaults to "jpgs"')
    parser.add_argument('--print_logs',
                        type=bool,
                        default=False,
                        required=False,
                        help='Flag to enable saving logs when writing images, defaults to False')
    args = parser.parse_args()

    ddf = dd.read_parquet(args.parquet_file)

    results = ddf.apply(save_image, axis=1, meta='str',
                        image_column=args.image_column,
                        save_folder=args.save_folder,
                        format=args.format,
                        print_logs=args.print_logs)
    results.compute()  


if __name__ == "__main__":
    main()