music-audit: fix-years sets date from the release group's first release
Keep the pressing date in originaldate so libraries still sort and display by first release. Sweeps a whole library, not just the albums we re-tagged.
This commit is contained in:
1 parent
ddc7d806b1
commit
936f8a323e
1 file changed
+131
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Set each album's year back to its original release, not the CD reissue.
|
||||
|
||||
mb-tag writes the date of the MusicBrainz release it matched, which for most
|
||||
catalogue albums is a later CD pressing: a 1973 record ends up filed as 1988.
|
||||
Music libraries sort and display by this year, so the release group's
|
||||
first-release-date is what belongs in `date`; the pressing date is kept in
|
||||
`originaldate` so nothing is lost.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
from mutagen import File
|
||||
|
||||
UA = "Dogebot/1.0 ( https://github.com/RustyRaptor/doge_cogs )"
|
||||
MB = "https://musicbrainz.org/ws/2/release/"
|
||||
AUDIO = (".flac", ".mp3", ".m4a", ".ogg", ".opus")
|
||||
CACHE = "/var/lib/beets/mb-release-cache.json"
|
||||
|
||||
|
||||
def get(url: str) -> dict:
|
||||
for attempt in range(4):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
||||
with urllib.request.urlopen(req, timeout=40) as r:
|
||||
return json.loads(r.read().decode())
|
||||
except Exception:
|
||||
if attempt == 3:
|
||||
return {}
|
||||
time.sleep(2 * (attempt + 1))
|
||||
return {}
|
||||
|
||||
|
||||
def val(tags, *names) -> str:
|
||||
for n in names:
|
||||
v = tags.get(n)
|
||||
if v is None:
|
||||
continue
|
||||
if isinstance(v, list):
|
||||
v = v[0] if v else ""
|
||||
s = str(v).strip()
|
||||
if s:
|
||||
return s
|
||||
return ""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
apply = "--write" in sys.argv
|
||||
cache = json.load(open(CACHE)) if os.path.exists(CACHE) else {}
|
||||
|
||||
folders = set()
|
||||
# Every album folder that carries a MusicBrainz id, not just the ones the
|
||||
# resolver touched: albums tagged by beets or by hand need the same fix.
|
||||
roots = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
for root in roots or ["/mnt/MediaDisk/Music/MyLibrary"]:
|
||||
for dirpath, _dirnames, filenames in os.walk(root):
|
||||
if any(f.lower().endswith(AUDIO) for f in filenames):
|
||||
folders.add(dirpath)
|
||||
|
||||
fixed = checked = 0
|
||||
for folder in sorted(folders):
|
||||
files = [f for f in sorted(os.listdir(folder)) if f.lower().endswith(AUDIO)]
|
||||
if not files:
|
||||
continue
|
||||
sample = os.path.join(folder, files[0])
|
||||
try:
|
||||
tags = File(sample).tags or {}
|
||||
except Exception:
|
||||
continue
|
||||
rel_id = val(tags, "musicbrainz_albumid", "TXXX:MusicBrainz Album Id")
|
||||
if not rel_id:
|
||||
continue
|
||||
if rel_id not in cache:
|
||||
rel = get("%s%s?inc=release-groups&fmt=json" % (MB, rel_id))
|
||||
time.sleep(1.1)
|
||||
rg = (rel.get("release-group") or {}).get("first-release-date") or ""
|
||||
cache[rel_id] = {"release_date": rel.get("date") or "", "first": rg}
|
||||
json.dump(cache, open(CACHE, "w"), indent=1)
|
||||
info = cache[rel_id]
|
||||
first = info.get("first") or ""
|
||||
if not first:
|
||||
continue
|
||||
checked += 1
|
||||
want = first[:4]
|
||||
for f in files:
|
||||
path = os.path.join(folder, f)
|
||||
try:
|
||||
t = File(path)
|
||||
tg = t.tags
|
||||
if tg is None:
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
cur = val(tg, "date", "TDRC", "year", "TXXX:YEAR")[:4]
|
||||
if cur == want:
|
||||
continue
|
||||
if apply:
|
||||
low = path.lower()
|
||||
# Vorbis comments (flac/ogg/opus) are dict-like; MP3 needs ID3 frames.
|
||||
if low.endswith((".flac", ".ogg", ".opus", ".m4a")):
|
||||
try:
|
||||
tg["date"] = [want]
|
||||
if info.get("release_date"):
|
||||
tg["originaldate"] = [info["release_date"]]
|
||||
t.save()
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
if True:
|
||||
from mutagen.id3 import TDRC, TXXX
|
||||
|
||||
tg.setall("TDRC", [TDRC(encoding=3, text=[want])])
|
||||
if info.get("release_date"):
|
||||
tg.setall("TXXX:ORIGINALDATE",
|
||||
[TXXX(encoding=3, desc="ORIGINALDATE", text=[info["release_date"]])])
|
||||
t.save()
|
||||
fixed += 1
|
||||
print(" %-46s date %s -> %s" % (os.path.basename(folder)[:46], cur or "?", want))
|
||||
|
||||
print("\n%d albums checked, %d files %s" % (checked, fixed, "re-dated" if apply else "would change (dry run)"))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user