From 6e84ac2b6e39b8b7be7f1f72ad8f9d1a470cd0d2 Mon Sep 17 00:00:00 2001 From: jpk Date: Mon, 30 May 2022 09:12:38 +0200 Subject: [PATCH] Sort wallpapers by resolution --- wpsrt/cli.py | 27 +++++++++++++++++++++------ wpsrt/wallpapers.py | 23 +++++++++++++++-------- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/wpsrt/cli.py b/wpsrt/cli.py index 6de81bb..62769b9 100644 --- a/wpsrt/cli.py +++ b/wpsrt/cli.py @@ -2,17 +2,32 @@ from pathlib import Path import click -from .wallpapers import scan_directory +from .wallpapers import move_wallpaper, scan_directory @click.command() @click.argument( - "directory", type=click.Path(exists=True, file_okay=False, dir_okay=True) + "source", + type=click.Path(exists=True, file_okay=False, dir_okay=True), + default=Path("~/Pictures/wallpapers").expanduser(), ) -def sort(directory): - for image in scan_directory(Path(directory).expanduser()): - click.echo(image) +@click.argument( + "target", + type=click.Path(exists=False, file_okay=False, dir_okay=True), + default=Path("~/Pictures/wallpapers/by-resolution").expanduser(), +) +def sort(source: Path, target: Path): + if not target.exists(): + target.mkdir() + for wallpaper in scan_directory(source): + filename, (xres, yres) = wallpaper + if filename.is_relative_to(target): + continue + new_filename = move_wallpaper( + filename, target / f"{xres}x{yres}/{filename.name}" + ) + click.echo(new_filename) if __name__ == "__main__": - sort(None) + sort(None, None) diff --git a/wpsrt/wallpapers.py b/wpsrt/wallpapers.py index 34afe24..cead4d3 100644 --- a/wpsrt/wallpapers.py +++ b/wpsrt/wallpapers.py @@ -1,12 +1,19 @@ -import pathlib -from typing import Iterable +import os +from pathlib import Path +from typing import Iterable, Tuple from PIL import Image -def scan_directory(directory: pathlib.Path) -> Iterable[pathlib.Path]: - for filename in directory.iterdir(): - if filename.is_file(): - image = Image.open(filename) - print(image.size) - yield filename +def scan_directory(directory: Path) -> Iterable[Tuple[Path, Tuple[int, int]]]: + for root, _, filenames in os.walk(directory): + for filename in [Path(os.path.join(root, fname)) for fname in filenames]: + if filename.is_file(): + image = Image.open(filename) + yield (filename, image.size) + + +def move_wallpaper(wallpaper: Path, target: Path) -> Path: + if not target.parent.exists(): + target.parent.mkdir() + return wallpaper.rename(target)