from pathlib import Path from PIL import Image def unique_output_path(path: Path) -> Path: if not path.exists(): return path stem, suffix = path.stem, path.suffix n = 1 while True: candidate = path.with_name(f"{stem}_{n}{suffix}") if not candidate.exists(): return candidate n += 1 def convert_image(path: Path, max_width: int, quality: int = 85) -> Path: """Resize (only if wider than max_width) and convert an image to WebP, deleting the original. Returns the new file path. Raises on failure — caller decides how to handle/log.""" with Image.open(path) as img: if img.width > max_width: ratio = max_width / img.width new_size = (max_width, round(img.height * ratio)) img = img.resize(new_size, Image.LANCZOS) output = unique_output_path(path.with_suffix(".webp")) img.save(output, "WEBP", quality=quality, method=6) path.unlink() return output