v0.15.0: ask the song what it is

Right-click → Identify Track… fingerprints the file with Chromaprint's
fpcalc and asks AcoustID who it is, then proposes the tags it found.

The year is the point. A 60s song kept getting stamped with the year its
CD reissue came out, which sorts the library wrong, so every candidate
carries the recording's *original* year — the earliest release across all
of its release groups — including the candidate that proposes a later
greatest-hits as the album. Ranking separately prefers a plain studio
Album over EP/Single over anything wearing a Compilation or Live
secondary type, so the default proposal is the real album as well.

Nothing is written until accepted: the dialog shows each current value
beside an editable proposed one, and a row starts checked only where the
proposal actually differs from what the file already has, so an untouched
field can never quietly blank a tag. Applying goes through
edit_track_fields, which is what buys the tag write, the abort-if-it-fails
rule, artist/album file relocation and one undo step without re-deriving
any of them.

A selection is a queue reviewed one track at a time; a failure is a
status-bar message that moves on rather than ending the batch. fpcalc is
detected at runtime like ffmpeg and the AcoustID key lives in preferences
(so it syncs, and stays out of git) — the round adds no new dependency.

Also fixes a pre-existing round 40 test that used the real tummult mount
point as its stand-in for an unreachable path, so it failed whenever that
drive was plugged in.

