feat(audiobook_library): use mutagen instead

add function to fix titles and write title list to files
This commit is contained in:
Lucas Vivo committed 2026-10-30 15:11:18 +01:00
1 parent fa3b9fb265
commit f926ee03a2
1 file changed
+120 -79
+120 -79
View File
@@ -13,11 +13,25 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from serverlibrary import *
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3, ID3NoHeaderError
logging.setLoggerClass(CustomLogger)
logger: CustomLogger = logging.getLogger(__name__) # type: ignore[assignment]
metadata_fields = ["artist", "album", "composer", "comment", "genre", "grouping", "album artist", "description"]
metadata_fields = [
"artist",
"album",
"composer",
"comment",
"genre",
"grouping",
"albumartist",
"description",
"title"
]
SEP = r"\s*[-_:,.]+\s*"
series_patterns = [
rf'^(\d+){SEP}(.+)$',
@@ -104,29 +118,18 @@ def get_chapters(media: Path) -> list[dict]:
def get_metadata_all(file: Path) -> dict[str, str]:
metadata = {}
try:
result = subprocess.run(
[
"exiftool",
"-j",
str(file),
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
check=True,
)
data = json.loads(result.stdout)[0]
try:
tags = EasyID3(file)
except ID3NoHeaderError:
tags = {}
metadata = {
str(k): str(v)
for k, v in data.items()
if not k.startswith(("File", "Directory", "SourceFile"))
key: "; ".join(value) if isinstance(value, list) else str(value)
for key, value in tags.items()
}
except (OSError, subprocess.SubprocessError, json.JSONDecodeError) as error:
except Exception as error:
print(f"Error getting metadata for {file}: {error}")
for field in metadata_fields:
@@ -134,24 +137,21 @@ def get_metadata_all(file: Path) -> dict[str, str]:
return metadata
def get_metadata_fields(file, fields) -> dict:
metadata = dict.fromkeys(fields, "")
for field in fields:
cmd = ["kid3-cli", "-c", f'get "{field}"', str(file)]
try:
result = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
check=True,
)
metadata[field] = result.stdout.strip()
except (OSError, subprocess.SubprocessError) as error:
print(f"Error getting metadata for {file}: {error}")
return metadata
return metadata
def get_metadata_fields(file: Path, fields) -> dict[str, str]:
metadata = dict.fromkeys(fields, "")
try:
tags = EasyID3(file)
for field in fields:
if field in tags:
metadata[field] = tags[field][0]
except Exception as error:
print(f"Error getting metadata for {file}: {error}")
return metadata
def get_duration_ms(media: Path) -> int:
duration = subprocess.check_output(
[
@@ -170,31 +170,31 @@ def get_duration_ms(media: Path) -> int:
return int(float(duration) * 1000)
def write_metadata(file, fields, values, dry_run=False):
cmd = ["exiftool", "-overwrite_original"]
for field, value in zip(fields, values):
cmd.append(f"-{field}={value}")
cmd.append(str(file))
try:
logger.debug(f"Writing metadata for {file}")
logger.trace(f"Cmd: {' '.join(cmd)}")
if dry_run:
return
subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
check=True,
)
except (OSError, subprocess.SubprocessError) as error:
print(f"Error writing metadata for {file}: {error}")
logger.debug(f"Writing metadata for {file}")
changes = {
field.lower().replace(" ", ""): str(value)
for field, value in zip(fields, values)
}
logger.trace(f"Changes: {changes}")
if dry_run:
return
try:
try:
tags = EasyID3(file)
except ID3NoHeaderError:
tags = EasyID3()
tags.save(file)
tags = EasyID3(file)
for field, value in changes.items():
if value:
tags[field] = [value]
elif field in tags:
del tags[field]
tags.save()
except Exception as e:
logger.exception(f"Error writing metadata for {file}: {e}")
def normalize_name(name: str,series: str) -> str:
# Remove anything in (), [], {}
@@ -270,6 +270,7 @@ def get_codec_bitrate(file: Path) -> tuple[str, str]:
class Audiobook:
def __init__(self, book_path: Path, library_root_path : Path) -> None:
self.title: str|list = ""
self.metadata_original = None
self.series_num = None
self.pdf_file = None
@@ -341,6 +342,7 @@ class Audiobook:
def write_fields_from_metadata(self) -> None:
self.name = self.metadata["album"]
self.title = self.metadata["title"]
self.composer = self.metadata["composer"]
self.comment = self.metadata["comment"]
self.genre = self.metadata["genre"]
@@ -349,18 +351,19 @@ class Audiobook:
self.series = self.series.strip()
self.series_and_num = self.metadata["grouping"]
artist = self.metadata.get("artist", "").strip()
self.artist = artist or self.metadata.get("album artist")
self.artist = artist or self.metadata.get("albumartist")
self.description = self.metadata["description"]
def write_metadata_from_fields(self):
self.metadata["album"] = self.name
self.metadata["title"] = self.title
self.metadata["composer"] = self.composer
self.metadata["genre"] = self.genre
self.metadata["grouping"] = self.series_and_num
self.metadata["comment"] = self.comment
self.metadata["description"] = self.description
self.metadata["artist"] = self.artist
self.metadata["album artist"] = self.artist
self.metadata["albumartist"] = self.artist
def extract_track_number(self, file: Path) -> int:
stem = file.stem
@@ -489,15 +492,16 @@ class Audiobook:
else:
logger.debug(f"Artist {artist} matches file metadata for {self.name}")
def fix_artist_from_path(self):
def fix_artist_from_path(self, force_artist_from_path):
rel_path = self.bookPath.relative_to(self.library_root_path).parts
if len(rel_path) < 2:
logger.trace(f"Artist not visible in folder structure: {rel_path}")
return
if not self.artist:
if self.artist == rel_path[0]:
return
if not self.artist or force_artist_from_path:
self.changed = True
self.artist = rel_path[0]
logger.info(f"[Updated] artist {self.artist} found in path for {self.bookPath}")
@@ -612,13 +616,20 @@ class Audiobook:
filename = f"{desired_name_stem}{file.suffix.lower()}"
else:
filename = file.name
new_file = file.rename(desired_path / filename)
new_file = desired_path / filename
if file == new_file:
continue
logger.trace(f"Moving {file} to {new_file}")
new_file = file.rename(new_file)
if file == self.epub_file:
self.epub_file = new_file
elif file == self.pdf_file:
self.pdf_file = new_file
if self.bookPath != desired_path:
logger.debug(f"Moving {self.bookPath} to {desired_path}")
remaining = list(self.bookPath.iterdir())
if not remaining:
self.bookPath.rmdir()
@@ -629,7 +640,6 @@ class Audiobook:
self.bookPath = desired_path
self.files = sorted(self.files, key=self.extract_track_number)
self.firstFile = self.get_first_file()
logger.debug(f"Moving {self.bookPath} to {desired_path}")
def generate_dir_from_metadata(self):
composer =""
@@ -645,8 +655,9 @@ class Audiobook:
series = self.series_and_num.split("#")
number = f"{series[1]} - "
series = series[0].rstrip()
desired_path = self.library_root_path / self.artist / series / f"{number}{name}"
desired_path = self.library_root_path / self.artist.replace("/", "_") / series.replace("/", "_") / f"{number}{name}".replace("/", "_")
desired_name_stem = self.artist + " - " + self.name + composer + self.bookPath.suffix
desired_name_stem = desired_name_stem.replace("/", "_")
return desired_path, desired_name_stem
def create_m4b_from_book(self, creat_m4b_no_delete: bool = False) -> None:
@@ -822,17 +833,36 @@ class Audiobook:
return
self.write_metadata_from_fields()
if keys is None:
keys = [
key
for key, value in self.metadata.items()
if self.metadata_original.get(key) != value
]
keys = []
for key, value in self.metadata.items():
if self.metadata_original.get(key) != value:
if not isinstance(value,list):
keys.append(key)
self.metadata_original = self.metadata.copy()
values = [self.metadata[key] for key in keys]
for file in self.files:
write_metadata(file, keys, values, dry_run)
if (not keys or not values) and self.metadata_original.get("title") != self.title:
logger.trace(f"Nothing to write to file for {self.name}")
return
if keys:
for file in self.files:
write_metadata(file, keys, values, dry_run)
if isinstance( self.title, list ):
for title,file in zip(self.title, self.files):
write_metadata(file, ["title"], [title], dry_run)
self.changed = False
def fix_title(self):
if not self.title:
if self.singleFile:
self.title = self.name
else:
self.title = []
padding = len(str(len(self.files)))
for idx, file in enumerate(self.files):
self.title.append(f"{self.name} - {idx+1:0{padding}d}")
class AudiobookLibrary:
def __init__(
self, library_path: Path, sql_database_path: Path, dry_run: bool, path_filter:str="", logfilename: str = "audiobook_library.log"
@@ -1074,10 +1104,10 @@ class AudiobookLibrary:
desired_path, desired_name = book.generate_dir_from_metadata()
book.move(desired_path, desired_name, dry_run)
def fix_artists(self):
def fix_artists(self,force_artist_from_path=False):
for book in self.audiobooks:
book.fix_artist_from_comment()
book.fix_artist_from_path()
book.fix_artist_from_path(force_artist_from_path)
def fix_composers(self):
for book in self.audiobooks:
@@ -1099,6 +1129,10 @@ class AudiobookLibrary:
for book in self.audiobooks:
book.fix_genre()
def fix_titles(self):
for book in self.audiobooks:
book.fix_title()
def fix_series(self):
for book in self.audiobooks:
book.fix_series()
@@ -1190,6 +1224,12 @@ def main():
action="store_true",
help="Fix the Database",
)
parser.add_argument(
"-fa",
"--force-artist-from-path",
action="store_true",
help="Force overwrite Artist from Path, only use if Path is correct",
)
parser.add_argument(
"-m",
"--move",
@@ -1220,12 +1260,13 @@ def main():
library.sql_database_instance.init()
library.fix_artist_dir()
library.fix_artists()
library.fix_artists(args.force_artist_from_path)
library.fix_composers()
library.fix_series()
library.fix_names()
library.fix_comments()
library.fix_genres()
library.fix_titles()
if args.create_m4b:
library.create_m4b_from_dir(
@@ -1245,7 +1286,7 @@ def main():
if args.move:
library.create_structured_directories(args.dry_run)
print("Fin")
logger.info("All Operations completed successfully")
if __name__ == "__main__":