tools: read-only music library audit + baseline report

Records the analyser used to size up the Jellyfin music library's metadata
problems, plus the 2026-11-25 baseline so the clean-up can be measured against
it. Read-only: mutagen parses tags, nothing is written to the files.
This commit is contained in:
ziadarafat committed 2026-11-25 19:39:06 -07:00
1 parent ea52f8f4fc
commit 40edcf1f29
2 files changed
+322

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# music-audit
Read-only tag audit for the Jellyfin music library. Never writes to files.
```
python3 audit.py /mnt/MediaDisk/Music/MyLibrary > report.json
```
Needs `mutagen` (a throwaway venv is enough: `python3 -m venv /tmp/mtagenv && /tmp/mtagenv/bin/pip install mutagen`).
Run it with the same privileges that can read the library (on yveltal that means `sudo -n`).
Reports, per library: missing tag counts, albums pooling many artists, near-duplicate
files, album-name drift per artist, track-numbering errors, big albums without disc
tags, genre sprawl, unreadable files and junk-file counts.
`report-2026-11-25.json` is the baseline taken before any clean-up; rerun after the
fix and compare the same keys.
+305
View File
@@ -0,0 +1,305 @@
#!/usr/bin/env python3
"""Audit a music library's tags and report the classes of metadata problem.
Reads only tags (mutagen), never writes. Prints a JSON report to stdout so the
numbers can be reasoned about rather than eyeballed.
"""
from __future__ import annotations
import json
import os
import re
import sys
from collections import Counter, defaultdict
from difflib import SequenceMatcher
from pathlib import Path
from mutagen import File as MutagenFile
from mutagen.flac import FLAC
from mutagen.id3 import ID3
from mutagen.mp4 import MP4
from mutagen.oggopus import OggOpus
from mutagen.oggspeex import OggSpeex
from mutagen.oggvorbis import OggVorbis
AUDIO_EXT = {".mp3", ".flac", ".m4a", ".mp4", ".ogg", ".oga", ".opus", ".wav", ".aiff", ".aif", ".wv", ".ape", ".wma"}
JUNK_EXT = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".txt", ".nfo", ".log", ".cue", ".m3u", ".m3u8", ".sfv", ".pdf", ".url", ".db", ".ini", ".xml", ".json", ".html", ".htm", ".zip", ".rar", ".7z", ".srt", ".lrc"}
def first(tags, keys):
for k in keys:
v = tags.get(k)
if v is None:
continue
if isinstance(v, (list, tuple)):
if not v:
continue
v = v[0]
if hasattr(v, "text"):
v = v.text[0] if v.text else None
if v is None:
continue
s = str(v).strip()
if s:
return s
return ""
def read_tags(path: Path):
"""Return a dict of the fields this audit cares about."""
out = {"title": "", "artist": "", "albumartist": "", "album": "", "track": "",
"disc": "", "date": "", "genre": "", "length": 0.0, "bitrate": 0, "codec": "", "error": ""}
try:
f = MutagenFile(path)
except Exception as e: # unreadable/corrupt
out["error"] = f"{type(e).__name__}"
return out
if f is None:
out["error"] = "unrecognised"
return out
info = getattr(f, "info", None)
if info is not None:
out["length"] = round(float(getattr(info, "length", 0.0) or 0.0), 2)
out["bitrate"] = int(getattr(info, "bitrate", 0) or 0)
out["codec"] = type(info).__name__
tags = {}
easy = getattr(f, "tags", None)
if isinstance(f, FLAC):
tags = {k.upper(): v for k, v in (f.tags or {})}
elif isinstance(f, (OggVorbis, OggOpus, OggSpeex)):
tags = {k.upper(): v for k, v in (f.tags or {})}
elif isinstance(f, MP4):
raw = f.tags or {}
tags = {
"\xa9nam": raw.get("\xa9nam"), "\xa9ART": raw.get("\xa9ART"), "aART": raw.get("aART"),
"\xa9alb": raw.get("\xa9alb"), "trkn": raw.get("trkn"), "disk": raw.get("disk"),
"\xa9day": raw.get("\xa9day"), "\xa9gen": raw.get("\xa9gen"),
}
elif isinstance(f, ID3) or easy is not None:
try:
id3 = f if isinstance(f, ID3) else ID3(path)
except Exception:
id3 = None
if id3 is not None:
tags = {
"TIT2": id3.get("TIT2"), "TPE1": id3.get("TPE1"), "TPE2": id3.get("TPE2"),
"TALB": id3.get("TALB"), "TRCK": id3.get("TRCK"), "TPOS": id3.get("TPOS"),
"TDRC": id3.get("TDRC"), "TYER": id3.get("TYER"), "TCON": id3.get("TCON"),
}
def text_of(v):
if v is None:
return ""
if isinstance(v, (list, tuple)):
if not v:
return ""
v = v[0]
if hasattr(v, "text"):
return str(v.text[0]).strip() if v.text else ""
if isinstance(v, tuple): # mp4 trkn/disk are (n, total)
return str(v[0]) if v and v[0] else ""
return str(v).strip()
out["title"] = text_of(tags.get("TIT2") or tags.get("\xa9nam") or tags.get("TITLE"))
out["artist"] = text_of(tags.get("TPE1") or tags.get("\xa9ART") or tags.get("ARTIST"))
out["albumartist"] = text_of(tags.get("TPE2") or tags.get("aART") or tags.get("ALBUMARTIST"))
out["album"] = text_of(tags.get("TALB") or tags.get("\xa9alb") or tags.get("ALBUM"))
out["track"] = text_of(tags.get("TRCK") or tags.get("trkn") or tags.get("TRACKNUMBER"))
out["disc"] = text_of(tags.get("TPOS") or tags.get("disk") or tags.get("DISCNUMBER"))
out["date"] = text_of(tags.get("TDRC") or tags.get("TYER") or tags.get("\xa9day") or tags.get("DATE"))
out["genre"] = text_of(tags.get("TCON") or tags.get("\xa9gen") or tags.get("GENRE"))
# TRCK/TPOS are often "3/12"
for field in ("track", "disc"):
if "/" in out[field]:
out[field] = out[field].split("/")[0].strip()
return out
def norm(s: str) -> str:
s = s.lower().strip()
s = re.sub(r"[\(\[].*?[\)\]]", " ", s) # drop bracketed noise
s = re.sub(r"[^a-z0-9]+", " ", s)
return " ".join(s.split())
def similarity(a: str, b: str) -> float:
return SequenceMatcher(None, norm(a), norm(b)).ratio()
def main(root: str) -> dict:
root_p = Path(root)
files, junk, broken = [], Counter(), []
for dirpath, dirnames, filenames in os.walk(root_p):
dirnames[:] = [d for d in dirnames if not d.startswith(".")]
for fn in filenames:
p = Path(dirpath) / fn
ext = p.suffix.lower()
if ext in AUDIO_EXT:
files.append(p)
elif ext in JUNK_EXT:
junk[ext] += 1
else:
junk[ext or "(none)"] += 1
records = []
for p in files:
t = read_tags(p)
if t["error"]:
broken.append({"path": str(p.relative_to(root_p)), "error": t["error"]})
continue
t["path"] = str(p.relative_to(root_p))
t["size"] = p.stat().st_size
records.append(t)
# ---- album clusters -------------------------------------------------
albums = defaultdict(list)
for r in records:
key = (r["album"].strip().lower(), )
albums[key[0]].append(r)
mixed_artist_albums = []
for album, rs in albums.items():
if not album:
continue
artists = {r["artist"] for r in rs if r["artist"]}
albumartists = {r["albumartist"] for r in rs if r["albumartist"]}
if len(artists) > 3 or len(albumartists) > 2:
mixed_artist_albums.append({
"album": rs[0]["album"],
"tracks": len(rs),
"distinct_artists": len(artists),
"distinct_albumartists": len(albumartists),
"sample_artists": sorted(artists)[:8],
"sample_paths": [r["path"] for r in rs[:4]],
"folders": len({r["path"].rsplit("/", 1)[0] for r in rs}),
})
mixed_artist_albums.sort(key=lambda x: -x["tracks"])
# ---- missing / weak tags -------------------------------------------
missing = Counter()
for r in records:
for f in ("title", "artist", "album", "albumartist", "track", "date", "genre"):
if not r[f]:
missing[f] += 1
# ---- duplicates -----------------------------------------------------
by_sig = defaultdict(list)
for r in records:
if r["artist"] and r["title"]:
by_sig[(norm(r["artist"]), norm(r["title"]))].append(r)
dup_groups = []
for (a, t), rs in by_sig.items():
if len(rs) > 1:
durations = {round(r["length"]) for r in rs}
bitrates = {r["bitrate"] for r in rs}
dup_groups.append({
"artist": rs[0]["artist"], "title": rs[0]["title"], "copies": len(rs),
"same_length": len(durations) == 1, "distinct_bitrates": len(bitrates),
"paths": [r["path"] for r in rs[:4]],
})
dup_groups.sort(key=lambda x: -x["copies"])
# ---- album name drift per artist ------------------------------------
by_artist_album = defaultdict(set)
for r in records:
aa = r["albumartist"] or r["artist"]
if aa and r["album"]:
by_artist_album[norm(aa)].add(r["album"])
drift = []
for aa, names in by_artist_album.items():
names = sorted(names)
if len(names) < 2:
continue
used = set()
for i, a in enumerate(names):
if a in used:
continue
sims = [b for b in names if b != a and b not in used and similarity(a, b) >= 0.86 and norm(a) != norm(b)]
if sims:
used.update(sims)
drift.append({"artist": aa, "kept": a, "variants": sims})
drift.sort(key=lambda x: -len(x["variants"]))
# ---- track numbering sanity ----------------------------------------
numbering = []
for album, rs in albums.items():
if not album or len(rs) < 4:
continue
tracks = []
for r in rs:
try:
tracks.append(int(r["track"]))
except (TypeError, ValueError):
continue
if not tracks:
continue
dupes = [n for n, c in Counter(tracks).items() if c > 1]
gap = max(tracks) - len(set(tracks))
if dupes or gap > 1:
numbering.append({"album": rs[0]["album"], "tracks": len(rs),
"duplicate_numbers": sorted(dupes)[:6], "missing_numbers": gap,
"sample_path": rs[0]["path"]})
numbering.sort(key=lambda x: -x["tracks"])
# ---- multi-disc without disc tags ----------------------------------
big_no_disc = []
for album, rs in albums.items():
if not album or len(rs) < 26:
continue
with_disc = sum(1 for r in rs if r["disc"] not in ("", "0", "1"))
if with_disc == 0:
big_no_disc.append({"album": rs[0]["album"], "tracks": len(rs), "sample_path": rs[0]["path"]})
big_no_disc.sort(key=lambda x: -x["tracks"])
genres = Counter(r["genre"] for r in records if r["genre"])
# ---- the Beastie Boys question, explicitly -------------------------
beastie = [r for r in records if "beastie" in r["album"].lower() or "beastie" in r["artist"].lower()
or "beastie" in r["albumartist"].lower()]
beastie_albums = Counter(r["album"] for r in beastie)
years = Counter(r["date"][:4] for r in records if r["date"][:4].isdigit())
return {
"root": root,
"files_scanned": len(files),
"files_with_tags": len(records),
"unreadable": broken[:20],
"unreadable_count": len(broken),
"junk_files": dict(junk.most_common(10)),
"size_gib": round(sum(r["size"] for r in records) / 2**30, 1),
"distinct_album_tags": len([a for a in albums if a]),
"distinct_artists": len({r["artist"] for r in records if r["artist"]}),
"missing_tag_counts": dict(missing),
"mixed_artist_albums": mixed_artist_albums[:15],
"mixed_artist_album_count": len(mixed_artist_albums),
"duplicate_groups": dup_groups[:15],
"duplicate_group_count": len(dup_groups),
"duplicate_file_count": sum(len(v) for v in by_sig.values() if len(v) > 1),
"album_name_drift": drift[:10],
"album_name_drift_count": len(drift),
"track_numbering_problems": numbering[:10],
"track_numbering_count": len(numbering),
"big_albums_without_disc_tags": big_no_disc[:10],
"big_albums_without_disc_tags_count": len(big_no_disc),
"distinct_genres": len(genres),
"top_genres": genres.most_common(10),
"beastie_boys": {
"files": len(beastie),
"albums": beastie_albums.most_common(10),
"sample_albumartist_mismatch": [
{"path": r["path"], "album": r["album"], "albumartist": r["albumartist"],
"artist": r["artist"], "title": r["title"], "track": r["track"]}
for r in beastie[:12]
],
},
"year_span": {"earliest": min(years) if years else "", "latest": max(years) if years else "",
"files_with_year": sum(years.values())},
}
if __name__ == "__main__":
root = sys.argv[1] if len(sys.argv) > 1 else "/mnt/MediaDisk/Music/MyLibrary"
json.dump(main(root), sys.stdout, indent=1)