Files
dotfiles/scripts/wallpaper-sort.py

70 lines
2.0 KiB
Python

"""Split a wallpaper folder into light/ and dark/ by perceived brightness.
wallpaper-sort SRC DEST [--threshold 0.45]
Copies every image in SRC into DEST/light or DEST/dark (hard-linking when on the
same filesystem). Brightness is the mean Rec. 709 luma of a 64x64 thumbnail; the
threshold is a 0-1 cut-off. Re-running only adds new files and moves any whose
bucket changed, so it is safe to point at a growing folder.
"""
import argparse
import os
import shutil
from pathlib import Path
from PIL import Image, ImageStat
EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif", ".avif"}
def luma(path: Path) -> float:
with Image.open(path) as im:
im.seek(0)
im = im.convert("RGB")
im.thumbnail((64, 64))
r, g, b = ImageStat.Stat(im).mean
return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255
def place(src: Path, dst: Path) -> None:
if dst.exists():
return
try:
os.link(src, dst)
except OSError:
shutil.copy2(src, dst)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("src", type=Path)
ap.add_argument("dest", type=Path)
ap.add_argument("--threshold", type=float, default=0.45)
args = ap.parse_args()
light, dark = args.dest / "light", args.dest / "dark"
light.mkdir(parents=True, exist_ok=True)
dark.mkdir(parents=True, exist_ok=True)
counts = {"light": 0, "dark": 0, "skipped": 0}
for f in sorted(args.src.iterdir()):
if f.suffix.lower() not in EXTS or not f.is_file():
continue
try:
value = luma(f)
except Exception as exc:
print(f"skip {f.name}: {exc}")
counts["skipped"] += 1
continue
bucket, other = (light, dark) if value >= args.threshold else (dark, light)
(other / f.name).unlink(missing_ok=True)
place(f, bucket / f.name)
counts[bucket.name] += 1
print(f"{bucket.name:5} {value:.2f} {f.name}")
print(f"{args.dest}: {counts}")
if __name__ == "__main__":
main()