Claude-Session: https://claude.ai/code/session_01NsiFHdyVg1UhBSxDJfTNRm
This commit is contained in:
2026-09-02 15:40:52 -04:00
parent 5831175584
commit 312748d05e
12 changed files with 946 additions and 2 deletions
+248
View File
@@ -0,0 +1,248 @@
"""Track identification via Chromaprint (fpcalc) + the AcoustID web API.
Pure parsing/ranking helpers are separated from the subprocess and network
calls so they can be tested offline with canned AcoustID JSON;
``TrackIdentifier`` runs the whole fingerprint+lookup on a daemon thread (the
art_search pattern) and reports back over a Qt signal, which is delivered
queued on the GUI thread.
fpcalc is the Chromaprint *CLI binary* (Fedora: chromaprint-tools, Debian:
libchromaprint-tools) — detected at runtime, never a pip dependency. The
AcoustID application key is user-supplied via Preferences (the Last.fm
precedent); registration is free at https://acoustid.org/new-application.
"""
import json
import shutil
import subprocess
import threading
from dataclasses import asdict, dataclass
from PyQt6.QtCore import QObject, pyqtSignal
ACOUSTID_LOOKUP_URL = "https://api.acoustid.org/v2/lookup"
LOOKUP_META = "recordings releasegroups releases tracks compress"
SCORE_THRESHOLD = 0.5 # AcoustID scores below this are noise
MAX_CANDIDATES = 8
TIMEOUT_S = 15
FPCALC_TIMEOUT_S = 60
@dataclass
class IdentifyCandidate:
"""One proposed identification. Field names match Track/tagging so
``fields()`` can go straight into ``LibraryManager.edit_track_fields``."""
score: float
name: str | None = None
artist: str | None = None
album_artist: str | None = None
album: str | None = None
year: int | None = None
track_number: int | None = None
track_count: int | None = None
disc_number: int | None = None
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}
# ---- pure parsing/ranking helpers (offline-testable) ----
def _join_artists(artists: list | None) -> str | None:
"""Concatenate MusicBrainz artist credits, honoring ``joinphrase``."""
if not artists:
return None
parts = []
for i, artist in enumerate(artists):
name = artist.get("name", "")
if not name:
continue
if parts:
parts.append(artists[i - 1].get("joinphrase") or "; ")
parts.append(name)
return "".join(parts) or None
def _release_year(release: dict) -> int | None:
year = (release.get("date") or {}).get("year")
return year if isinstance(year, int) and year > 0 else None
def _oldest_year(releasegroup: dict) -> int | None:
"""Earliest dated release in the group — the original pressing, not the
CD reissue."""
years = [y for r in releasegroup.get("releases", [])
if (y := _release_year(r)) is not None]
return min(years) if years else None
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."""
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
return (rank, _oldest_year(releasegroup) or 9999)
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."""
releases = releasegroup.get("releases", [])
if not releases:
return None
dated = sorted(releases, key=lambda r: _release_year(r) or 9999)
for release in dated:
if release.get("mediums"):
return release
return dated[0]
def _track_position(release: dict | None) -> tuple[int | None, int | None,
int | None]:
"""(track_number, track_count, disc_number) from the matching medium.
With ``meta=tracks`` AcoustID returns only the medium/track entries that
match the looked-up recording, so the first entries are the match.
"""
if not release:
return None, None, None
mediums = release.get("mediums") or []
if not mediums:
return None, None, None
medium = mediums[0]
tracks = medium.get("tracks") or []
number = tracks[0].get("position") if tracks else None
count = medium.get("track_count")
disc = medium.get("position")
return (number if isinstance(number, int) else None,
count if isinstance(count, int) else None,
disc if isinstance(disc, int) else None)
def parse_lookup(payload: dict, threshold: float = SCORE_THRESHOLD,
limit: int = MAX_CANDIDATES) -> list[IdentifyCandidate]:
"""Turn an AcoustID lookup response into ranked candidates.
One candidate per release group of each matched recording, so the
alternates offered in the dialog genuinely differ (different album/year).
Every candidate of a recording carries the recording's *original* year —
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.
"""
candidates = []
seen = set()
results = sorted(payload.get("results", []),
key=lambda r: r.get("score", 0), reverse=True)
for result in results:
score = result.get("score", 0)
if score < threshold:
continue
for recording in result.get("recordings", []):
title = recording.get("title")
artist = _join_artists(recording.get("artists"))
groups = sorted(recording.get("releasegroups") or [],
key=_releasegroup_sort_key)
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 not groups:
if title:
candidates.append(IdentifyCandidate(
score=score, name=title, artist=artist))
continue
for releasegroup in groups:
album = releasegroup.get("title")
key = (title, artist, album)
if key in seen:
continue
seen.add(key)
number, count, disc = _track_position(
_pick_release(releasegroup))
candidates.append(IdentifyCandidate(
score=score,
name=title,
artist=artist,
album_artist=_join_artists(releasegroup.get("artists")),
album=album,
year=original_year,
track_number=number,
track_count=count,
disc_number=disc,
))
return candidates[:limit]
# ---- subprocess + network ----
def fpcalc_available() -> bool:
"""Whether the fpcalc *binary* is on PATH (the ffmpeg_available pattern —
Chromaprint's CLI tool, not a Python package)."""
return shutil.which("fpcalc") is not None
def fingerprint_file(location: str) -> tuple[int, str]:
"""Run fpcalc on a file; returns (duration seconds, fingerprint).
Raises OSError on failure, carrying fpcalc's last stderr line."""
try:
proc = subprocess.run(
["fpcalc", "-json", location],
stdin=subprocess.DEVNULL, capture_output=True,
timeout=FPCALC_TIMEOUT_S)
except (OSError, ValueError, subprocess.TimeoutExpired) as e:
raise OSError(f"couldn't run fpcalc: {e}") from e
name = location.rsplit("/", 1)[-1]
if proc.returncode != 0:
detail = proc.stderr.decode("utf-8", "replace").strip().splitlines()
raise OSError(f"fpcalc failed on {name}"
+ (f": {detail[-1]}" if detail else ""))
try:
payload = json.loads(proc.stdout.decode("utf-8", "replace"))
return int(payload["duration"]), payload["fingerprint"]
except (ValueError, KeyError, TypeError) as e:
raise OSError(f"couldn't read fpcalc output for {name}") from e
def lookup_fingerprint(api_key: str, duration: int,
fingerprint: str) -> list[IdentifyCandidate]:
import requests
response = requests.post(
ACOUSTID_LOOKUP_URL,
data={"client": api_key, "duration": duration,
"fingerprint": fingerprint, "meta": LOOKUP_META,
"format": "json"},
timeout=TIMEOUT_S,
)
response.raise_for_status()
payload = response.json()
if payload.get("status") != "ok":
message = (payload.get("error") or {}).get("message", "lookup failed")
raise RuntimeError(message)
return parse_lookup(payload)
class TrackIdentifier(QObject):
"""One fingerprint+lookup running off the GUI thread.
``finished`` carries {"track_id": int, "candidates": [IdentifyCandidate]}
or {"track_id": int, "error": str}.
"""
finished = pyqtSignal(object)
def identify(self, track_id: int, location: str, api_key: str):
def work():
try:
duration, fp = fingerprint_file(location)
candidates = lookup_fingerprint(api_key, duration, fp)
self.finished.emit(
{"track_id": track_id, "candidates": candidates})
except Exception as e:
self.finished.emit({"track_id": track_id, "error": str(e)})
threading.Thread(target=work, daemon=True).start()