|
import os |
|
import logging |
|
import argparse |
|
from io import BytesIO |
|
from PIL import Image |
|
|
|
import dask |
|
import dask.dataframe as dd |
|
|
|
dask.config.set({"dataframe.convert-string": False}) |
|
|
|
logging.basicConfig( |
|
format="[%(asctime)s | %(name)s | %(levelname)s] %(message)s", |
|
level=logging.INFO, |
|
) |
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
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: |
|
logger.info(f"Saving image to {img_path}") |
|
except Exception as e: |
|
logger.warning(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) |
|
|
|
logger.info(f"Extracting images to folder `{args.save_folder}`") |
|
|
|
results = ddf.apply(save_image, |
|
axis=1, |
|
meta=(args.image_column, "str"), |
|
image_column=args.image_column, |
|
save_folder=args.save_folder, |
|
format=args.format, |
|
print_logs=args.print_logs) |
|
results.compute() |
|
|
|
logger.info("Image extraction complete") |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |
|
|