Files
lintunes/lintunes/gui/identify_dialog.py
T
trav a52542750c v0.73.0: Connections › Import Shazams… — the Rabbit's new Shazams, found on YouTube as the original song, tagged as they land
Reads Shazam's history over root adb (and unroots after), offers only
Shazams not dealt with yet (a synced list), picks the plain studio take
(no live/cover/karaoke/clean/vinyl/sped-up, Apple's length decides), and
shows every song's stage with the Identify panel for each one as soon as
it's imported, in the same window.
2026-10-20 00:00:20 -07:00

182 lines
7.2 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.
The proposal itself is ``IdentifyPanel``, a plain widget, so Import Shazams
can show it inside its own window while songs are still downloading.
"""
from PyQt6.QtWidgets import (
QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QLabel,
QLineEdit, QPushButton, QSpinBox, QVBoxLayout, QWidget,
)
# (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 IdentifyPanel(QWidget):
"""One track's proposals: the candidate drop-down and the field grid."""
def __init__(self, track, candidates, parent=None):
super().__init__(parent)
self._track = track
self._candidates = candidates
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
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)
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)
# ---- 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
class IdentifyDialog(QDialog):
"""``IdentifyPanel`` as its own window, with Apply / Cancel and, for a
queue, Stop Identifying."""
def __init__(self, track, candidates, remaining: int = 0, parent=None):
super().__init__(parent)
self.setWindowTitle("Identify Track")
# True when the user pressed "Stop Identifying" on a queued batch.
self.cancel_all = False
layout = QVBoxLayout(self)
self.panel = IdentifyPanel(track, candidates, self)
layout.addWidget(self.panel)
# What the tests reach into.
self._header = self.panel._header
self._combo = self.panel._combo
self._checks = self.panel._checks
self._editors = self.panel._editors
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)
def _stop_all(self):
self.cancel_all = True
self.reject()
def result_fields(self) -> dict:
return self.panel.result_fields()