fix(audiobook_library): use raw ID3 for read/write metadata

This commit is contained in:
Lucas Vivo committed 2026-10-31 17:37:48 +01:00
1 parent 21619c45af
commit 1e9989c778
1 file changed
+100 -18
+100 -18
View File
@@ -10,12 +10,34 @@ import tempfile
import sqlite3
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from serverlibrary import *
from mutagen.easyid3 import EasyID3
from serverlibrary import CustomLogger, setup_logging, score_match_jaccard, words, AUDIO_SUFFIXES, red_tag, blue_tag, \
green_tag, AUDIO_RE_SUFFIXES
from pathlib import Path
from mutagen.id3 import ID3NoHeaderError
from mutagen.oggopus import OggOpus
from mutagen.mp4 import MP4Tags
from mutagen.mp4 import MP4
from mutagen import File
from mutagen.id3 import (
ID3,
COMM,
TIT2,
TALB,
TPE1,
TPE2,
TCON,
TCOM,
TIT1,
)
ID3_FRAME_CLASSES = {
"TIT2": TIT2,
"TALB": TALB,
"TPE1": TPE1,
"TPE2": TPE2,
"TCON": TCON,
"TCOM": TCOM,
"TIT1": TIT1,
}
logging.setLoggerClass(CustomLogger)
logger: CustomLogger = logging.getLogger(__name__) # type: ignore[assignment]
@@ -31,6 +53,16 @@ MP4_MAP = {
"description": "desc",
}
ID3_MAP = {
"artist": "TPE1",
"album": "TALB",
"title": "TIT2",
"genre": "TCON",
"composer": "TCOM",
"albumartist": "TPE2",
"grouping": "TIT1",
}
metadata_fields = [
"artist",
"album",
@@ -128,43 +160,70 @@ def get_chapters(media: Path) -> list[dict]:
return data.get("chapters", [])
def _to_str(value):
if value is None:
return ""
if hasattr(value, "text"):
value = value.text
if isinstance(value, (list, tuple)):
return "; ".join(map(str, value))
return "; ".join(str(v) for v in value)
return str(value)
def get_metadata_all(file: Path) -> dict[str, str]:
metadata = dict.fromkeys(metadata_fields, "")
try:
audio = File(file)
if audio is None or audio.tags is None:
return metadata
# MP4 / M4A / M4B
if isinstance(audio, MP4):
for field, mp4_key in MP4_MAP.items():
value = audio.tags.get(mp4_key)
# MP4/M4A/M4B
if isinstance(audio.tags, MP4Tags):
type = "mp4"
for field, tag in MP4_MAP.items():
value = audio.tags.get(tag)
if value:
metadata[field] = _to_str(value)
# Everything else (MP3, FLAC, Opus, Ogg...)
# ID3 (MP3 or mislabeled .m4b)
elif isinstance(audio.tags, ID3):
type = "id3"
for field, frame_id in ID3_MAP.items():
frame = audio.tags.get(frame_id)
if frame:
metadata[field] = _to_str(frame)
comments = audio.tags.getall("COMM")
if comments:
metadata["comment"] = _to_str(comments[0])
# Optional fallback
if not metadata["description"]:
metadata["description"] = metadata["comment"]
# FLAC / Opus / Vorbis
else:
type="other"
for field in metadata_fields:
value = audio.tags.get(field)
if value:
metadata[field] = _to_str(value)
except (ID3NoHeaderError, Exception) as error:
logger.exception(f"Error getting metadata for {file}: {error}")
except Exception:
logger.exception(f"Error getting metadata for {file}")
return metadata
def write_metadata(file, fields, values, dry_run=False):
changes = {
field.lower().replace(" ", ""): str(value)
for field, value in zip(fields, values)
}
logger.debug(f"Writing metadata for {file}: {changes}")
if dry_run:
@@ -173,18 +232,39 @@ def write_metadata(file, fields, values, dry_run=False):
try:
suffix = file.suffix.lower()
# MP3 / ID3
if suffix == ".mp3":
tags = EasyID3(file)
tags = ID3(file)
for field, value in changes.items():
if field == "comment":
tags.delall("COMM")
if value:
tags.add(
COMM(
encoding=3,
lang="eng",
desc="",
text=[value],
)
)
continue
frame_id = ID3_MAP.get(field)
if not frame_id:
continue
tags.delall(frame_id)
if value:
tags[field] = [value]
elif field in tags:
del tags[field]
frame_cls = ID3_FRAME_CLASSES[frame_id]
tags.add(frame_cls(encoding=3, text=[value]))
tags.save()
tags.save(file)
elif suffix in {".m4b", ".m4a", ".mp4"}:
# M4A / M4B / MP4
elif suffix in {".m4a", ".m4b", ".mp4"}:
tags = MP4(file)
for field, value in changes.items():
@@ -201,6 +281,7 @@ def write_metadata(file, fields, values, dry_run=False):
tags.save()
# Opus
elif suffix == ".opus":
tags = OggOpus(file)
@@ -211,6 +292,7 @@ def write_metadata(file, fields, values, dry_run=False):
tags.pop(field, None)
tags.save()
else:
logger.warning(f"Unsupported file type: {file}")