#!/home/lucas/scripts/.venv/bin/python import os import sys from PIL import Image import imagehash EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tiff'} HASH_THRESHOLD = 3 # Lower = stricter matching def get_images(folder): images = [] for root, _, files in os.walk(folder): for filename in files: path = os.path.join(root, filename) if os.path.splitext(filename)[1].lower() not in EXTENSIONS: continue try: with Image.open(path) as img: width, height = img.size phash = imagehash.phash(img.convert("RGB")) images.append({ "path": path, "width": width, "height": height, "pixels": width * height, "hash": phash, "size": os.path.getsize(path) }) except Exception as e: print(f"Skipping {path}: {e}") return images def find_duplicates(images): groups = [] used = set() # Compare images with perceptual hashes for i, img in enumerate(images): if i in used: continue group = [img] used.add(i) for j in range(i + 1, len(images)): if j in used: continue if img["hash"] - images[j]["hash"] <= HASH_THRESHOLD: group.append(images[j]) used.add(j) if len(group) > 1: groups.append(group) return groups def main(): if len(sys.argv) < 2: print("Usage: python dedup_images.py DIRECTORY [--delete]") return folder = sys.argv[1] delete = "--delete" in sys.argv images = get_images(folder) print(f"Found {len(images)} images") groups = find_duplicates(images) for number, group in enumerate(groups, 1): # Keep highest resolution, then largest file group.sort( key=lambda x: (x["pixels"], x["size"]), reverse=True ) keeper = group[0] print(f"\nGroup {number}") print(f"KEEP: {keeper['path']} " f"({keeper['width']}x{keeper['height']})") for duplicate in group[1:]: print(f"{'DELETE' if delete else 'WOULD DELETE'}: " f"{duplicate['path']} " f"({duplicate['width']}x{duplicate['height']})") if delete: os.remove(duplicate["path"]) print(f"\nFound {len(groups)} duplicate groups.") if __name__ == "__main__": main()