Files
lintunes/lintunes/gui/identify_dialog.py
T
trav 33d74ab1f5 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
2026-09-02 17:24:07 -04:00

156 lines
6.3 KiB
Python

"""Confirmation dialog for a track identification (Identify Track…).
Shows the proposed tag changes for one track — current value vs an editable
proposed value per field, with a checkbox to opt out of any row — and a
dropdown of alternate candidates (other albums/releases the recording appears
on). Passive like AlbumArtDialog: candidates arrive pre-parsed, nothing is
written until the user accepts, and the caller applies ``result_fields()``
through LibraryManager afterwards.
"""
from PyQt6.QtWidgets import (
QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QLabel,
QLineEdit, QPushButton, QSpinBox, QVBoxLayout,
)
# (field, label, is_number, spinbox max)
_FIELDS = [
("name", "Name", False, 0),
("artist", "Artist", False, 0),
("album_artist", "Album Artist", False, 0),
("album", "Album", False, 0),
("year", "Year", True, 9999),
("track_number", "Track #", True, 999),
("track_count", "Track Count", True, 999),
("disc_number", "Disc #", True, 99),
]
class IdentifyDialog(QDialog):
def __init__(self, track, candidates, remaining: int = 0, parent=None):
super().__init__(parent)
self.setWindowTitle("Identify Track")
self._track = track
self._candidates = candidates
# True when the user pressed "Stop Identifying" on a queued batch.
self.cancel_all = False
layout = QVBoxLayout(self)
self._header = QLabel()
self._header.setWordWrap(True)
layout.addWidget(self._header)
# All alternates at a glance — a candidate summarizes to one line, so
# a dropdown beats AlbumArtDialog's blind Next-clicking.
self._combo = QComboBox()
for c in candidates:
year = f" ({c.year})" if c.year else ""
summary = " — ".join(
p for p in (c.name, c.artist, c.album) if p) + year
if c.source == "filename":
summary = f"From the filename: {summary}"
self._combo.addItem(summary)
layout.addWidget(self._combo)
grid = QGridLayout()
grid.setColumnStretch(1, 1)
grid.setColumnStretch(3, 1)
self._checks: dict[str, QCheckBox] = {}
self._current_labels: dict[str, QLabel] = {}
self._editors: dict[str, QLineEdit | QSpinBox] = {}
for row, (field, label, is_number, maximum) in enumerate(_FIELDS):
check = QCheckBox(label)
current = QLabel()
current.setEnabled(False) # the greyed-hint idiom
arrow = QLabel("→")
if is_number:
editor = QSpinBox()
editor.setRange(0, maximum)
editor.setSpecialValueText(" ")
else:
editor = QLineEdit()
check.toggled.connect(editor.setEnabled)
self._checks[field] = check
self._current_labels[field] = current
self._editors[field] = editor
grid.addWidget(check, row, 0)
grid.addWidget(current, row, 1)
grid.addWidget(arrow, row, 2)
grid.addWidget(editor, row, 3)
layout.addLayout(grid)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok
| QDialogButtonBox.StandardButton.Cancel)
buttons.button(QDialogButtonBox.StandardButton.Ok).setText(
"Apply Tags")
if remaining > 0:
noun = "track" if remaining == 1 else "tracks"
stop_btn = QPushButton(f"Stop Identifying ({remaining} {noun} left)")
buttons.addButton(stop_btn,
QDialogButtonBox.ButtonRole.ActionRole)
stop_btn.clicked.connect(self._stop_all)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
self._combo.currentIndexChanged.connect(self._fill_from_candidate)
self._fill_from_candidate(0)
# ---- candidate switching ----
def _current_value(self, field):
return getattr(self._track, field, None)
def _fill_from_candidate(self, index: int):
"""Re-fill the grid from a candidate (hand edits are discarded on a
switch, like AlbumArtDialog cycling). A row is checked and editable
iff the candidate proposes a value that differs from the current one;
rows with nothing proposed are unchecked and disabled."""
candidate = self._candidates[index]
name = self._track.name or "(untitled)"
if candidate.source == "filename":
# No database matched this, so there is no confidence to quote —
# say where the proposal actually came from instead of implying
# something recognized the audio.
self._header.setText(
f"No database knows “{name}”. Read from the file's name:")
else:
self._header.setText(
f"Identified “{name}” — match confidence "
f"{round(candidate.score * 100)}%")
for field, _label, is_number, _max in _FIELDS:
current = self._current_value(field)
proposed = getattr(candidate, field)
label = self._current_labels[field]
editor = self._editors[field]
check = self._checks[field]
label.setText(str(current) if current else "—")
if is_number:
editor.setValue(proposed or 0)
else:
editor.setText(proposed or "")
has_proposal = proposed is not None
differs = has_proposal and proposed != (current or None)
check.setEnabled(has_proposal)
check.setChecked(differs)
editor.setEnabled(differs)
def _stop_all(self):
self.cancel_all = True
self.reject()
# ---- result ----
def result_fields(self) -> dict:
"""Checked rows only, keyed by LinTunes field names — ready for
``LibraryManager.edit_track_fields``. Blank editors are dropped (a
checked row the user then emptied proposes nothing)."""
fields = {}
for field, _label, is_number, _max in _FIELDS:
if not self._checks[field].isChecked():
continue
editor = self._editors[field]
value = editor.value() if is_number else editor.text().strip()
if value:
fields[field] = value
return fields