Sort wallpapers by resolution

This commit is contained in:
jpk 2022-05-30 09:12:38 +02:00
parent 6e2719f053
commit 6e84ac2b6e
2 changed files with 36 additions and 14 deletions

View File

@ -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)

View File

@ -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)