| from pathlib import Path |
| import hashlib |
|
|
| FOLDERS = [ |
| Path("./data/appropriate"), |
| Path("./data/inappropriate"), |
| ] |
|
|
| EXTENSIONS = {".png", ".webp"} |
|
|
| def file_hash(path, chunk_size=8192): |
| h = hashlib.sha256() |
| with open(path, "rb") as f: |
| while chunk := f.read(chunk_size): |
| h.update(chunk) |
| return h.hexdigest() |
|
|
| def get_duplicate_name(folder, suffix): |
| counter = 1 |
| while True: |
| candidate = folder / f"duplicate_{counter}{suffix}" |
| if not candidate.exists(): |
| return candidate |
| counter += 1 |
|
|
| def process_folder(folder: Path): |
| if not folder.is_dir(): |
| print(f"Skipping invalid folder: {folder}") |
| return |
|
|
| files = sorted( |
| [f for f in folder.iterdir() if f.is_file() and f.suffix.lower() in EXTENSIONS], |
| key=lambda f: f.name.lower() |
| ) |
|
|
| seen_hashes = {} |
| for f in files: |
| h = file_hash(f) |
| if h in seen_hashes: |
| print("found duplicate") |
| f.unlink() |
| else: |
| seen_hashes[h] = f |
|
|
| files = sorted( |
| [f for f in folder.iterdir() if f.is_file() and f.suffix.lower() in EXTENSIONS], |
| key=lambda f: f.name.lower() |
| ) |
|
|
| for f in files: |
| if f.stem.isdigit(): |
| new_path = get_duplicate_name(folder, f.suffix.lower()) |
| f.rename(new_path) |
|
|
| files = sorted( |
| [f for f in folder.iterdir() if f.is_file() and f.suffix.lower() in EXTENSIONS], |
| key=lambda f: f.name.lower() |
| ) |
|
|
| for i, f in enumerate(files, start=1): |
| new_path = folder / f"{i}{f.suffix.lower()}" |
| f.rename(new_path) |
|
|
| print(f"{folder}: {len(files)} files kept and renamed") |
|
|
| for folder in FOLDERS: |
| process_folder(folder) |
|
|