Write a Python script to batch convert images using Pillow with multiprocessing to use all CPU cores. It should detect corrupt images with truncated headers and move them to a quarantine folder instead of crashing.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm assembling a Python script that uses multiprocessing with Pillow to recursively convert images to JPEG, detect corrupt or truncated files via im.verify(), and move those to a quarantine folder without crashing, initializing worker globals for path handling and reporting conversion or quarantine status.
Here's a self‑contained example that will walk a source directory tree, convert every file Pillow can open to JPEG using all available CPU cores, and quarantine anything that Pillow reports as truncated/corrupt rather than letting the worker crash:
python
#!/usr/bin/env python3
import argparse
import glob
import os
import shutil
from multiprocessing import Pool, cpu_count
from PIL import Image, ImageFile, UnidentifiedImageError
# Do not silently accept truncated files
ImageFile.LOAD_TRUNCATED_IMAGES = False
# Globals initialised in each worker
SRC_ROOT = DST_ROOT = QUARANTINE_ROOT = None
def init_worker(src_root, dst_root, quarantine_root):
"""Initializer to set up globals in child processes."""
global SRC_ROOT, DST_ROOT, QUARANTINE_ROOT
SRC_ROOT = src_root
DST_ROOT = dst_root
QUARANTINE_ROOT = quarantine_root
def process_image(in_path: str):
"""
Convert a single image to JPEG. If the image is corrupt (e.g. truncated header),
move it to the quarantine directory.
"""
# Compute relative path to preserve subdirectories
rel = os.path.relpath(in_path, SRC_ROOT)
out_path = os.path.splitext(os.path.join(DST_ROOT, rel))[0] + ".jpg"
try:
# First pass to validate integrity; this will raise on truncated/corrupt data
with Image.open(in_path) as im:
im.verify()
# Reopen for actual conversion
with Image.open(in_path) as im:
im = im.convert("RGB")
os.makedirs(os.path.dirname(out_path), exist_ok=True)
im.save(out_path, "JPEG", quality=90)
return f"OK {in_path}"
except (UnidentifiedImageError, OSError, IOError) as exc:
# Anything PIL/OSError raises goes to quarantine
q_path = os.path.join(QUARANTINE_ROOT, rel)
os.makedirs(os.path.dirname(q_path), exist_ok=True)
try:
shutil.move(in_path, q_path)
return f"QUAR {in_path} -> {q_path} ({exc})"
except Exception as move_exc:
return f"FAIL {in_path} ({exc}) move failed: {move_exc}"
def main():
parser = argparse.ArgumentParser(description="Batch convert images with multiprocessing")
parser.add_argument("src", help="Source directory of images")
parser.add_argument("dst", help="Destination directory for converted images")
parser.add_argument("quarantine", help="Quarantine directory for corrupt images")
parser.add_argument("-w", "--workers", type=int, default=cpu_count(),
help="Number of worker processes (default: all cores)")
args = parser.parse_args()
# Gather candidate files
files = [p for p in glob.glob(os.path.join(args.src, "**"), recursive=True)
if os.path.isfile(p)]
os.makedirs(args.dst, exist_ok=True)
os.makedirs(args.quarantine, exist_ok=True)
with Pool(processes=args.workers,
initializer=init_worker,
initargs=(os.path.abspath(args.src),
os.path.abspath(args.dst),
os.path.abspath(args.quarantine))) as pool:
for msg in pool.imap_unordered(process_image, files, chunksize=8):
print(msg)
if __name__ == "__main__":
main()
A few notes:
ImageFile.LOAD_TRUNCATED_IMAGES is set to False so Pillow will raise on truncated files instead of trying to load them.
im.verify() is used to force Pillow to read the file header and catch corruption; the image is then reopened for conversion.
The process_image function catches UnidentifiedImageError and OSError/IOError, which are what Pillow raises on corrupt/truncated files, and moves the offending file to the quarantine directory.
The Pool initializer is used to pass the source/destination/quarantine roots to each worker without having to pickle large objects.