forked from trav/lintunes
v0.16.0: the file already told you
Two real failures from the first hour of round 45, both fixed by treating the file itself as evidence. "B. Clem - Zuuso [1025657891]" fingerprinted fine and matched nothing. Checked before building: AcoustID returns zero results, a MusicBrainz text search for "Zuuso" returns zero, iTunes returns zero. The track is in no metadata service on earth, so no smarter lookup could have answered it — but its filename said exactly what it was. New filename_tags.py reads that, validated against all 474 files in the untagged folder rather than invented examples: it strips yt-dlp ids, drops "(Official Video)" noise, splits Artist - Title, reads a leading 1-04, and falls back to the iTunes tree. It is careful about what it removes — an 11-char trailing token counts as a YouTube id only if it carries a digit, an underscore or flipping case, or "Cold Draft-Underground" loses a word, and a hyphen only splits when it has spaces around it so Jay-Z survives. A guess says it is one: candidates carry a source, and the dialog quotes a confidence only for real fingerprint matches. The file now ranks lookup results too, which fixes the Alhambra case: token overlap (words double, bare numbers single), a duration bucket against the recording lengths AcoustID returns, and a filename year that predates what the database knows. Live also stops counting as a demerit — it was lumped in with Compilation and buried a live album for a file whose name said "Live At The Alhambra". That track now proposes the right album with year 1961 instead of a compilation with 2002. The year genuinely needed the filename: MusicBrainz's own first-release-date for "Ahmad Jamal's Alhambra" is 2002, because its three original 1961 pressings are stored undated. The obvious fix of a second MusicBrainz call returns the same wrong answer. Not done on purpose: trav rejected "never propose a shorter title" — truncating is wanted, since the garbage is usually the part being dropped. Claude-Session: https://claude.ai/code/session_01NsiFHdyVg1UhBSxDJfTNRm
This commit is contained in:
+160
-26
@@ -12,13 +12,17 @@ AcoustID application key is user-supplied via Preferences (the Last.fm
|
||||
precedent); registration is free at https://acoustid.org/new-application.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from PyQt6.QtCore import QObject, pyqtSignal
|
||||
|
||||
from lintunes import filename_tags
|
||||
|
||||
|
||||
ACOUSTID_LOOKUP_URL = "https://api.acoustid.org/v2/lookup"
|
||||
LOOKUP_META = "recordings releasegroups releases tracks compress"
|
||||
@@ -33,6 +37,10 @@ class IdentifyCandidate:
|
||||
"""One proposed identification. Field names match Track/tagging so
|
||||
``fields()`` can go straight into ``LibraryManager.edit_track_fields``."""
|
||||
score: float
|
||||
# "acoustid" (a fingerprint match, so ``score`` is a real confidence) or
|
||||
# "filename" (a guess read off the file's own name — no confidence to
|
||||
# quote, and the dialog says so rather than implying one).
|
||||
source: str = "acoustid"
|
||||
name: str | None = None
|
||||
artist: str | None = None
|
||||
album_artist: str | None = None
|
||||
@@ -45,7 +53,7 @@ class IdentifyCandidate:
|
||||
def fields(self) -> dict:
|
||||
"""Proposed edits keyed by LinTunes field names, Nones omitted."""
|
||||
return {k: v for k, v in asdict(self).items()
|
||||
if k != "score" and v is not None}
|
||||
if k not in ("score", "source") and v is not None}
|
||||
|
||||
|
||||
# ---- pure parsing/ranking helpers (offline-testable) ----
|
||||
@@ -78,18 +86,75 @@ def _oldest_year(releasegroup: dict) -> int | None:
|
||||
return min(years) if years else None
|
||||
|
||||
|
||||
# Secondary types that mean "this is not the album the song came from".
|
||||
# Live is deliberately absent: a live album is a real album, and demoting it
|
||||
# buried "Ahmad Jamal's Alhambra" under a compilation for a file whose own
|
||||
# name said "Live At The Alhambra".
|
||||
_DEMOTED_SECONDARY = {"compilation", "interview", "remix", "dj-mix",
|
||||
"mixtape/street", "demo", "audiobook"}
|
||||
|
||||
|
||||
def _releasegroup_sort_key(releasegroup: dict) -> tuple:
|
||||
"""Rank a release group for the default proposal: the earliest proper
|
||||
studio Album first, then EPs/Singles, then Compilations/Live/etc."""
|
||||
"""Rank a release group for the default proposal: a proper album first,
|
||||
then EPs/Singles, with compilations and the like pushed down."""
|
||||
rg_type = releasegroup.get("type") or ""
|
||||
secondary = releasegroup.get("secondarytypes") or []
|
||||
if not secondary:
|
||||
rank = {"Album": 0, "EP": 1, "Single": 2}.get(rg_type, 4)
|
||||
else:
|
||||
rank = 3 if rg_type == "Album" else 4
|
||||
rank = {"Album": 0, "EP": 1, "Single": 2}.get(rg_type, 4)
|
||||
if any((s or "").casefold() in _DEMOTED_SECONDARY for s in secondary):
|
||||
rank += 3
|
||||
return (rank, _oldest_year(releasegroup) or 9999)
|
||||
|
||||
|
||||
_TOKEN = re.compile(r"[^\W\d_]+|\d+", re.UNICODE)
|
||||
_STOPWORDS = {"the", "a", "an", "of", "and", "in", "at", "on", "live",
|
||||
"feat", "ft", "remastered", "version", "mix", "edit"}
|
||||
|
||||
|
||||
def _tokens(text: str) -> set:
|
||||
"""Comparable words from a title/album/filename."""
|
||||
return {t.casefold() for t in _TOKEN.findall(text or "")
|
||||
if len(t) > 1 and t.casefold() not in _STOPWORDS}
|
||||
|
||||
|
||||
def _duration_bucket(recording: dict, duration: float | None) -> int:
|
||||
"""How well a recording's length matches the file's, coarsely.
|
||||
|
||||
AcoustID often returns several recordings of the same song — a studio
|
||||
take, a live take, an edit — and their lengths are what tell them apart.
|
||||
Buckets rather than raw difference so a second or two never outweighs the
|
||||
other evidence, but a clearly different take sinks.
|
||||
"""
|
||||
other = recording.get("duration")
|
||||
if duration is None or not isinstance(other, (int, float)):
|
||||
return 1 # unknown: behind an exact match, ahead of a bad one
|
||||
diff = abs(other - duration)
|
||||
if diff <= 1.5:
|
||||
return 0
|
||||
if diff <= 4:
|
||||
return 1
|
||||
if diff <= 12:
|
||||
return 2
|
||||
return 3
|
||||
|
||||
|
||||
def _hint_overlap(hint_tokens: set, candidate: IdentifyCandidate) -> int:
|
||||
"""How much a candidate echoes what the file already claims to be.
|
||||
|
||||
The distinctive words in "Snowfall (Live At The Alhambra_1961)" —
|
||||
*snowfall*, *alhambra*, *1961* — are the best evidence available about
|
||||
which of eight plausible releases this actually is, and ignoring them was
|
||||
why a compilation could outrank the album named in the filename.
|
||||
"""
|
||||
if not hint_tokens:
|
||||
return 0
|
||||
text = " ".join(p for p in (candidate.name, candidate.artist,
|
||||
candidate.album_artist, candidate.album) if p)
|
||||
# A word like "alhambra" names a release; a bare number like "1961" turns
|
||||
# up in every compilation spanning that year, so it counts for less.
|
||||
return sum(2 if not token.isdigit() else 1
|
||||
for token in hint_tokens & _tokens(text))
|
||||
|
||||
|
||||
def _pick_release(releasegroup: dict) -> dict | None:
|
||||
"""Earliest dated release that carries mediums (track positions); falls
|
||||
back to the earliest dated one, then the first."""
|
||||
@@ -126,7 +191,8 @@ def _track_position(release: dict | None) -> tuple[int | None, int | None,
|
||||
|
||||
|
||||
def parse_lookup(payload: dict, threshold: float = SCORE_THRESHOLD,
|
||||
limit: int = MAX_CANDIDATES) -> list[IdentifyCandidate]:
|
||||
limit: int = MAX_CANDIDATES, hint: str = "",
|
||||
duration: float | None = None) -> list[IdentifyCandidate]:
|
||||
"""Turn an AcoustID lookup response into ranked candidates.
|
||||
|
||||
One candidate per release group of each matched recording, so the
|
||||
@@ -135,16 +201,23 @@ def parse_lookup(payload: dict, threshold: float = SCORE_THRESHOLD,
|
||||
the minimum across all its release groups' releases — even when the
|
||||
proposed album is a later compilation: years sort by when the song first
|
||||
came out, not by which pressing this file happens to be from.
|
||||
|
||||
``hint`` is whatever the file already claims to be (its tags and its
|
||||
filename). It never invents a candidate, but it breaks ties: a release
|
||||
whose words echo the hint outranks one that doesn't, and a year named in
|
||||
the hint wins when it predates anything the database knows — MusicBrainz
|
||||
often holds only a reissue's date, with the original pressing undated.
|
||||
"""
|
||||
candidates = []
|
||||
hint_tokens = _tokens(hint)
|
||||
hint_year = _single_year(hint)
|
||||
scored = []
|
||||
seen = set()
|
||||
results = sorted(payload.get("results", []),
|
||||
key=lambda r: r.get("score", 0), reverse=True)
|
||||
for result in results:
|
||||
for result in payload.get("results", []):
|
||||
score = result.get("score", 0)
|
||||
if score < threshold:
|
||||
continue
|
||||
for recording in result.get("recordings", []):
|
||||
length = _duration_bucket(recording, duration)
|
||||
title = recording.get("title")
|
||||
artist = _join_artists(recording.get("artists"))
|
||||
groups = sorted(recording.get("releasegroups") or [],
|
||||
@@ -152,10 +225,16 @@ def parse_lookup(payload: dict, threshold: float = SCORE_THRESHOLD,
|
||||
original_years = [y for rg in groups
|
||||
if (y := _oldest_year(rg)) is not None]
|
||||
original_year = min(original_years) if original_years else None
|
||||
if hint_year is not None and (original_year is None
|
||||
or hint_year < original_year):
|
||||
original_year = hint_year
|
||||
if not groups:
|
||||
if title:
|
||||
candidates.append(IdentifyCandidate(
|
||||
score=score, name=title, artist=artist))
|
||||
bare = IdentifyCandidate(score=score, name=title,
|
||||
artist=artist, year=hint_year)
|
||||
scored.append(((-round(score, 2), length,
|
||||
-_hint_overlap(hint_tokens, bare),
|
||||
4, 9999), bare))
|
||||
continue
|
||||
for releasegroup in groups:
|
||||
album = releasegroup.get("title")
|
||||
@@ -165,7 +244,7 @@ def parse_lookup(payload: dict, threshold: float = SCORE_THRESHOLD,
|
||||
seen.add(key)
|
||||
number, count, disc = _track_position(
|
||||
_pick_release(releasegroup))
|
||||
candidates.append(IdentifyCandidate(
|
||||
candidate = IdentifyCandidate(
|
||||
score=score,
|
||||
name=title,
|
||||
artist=artist,
|
||||
@@ -175,8 +254,47 @@ def parse_lookup(payload: dict, threshold: float = SCORE_THRESHOLD,
|
||||
track_number=number,
|
||||
track_count=count,
|
||||
disc_number=disc,
|
||||
))
|
||||
return candidates[:limit]
|
||||
)
|
||||
rank, rg_year = _releasegroup_sort_key(releasegroup)
|
||||
scored.append(((-round(score, 2), length,
|
||||
-_hint_overlap(hint_tokens, candidate),
|
||||
rank, rg_year), candidate))
|
||||
scored.sort(key=lambda pair: pair[0])
|
||||
return [candidate for _key, candidate in scored][:limit]
|
||||
|
||||
|
||||
def _single_year(text: str) -> int | None:
|
||||
"""The year a string names, when it names exactly one (so a range like
|
||||
"1958-62" is never mistaken for a release year)."""
|
||||
return filename_tags.year_in(text or "")
|
||||
|
||||
|
||||
def hint_for(track) -> str:
|
||||
"""What a track already claims to be — its tags plus its filename. Used
|
||||
to rank lookup results, and to fall back on when nothing matches."""
|
||||
parts = [track.name or "", track.artist or "", track.album or ""]
|
||||
if track.location:
|
||||
parts.append(Path(track.location).stem)
|
||||
return " ".join(p for p in parts if p)
|
||||
|
||||
|
||||
def candidate_from_filename(track) -> IdentifyCandidate | None:
|
||||
"""A proposal read off the file's own name, for the very common case that
|
||||
no database has ever heard of the song.
|
||||
|
||||
Underground and self-released music simply isn't in AcoustID — the
|
||||
fingerprint is fine, there is just nothing to match it against — but the
|
||||
download named the file "Artist - Title [id]", which is how a human reads
|
||||
it too. Returns None when the name yields nothing usable.
|
||||
"""
|
||||
if not track.location:
|
||||
return None
|
||||
fields = filename_tags.parse_filename(track.location)
|
||||
candidate = IdentifyCandidate(score=0.0, source="filename")
|
||||
for key, value in fields.items():
|
||||
if hasattr(candidate, key):
|
||||
setattr(candidate, key, value)
|
||||
return candidate if candidate.fields() else None
|
||||
|
||||
|
||||
# ---- subprocess + network ----
|
||||
@@ -209,8 +327,8 @@ def fingerprint_file(location: str) -> tuple[int, str]:
|
||||
raise OSError(f"couldn't read fpcalc output for {name}") from e
|
||||
|
||||
|
||||
def lookup_fingerprint(api_key: str, duration: int,
|
||||
fingerprint: str) -> list[IdentifyCandidate]:
|
||||
def lookup_fingerprint(api_key: str, duration: int, fingerprint: str,
|
||||
hint: str = "") -> list[IdentifyCandidate]:
|
||||
import requests
|
||||
response = requests.post(
|
||||
ACOUSTID_LOOKUP_URL,
|
||||
@@ -224,25 +342,41 @@ def lookup_fingerprint(api_key: str, duration: int,
|
||||
if payload.get("status") != "ok":
|
||||
message = (payload.get("error") or {}).get("message", "lookup failed")
|
||||
raise RuntimeError(message)
|
||||
return parse_lookup(payload)
|
||||
return parse_lookup(payload, hint=hint, duration=duration)
|
||||
|
||||
|
||||
class TrackIdentifier(QObject):
|
||||
"""One fingerprint+lookup running off the GUI thread.
|
||||
|
||||
``finished`` carries {"track_id": int, "candidates": [IdentifyCandidate]}
|
||||
or {"track_id": int, "error": str}.
|
||||
or {"track_id": int, "error": str}. A filename guess is appended to the
|
||||
fingerprint's matches, and stands alone when there are none — a lookup
|
||||
that found nothing is not the same as nothing to propose.
|
||||
"""
|
||||
|
||||
finished = pyqtSignal(object)
|
||||
|
||||
def identify(self, track_id: int, location: str, api_key: str):
|
||||
def identify(self, track, api_key: str):
|
||||
track_id = track.track_id
|
||||
location = track.location
|
||||
hint = hint_for(track)
|
||||
guess = candidate_from_filename(track)
|
||||
|
||||
def work():
|
||||
try:
|
||||
duration, fp = fingerprint_file(location)
|
||||
candidates = lookup_fingerprint(api_key, duration, fp)
|
||||
self.finished.emit(
|
||||
{"track_id": track_id, "candidates": candidates})
|
||||
candidates = lookup_fingerprint(api_key, duration, fp, hint)
|
||||
except Exception as e:
|
||||
self.finished.emit({"track_id": track_id, "error": str(e)})
|
||||
# A file too short or too odd to fingerprint still has a name.
|
||||
if guess is not None:
|
||||
self.finished.emit({"track_id": track_id,
|
||||
"candidates": [guess],
|
||||
"note": str(e)})
|
||||
else:
|
||||
self.finished.emit({"track_id": track_id, "error": str(e)})
|
||||
return
|
||||
if guess is not None:
|
||||
candidates = candidates + [guess]
|
||||
self.finished.emit(
|
||||
{"track_id": track_id, "candidates": candidates})
|
||||
threading.Thread(target=work, daemon=True).start()
|
||||
|
||||
Reference in New Issue
Block a user