247 lines
9.9 KiB
Python
247 lines
9.9 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.
|
|
|
|
With ``find_art`` the dialog also searches a cover for the album the grid
|
|
proposes (Round 119, ``art_picker``), re-searching when the candidate or
|
|
the artist/album boxes change; ``selected_image`` is set on accept.
|
|
"""
|
|
from PyQt6.QtCore import QTimer, pyqtSignal
|
|
from PyQt6.QtWidgets import (
|
|
QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout,
|
|
QLabel, QLineEdit, QPushButton, QSpinBox, QVBoxLayout, QWidget,
|
|
)
|
|
|
|
from lintunes.gui.art_picker import ArtPicker
|
|
|
|
# (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."""
|
|
|
|
# The candidate switched, or a box or tick was edited.
|
|
proposal_changed = pyqtSignal()
|
|
|
|
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)
|
|
check.toggled.connect(lambda _on: self.proposal_changed.emit())
|
|
if is_number:
|
|
editor.valueChanged.connect(
|
|
lambda _v: self.proposal_changed.emit())
|
|
else:
|
|
editor.textChanged.connect(
|
|
lambda _t: self.proposal_changed.emit())
|
|
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 value(self, field):
|
|
"""What ``field`` will be after Apply: the box when its row is
|
|
ticked and filled, else the track's own value."""
|
|
proposed = self.result_fields().get(field)
|
|
return proposed if proposed else self._current_value(field)
|
|
|
|
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."""
|
|
|
|
# How long typing in Artist/Album rests before the cover is searched.
|
|
ART_DELAY_MS = 700
|
|
|
|
def __init__(self, track, candidates, remaining: int = 0, parent=None,
|
|
find_art: bool = False, embed_art: bool = True):
|
|
super().__init__(parent)
|
|
self.setWindowTitle("Identify Track")
|
|
# True when the user pressed "Stop Identifying" on a queued batch.
|
|
self.cancel_all = False
|
|
self.selected_image: bytes | None = None
|
|
self.selected_mime = "image/jpeg"
|
|
|
|
layout = QVBoxLayout(self)
|
|
top = QHBoxLayout()
|
|
self.panel = IdentifyPanel(track, candidates, self)
|
|
top.addWidget(self.panel, 1)
|
|
self.art = None
|
|
if find_art:
|
|
self._embed_art = embed_art
|
|
self.art = ArtPicker("Embed this artwork", parent=self)
|
|
top.addSpacing(12)
|
|
top.addWidget(self.art)
|
|
self._art_timer = QTimer(self)
|
|
self._art_timer.setSingleShot(True)
|
|
self._art_timer.setInterval(self.ART_DELAY_MS)
|
|
self._art_timer.timeout.connect(self._search_art)
|
|
self.panel.proposal_changed.connect(self._art_timer.start)
|
|
self.panel._combo.currentIndexChanged.connect(
|
|
lambda _i: self._search_art())
|
|
self._search_art()
|
|
layout.addLayout(top)
|
|
# 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._on_accept)
|
|
buttons.rejected.connect(self.reject)
|
|
layout.addWidget(buttons)
|
|
|
|
def art_query(self) -> tuple[str, str] | None:
|
|
"""(artist, album) the proposal would leave the song with."""
|
|
artist = self.panel.value("album_artist") or self.panel.value("artist")
|
|
album = self.panel.value("album")
|
|
return (artist, album) if artist and album else None
|
|
|
|
def _search_art(self):
|
|
self._art_timer.stop()
|
|
query = self.art_query()
|
|
if query is None:
|
|
self.art.clear()
|
|
elif query != self.art.query:
|
|
self.art.search(*query, embed_by_default=self._embed_art)
|
|
|
|
def _on_accept(self):
|
|
chosen = self.art.selected() if self.art is not None else None
|
|
if chosen:
|
|
self.selected_image, self.selected_mime = chosen
|
|
self.accept()
|
|
|
|
def _stop_all(self):
|
|
self.cancel_all = True
|
|
self.reject()
|
|
|
|
def result_fields(self) -> dict:
|
|
return self.panel.result_fields()
|