#!/usr/bin/env python3 """Собирает каталог аудиокниг по папкам.""" from __future__ import annotations import argparse import csv import json from collections import defaultdict from pathlib import Path from mutagen import File as MutagenFile AUDIO_EXTENSIONS = {".mp3", ".m4a", ".m4b", ".flac", ".ogg", ".opus"} def tag(tags, key: str) -> str: value = tags.get(key) if isinstance(value, list): value = value[0] if value else "" return "" if value is None else str(value).strip() def main() -> int: parser = argparse.ArgumentParser(description="Каталог аудиокниг") parser.add_argument("--dir", type=Path, required=True, help="Папка с аудиокнигами") parser.add_argument("--csv", type=Path, help="Сохранить CSV") parser.add_argument("--json", type=Path, help="Сохранить JSON") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") books: dict[Path, dict] = defaultdict(lambda: {"chapters": 0, "seconds": 0.0, "author": "", "title": ""}) for path in sorted(root.rglob("*")): if not path.is_file() or path.suffix.lower() not in AUDIO_EXTENSIONS: continue try: audio = MutagenFile(path, easy=True) except Exception as error: print(f"Не прочитано: {path}: {error}") continue if audio is None: continue folder = path.parent book = books[folder] book["chapters"] += 1 book["seconds"] += float(getattr(audio.info, "length", 0.0)) tags = audio.tags or {} if not book["title"]: book["title"] = tag(tags, "album") or folder.name if not book["author"]: book["author"] = tag(tags, "albumartist") or tag(tags, "artist") if not books: print("Аудиокниги не найдены.") return 1 rows = [] for folder, book in sorted(books.items()): hours = book["seconds"] / 3600 rows.append( { "author": book["author"], "title": book["title"], "chapters": book["chapters"], "hours": round(hours, 2), "folder": str(folder.relative_to(root)), } ) print(f"{book['author'] or '?'} - {book['title']}: {book['chapters']} глав, {hours:.1f} ч") if args.csv: target = args.csv.expanduser() target.parent.mkdir(parents=True, exist_ok=True) with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["author", "title", "chapters", "hours", "folder"]) writer.writeheader() writer.writerows(rows) print(f"CSV: {target}") if args.json: target = args.json.expanduser() target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"JSON: {target}") print(f"Книг: {len(rows)}") return 0 if __name__ == "__main__": raise SystemExit(main())