Files
lintunes/lintunes/identify_batch.py
T
trav f079d26416 v0.38.0: several imported songs are identified as one batch
No identify dialog pops up mid-download any more: songs are looked up
quietly as they land and reviewed together once the last one is in, as
rows in the app's columns. Songs that are one album get the album-wide
fields once, unified, plus a cover from the album-art search. Ticked
rows apply as one undo step; unticked ones get the ordinary dialog
after. Popups wait for LinTunes to be the app in front.
2026-10-09 01:42:13 -07:00

251 lines
9.1 KiB
Python

"""Identify several songs at once (Round 77): the analysis behind the batch
review window an Import from URL of more than one song ends with.
One dialog per song was fine for a song and a chore for an album: twelve
"Apply Tags" clicks for twelve songs that obviously belong together. So a
multi-song import is fingerprinted quietly while it downloads, and only
once *everything* has landed is it shown, all at once, as rows.
``find_common_album`` is the "these are all one album" call. Every song
votes for each album it could be on: any of its lookup candidates, plus
its own tags (a Spotify album import already carries the right album, even
when AcoustID only knows the song from a compilation). An album named by
every song that names one, covering at least ``ALBUM_SHARE`` of them, is
the album. Each song then takes its best candidate *on that album*, and the
album-wide fields (album, album artist, year, track count) are unified to
the most common value, so one stray pressing can't leave a single song
filed under a different year. A playlist gets none of that: each song
simply shows its best candidate.
Pure and Qt-widget-free apart from ``IdentifyCollector``, which runs the
lookups one at a time while a download is still going.
"""
from collections import Counter
from dataclasses import dataclass, field
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes.art_search import _simplify_album
from lintunes.fingerprint import IdentifyCandidate, TrackIdentifier
# What a row shows and may change, in column order.
FIELDS = ("name", "artist", "album_artist", "album", "year", "track_number",
"track_count", "disc_number")
ALBUM_FIELDS = ("album", "album_artist", "year", "track_count")
# Share of the songs an album must cover to be "one album".
ALBUM_SHARE = 0.75
@dataclass
class BatchRow:
track: object # the library Track
proposal: dict # field → proposed value (None: keep)
source: str # "AcoustID 97%", "Filename", …
candidates: list = field(default_factory=list)
def current(self, name: str):
return getattr(self.track, name, None)
def changes(self) -> dict:
"""The proposed values that differ from the track's own. A blank
proposal never blanks a tag."""
out = {}
for name in FIELDS:
value = self.proposal.get(name)
if value in (None, "", 0):
continue
if value != (self.current(name) or None):
out[name] = value
return out
@dataclass
class BatchAnalysis:
rows: list
album: str | None = None # set when the songs are one album
album_artist: str | None = None
year: int | None = None
@property
def is_album(self) -> bool:
return self.album is not None
def album_key(album: str | None) -> str:
""""Last Splash (Remastered)" and "last splash" are one album."""
return _simplify_album(album or "").casefold().strip()
def tags_candidate(track) -> IdentifyCandidate:
"""What the song's own tags say, as a candidate."""
candidate = IdentifyCandidate(score=0.0, source="tags")
for name in FIELDS:
value = getattr(track, name, None)
if value not in (None, "", 0):
setattr(candidate, name, value)
return candidate
def describe(candidate: IdentifyCandidate | None) -> str:
if candidate is None:
return "Nothing found"
if candidate.source == "acoustid":
return f"AcoustID {round(candidate.score * 100)}%"
return {"filename": "Filename", "tags": "Its own tags"}.get(
candidate.source, candidate.source)
def _options(track, candidates) -> list:
"""Every candidate for a song, best first, its own tags last."""
return list(candidates) + [tags_candidate(track)]
def find_common_album(entries) -> str | None:
"""The album key every song that names an album agrees on, or None.
``entries`` is [(track, candidates)]. Among albums every voting song
can be on, the one its songs' *best* candidates name most wins (so a
compilation that happens to hold every song too loses to the album
the top matches say)."""
if len(entries) < 2:
return None
voters = []
top_votes = Counter()
for track, candidates in entries:
keys = {album_key(c.album) for c in _options(track, candidates)
if album_key(c.album)}
if keys:
voters.append(keys)
for c in _options(track, candidates):
if album_key(c.album):
top_votes[album_key(c.album)] += 1
break
if len(voters) < max(2, ALBUM_SHARE * len(entries)):
return None
common = set.intersection(*voters)
if not common:
return None
return max(sorted(common), key=lambda k: top_votes[k])
def _most_common(values):
"""The most frequent non-empty value; ties go to the smallest (the
earliest year, the lowest count)."""
counts = Counter(v for v in values if v not in (None, "", 0))
if not counts:
return None
best = max(counts.values())
return min(v for v, n in counts.items() if n == best)
def analyze(entries) -> BatchAnalysis:
"""[(track, candidates)] → rows to review, unified into one album when
the songs are one."""
key = find_common_album(entries)
chosen = []
for track, candidates in entries:
pick = candidates[0] if candidates else None
if key is not None:
pick = next((c for c in _options(track, candidates)
if album_key(c.album) == key), pick)
chosen.append((track, candidates, pick))
if key is None:
rows = [BatchRow(track, pick.fields() if pick else {},
describe(pick), list(candidates))
for track, candidates, pick in chosen]
return BatchAnalysis(rows)
picks = [pick for _t, _c, pick in chosen if pick is not None
and album_key(pick.album) == key]
album = _most_common(p.album for p in picks)
album_artist = _most_common(p.album_artist for p in picks)
year = _most_common(p.year for p in picks)
track_count = _most_common(p.track_count for p in picks)
rows = []
for track, candidates, pick in chosen:
proposal = pick.fields() if pick is not None else {}
proposal.update({"album": album, "album_artist": album_artist,
"year": year, "track_count": track_count})
rows.append(BatchRow(track, proposal, describe(pick),
list(candidates)))
return BatchAnalysis(rows, album=album, album_artist=album_artist,
year=year)
def album_art_query(analysis: BatchAnalysis) -> tuple[str, str] | None:
"""(artist, album) to search cover art by, for an album batch."""
if not analysis.is_album:
return None
artist = analysis.album_artist or _most_common(
r.proposal.get("artist") or r.current("artist")
for r in analysis.rows)
return (artist, analysis.album) if artist else None
class IdentifyCollector(QObject):
"""Looks songs up one at a time, quietly, as they're handed in, and
says ``ready`` with [(track, candidates)] in the order they came once
``close()`` has said no more are coming and the last lookup is back.
``progress`` is (looked up, handed in)."""
progress = pyqtSignal(int, int)
ready = pyqtSignal(list)
def __init__(self, api_key: str, parent=None):
super().__init__(parent)
self._api_key = api_key
self._tracks: list = []
self._results: dict = {} # track id → candidates
self._queue: list = []
self._identifier = None
self._closed = False
self._cancelled = False
self._sent = False
def add(self, tracks):
if self._cancelled:
return
self._tracks.extend(tracks)
self._queue.extend(tracks)
if self._identifier is None:
self._next()
def close(self):
self._closed = True
self._maybe_ready()
def cancel(self):
self._cancelled = True
self._queue.clear()
def total(self) -> int:
return len(self._tracks)
def _next(self):
if not self._queue or self._cancelled:
self._identifier = None
self._maybe_ready()
return
track = self._queue.pop(0)
# Kept so the identifier and its thread's signal source outlive
# this call.
self._identifier = TrackIdentifier()
self._identifier.finished.connect(
lambda result, t=track: self._on_result(t, result))
self._identifier.identify(track, self._api_key)
def _on_result(self, track, result: dict):
self._results[track.track_id] = result.get("candidates") or []
self.progress.emit(len(self._results), len(self._tracks))
self._next()
def _maybe_ready(self):
if (self._closed and self._identifier is None and not self._sent
and not self._cancelled):
self._sent = True
self.ready.emit([(t, self._results.get(t.track_id, []))
for t in self._tracks])