#!/usr/bin/env python3 """Группировка фотографий по дате съёмки.""" from __future__ import annotations import argparse import os import shutil import sys from datetime import datetime from pathlib import Path try: from PIL import Image except ImportError: Image = None IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".tif", ".tiff", ".png", ".webp"} EXIF_TAGS = (36867, 36868, 306) LAYOUTS = {"year": "%Y", "month": "%Y/%m", "day": "%Y/%m/%d"} def read_taken_at(path: Path) -> datetime | None: if Image is None: return None try: with Image.open(path) as image: exif = image.getexif() for tag in EXIF_TAGS: value = exif.get(tag) if value is None: continue if isinstance(value, bytes): value = value.decode("utf-8", errors="ignore") text = str(value).strip().replace("\x00", "") for fmt in ("%Y:%m:%d %H:%M:%S", "%Y-%m-%d %H:%M:%S"): try: return datetime.strptime(text[:19], fmt) except ValueError: continue except Exception: return None return None def iter_files(root: Path): for current, dirs, names in os.walk(root): current_path = Path(current) dirs[:] = [name for name in dirs if not (current_path / name).is_symlink()] for name in names: path = current_path / name if path.is_file() and not path.is_symlink(): yield path def unique_path(path: Path, reserved: set[Path]) -> Path: if path not in reserved and not path.exists(): return path for index in range(2, 10000): candidate = path.with_name(f"{path.stem}_{index}{path.suffix}") if candidate not in reserved and not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {path}") def main() -> int: parser = argparse.ArgumentParser(description="Разложить фото по датам") parser.add_argument("--src", type=Path, required=True, help="Исходная папка") parser.add_argument("--dst", type=Path, required=True, help="Папка назначения") parser.add_argument("--by", choices=tuple(LAYOUTS), default="month", help="Группировка") parser.add_argument("--move", action="store_true", help="Переместить, а не копировать") parser.add_argument("--apply", action="store_true", help="Выполнить операцию") parser.add_argument("--yes", action="store_true", help="Не задавать вопрос при перемещении") args = parser.parse_args() if Image is None: print("Нужен Pillow: python3 -m pip install Pillow", file=sys.stderr) return 2 source = args.src.expanduser().resolve() destination = args.dst.expanduser().resolve() if not source.is_dir(): parser.error(f"Исходная папка не найдена: {source}") if destination == source or source in destination.parents: parser.error("Папка назначения не должна находиться внутри исходной") reserved: set[Path] = set() plan: list[tuple[Path, Path]] = [] fallback = 0 for path in iter_files(source): if path.suffix.lower() not in IMAGE_EXTENSIONS: continue taken = read_taken_at(path) if taken is None: fallback += 1 taken = datetime.fromtimestamp(path.stat().st_mtime) subdir = destination / taken.strftime(LAYOUTS[args.by]) candidate = unique_path(subdir / path.name, reserved) reserved.add(candidate) plan.append((path, candidate)) if not plan: print("Изображения не найдены.") return 0 for path, target in plan: print(f"{path.relative_to(source)} -> {target.relative_to(destination)}") action = "переместить" if args.move else "скопировать" if not args.apply: print(f"\nПредпросмотр: {len(plan)} файлов, дата из mtime у {fallback}. Для запуска добавьте --apply и {action}.") return 0 if args.move and not args.yes: if not sys.stdin.isatty(): parser.error("Для перемещения нужно подтверждение. Добавьте --yes") answer = input(f"Переместить файлов: {len(plan)}? Введите yes: ").strip().lower() if answer not in {"yes", "да"}: print("Отменено.") return 1 done = 0 failed = 0 for path, target in plan: try: target.parent.mkdir(parents=True, exist_ok=True) if args.move: shutil.move(str(path), str(target)) else: shutil.copy2(path, target) done += 1 except OSError as error: failed += 1 print(f"Ошибка {path}: {error}", file=sys.stderr) print(f"\nГотово: {done}, ошибок: {failed}, без EXIF: {fallback}") return 0 if failed == 0 else 1 if __name__ == "__main__": raise SystemExit(main())