#!/usr/bin/env python3 """Собирает каталог музыки по тегам.""" from __future__ import annotations import argparse import csv import json from pathlib import Path from mutagen import File as MutagenFile AUDIO_EXTENSIONS = {".mp3", ".flac", ".m4a", ".ogg", ".opus", ".wav"} def first(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}") rows = [] incomplete = 0 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 tags = audio.tags or {} artist = first(tags, "artist") album = first(tags, "album") title = first(tags, "title") if not artist or not album or not title: incomplete += 1 duration = float(getattr(audio.info, "length", 0.0)) rows.append( { "artist": artist, "album": album, "title": title, "track": first(tags, "track"), "year": first(tags, "date")[:4], "genre": first(tags, "genre"), "duration": round(duration, 1), "file": str(path.relative_to(root)), } ) if not rows: print("Аудиофайлы не найдены.") return 1 for row in rows[:25]: print(f"{row['artist'] or '?'} - {row['album'] or '?'} - {row['title'] or '?'}") if len(rows) > 25: print(f"И ещё {len(rows) - 25} записей.") 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=list(rows[0])) 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)}, без части тегов: {incomplete}") return 0 if __name__ == "__main__": raise SystemExit(main())