Медиатека

Каталог аудиокниг

Группирует главы по папкам, суммирует длительность и выводит книги в CSV или JSON.

Python Windows macOS Linux Новичок
Скачать audiobook_catalog.py
Описание

Что делает скрипт

Скрипт читает названия, автора и альбом из тегов, а длительность берёт из аудиофайла. Для каждой папки считается число глав и общее время прослушивания. Это отчёт без изменения файлов и без обращения к внешним сервисам.

Запуск

Быстрый старт

python audiobook_catalog.py --dir ~/Audiobooks --csv books.csv

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python audiobook_catalog.py --dir ~/Audiobooks
  • python audiobook_catalog.py --dir ~/Audiobooks --csv books.csv
  • python audiobook_catalog.py --dir D:\Books --json books.json
Зависимости

Что понадобится

Python 3.10+ Интерпретатор и стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
mutagen Чтение и запись тегов аудио
Windows py -m pip install mutagen
macOS python3 -m pip install mutagen
Linux python3 -m pip install mutagen
Исходник

audiobook_catalog.py

#!/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())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get media-audiobook-catalog
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Медиатека

Плейлисты, метаданные, обложки, субтитры и порядок в коллекциях.