v0.96.0: now-playing words grow to fill the panel side by side; Spotify/Apple imports untick songs already in the library and put those copies in their place, so the playlist comes out the same; the shown playlist's cover fills the art panel while nothing plays

This commit is contained in:
2026-11-17 22:04:11 -08:00
parent cea9daa09f
commit 9f2f9222dd
13 changed files with 560 additions and 42 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.95.0"
__version__ = "0.96.0"
+109 -4
View File
@@ -115,6 +115,9 @@ _CURRENT_TARGET = object()
class MainWindow(QMainWindow):
# A playlist's cover finished downloading (emitted off the GUI thread).
_playlist_art_saved = pyqtSignal(str)
def __init__(self, manager, prefs, lastfm=None, parent=None):
super().__init__(parent)
self._manager = manager
@@ -307,6 +310,10 @@ class MainWindow(QMainWindow):
self._url_new_name = ""
self._url_new_cover = ""
self._url_new_pid = ""
self._url_rows = None # a Spotify/Apple list, in order
self._url_owned = 0
self._url_placed = 0
self._url_current = ""
self._url_imported = 0
self._url_identify = True # False after "Stop Identifying"
self._url_note = ""
@@ -348,6 +355,8 @@ class MainWindow(QMainWindow):
self._sidebar.art.download_art_requested.connect(
lambda tid: self._download_album_art([tid]))
self._content.currentChanged.connect(self._update_totals)
self._content.currentChanged.connect(self._update_playlist_art)
self._playlist_art_saved.connect(self._update_playlist_art)
for view in (self._library_view, self._playlist_view):
view.play_requested.connect(
lambda ids, start, v=view: self._play_from_view(v, ids, start))
@@ -1541,6 +1550,19 @@ class MainWindow(QMainWindow):
self._playlist_view.show_playlist(playlist)
self._content.setCurrentWidget(self._playlist_view)
self._update_now_playing_icon()
self._update_playlist_art()
def _update_playlist_art(self, *_):
"""Hand the art panel the shown playlist's cover (it shows it only
while nothing is playing)."""
path, name = None, ""
if self._content.currentWidget() is self._playlist_view:
pid = self._playlist_view.playlist_id
playlist = self._manager.library.playlists.get(pid)
if playlist is not None:
path = playlist_art.find(self._manager.data_dir, pid)
name = playlist.name
self._sidebar.art.set_playlist_art(path, name)
def _go_to_current_song(self):
"""Jump to wherever the current song is playing from, select it, and
@@ -1921,8 +1943,10 @@ class MainWindow(QMainWindow):
return
target = self._url_import_target()
cookies = load_config().get(url_import.COOKIES_KEY)
dialog = UrlImportDialog(target.description if target else None, self,
cookies_browser=cookies)
dialog = UrlImportDialog(
target.description if target else None, self,
cookies_browser=cookies,
library_tracks=lambda: self._manager.library.tracks.values())
accepted = dialog.exec()
if dialog.cookies_used: # the listing needed them
self._remember_cookies_browser(dialog.cookies_used)
@@ -1944,6 +1968,22 @@ class MainWindow(QMainWindow):
if problem else "")
spotify = dialog.spotify_tracks()
# A Spotify/Apple list: its songs in order, the ones the library
# already has standing in as themselves (placed by _place_url_rows).
self._url_rows = dialog.link_rows()
self._url_placed = 0
self._url_current = ""
self._url_owned = sum(1 for r in self._url_rows or [] if r["owned"])
if self._url_rows is not None and not spotify:
self._place_url_rows(final=True) # nothing to download
owned = sum(1 for r in self._url_rows if r["owned"])
self.statusBar().showMessage(
f"{owned} song{'' if owned == 1 else 's'} already in your "
"library" + (", added to the playlist" if owned and (
self._url_target is not None or self._url_new_pid)
else "") + " · nothing to download", 12000)
self._url_rows = None
return
if self._url_batch is not None:
self._url_batch.cancel()
self._url_batch = None
@@ -1978,6 +2018,7 @@ class MainWindow(QMainWindow):
self._url_progress.show()
worker.cookies_used.connect(self._remember_cookies_browser)
worker.item_started.connect(self._on_url_item_started)
worker.item_failed.connect(self._on_url_item_failed)
worker.progress.connect(self._sync_progress.setValue)
worker.downloaded.connect(self._on_url_downloaded)
worker.finished.connect(self._on_url_finished)
@@ -2009,6 +2050,7 @@ class MainWindow(QMainWindow):
def _on_url_item_started(self, index: int, count: int, item_id: str,
title: str):
self._url_current = item_id
if self._url_progress is not None:
self._url_progress.started(item_id)
short = title if len(title) <= 40 else title[:39] + "…"
@@ -2016,9 +2058,63 @@ class MainWindow(QMainWindow):
self._sync_label.setText(f"Downloading {where}{short}")
self._sync_progress.setValue(0)
def _place_url_rows(self, final: bool = False):
"""Put a Spotify/Apple list's songs into the playlists in the link's
order, as far as they're known: an owned song or a landed download
goes in, a song still downloading holds back everything after it,
a failed one is skipped. ``final``: nothing more is coming."""
rows = self._url_rows or []
ready = []
while self._url_placed < len(rows):
row = rows[self._url_placed]
if row["download"] and row["owned"] is None and not final:
break # still to land (or fail)
self._url_placed += 1
if row["owned"] is not None \
and row["owned"] in self._manager.library.tracks:
ready.append(row["owned"])
if not ready:
return
target = self._url_target
if target is not None and target.pid in self._manager.library.playlists:
position = (None if target.position is None
else target.position + self._url_inserted)
self._manager.add_tracks_to_playlist(target.pid, ready, position)
self._url_inserted += len(ready)
if self._url_new_name or self._url_new_pid:
self._add_to_new_url_playlist(
[self._manager.library.tracks[t] for t in ready])
def _url_row_done(self, key: str, track_id):
"""A download of a Spotify/Apple list's song landed (a track id) or
failed (None)."""
for row in self._url_rows or []:
if row["key"] == key and row["download"] and row["owned"] is None:
row["owned"] = track_id
row["download"] = track_id is not None
break
self._place_url_rows()
def _on_url_item_failed(self, key: str, _reason: str = ""):
if self._url_rows is not None:
self._url_row_done(key, None)
def _on_url_downloaded(self, path: str):
"""One song is off the network: file it and identify it now, so the
first dialog can be up while the rest are still downloading."""
if self._url_rows is not None:
imported = self.import_files([Path(path)])
self._url_row_done(self._url_current,
imported[0].track_id if imported else None)
self._url_imported += len(imported)
if self._url_progress is not None:
self._url_progress.landed(bool(imported))
if imported and self._url_identify:
if self._url_batch is not None:
self._url_batch.add(imported)
else:
self._enqueue_identify(imported)
return
target = self._url_target
pid, position = "", None
if target is not None and target.pid in self._manager.library.playlists:
@@ -2051,15 +2147,19 @@ class MainWindow(QMainWindow):
playlist = self._manager.create_playlist(self._url_new_name)
self._url_new_pid = playlist.persistent_id
self._url_new_name = ""
if self._url_new_cover: # kept for later; nothing shows it yet
if self._url_new_cover: # shown by the art panel
playlist_art.fetch_in_background(
self._url_new_cover, self._manager.data_dir,
playlist.persistent_id)
playlist.persistent_id,
saved=self._playlist_art_saved.emit)
self._url_new_cover = ""
self._manager.add_tracks_to_playlist(
self._url_new_pid, [t.track_id for t in tracks], undoable=False)
def _finish_url_import(self):
if self._url_rows is not None:
self._place_url_rows(final=True) # the rest, in order
self._url_rows = None
if self._url_worker is not None:
self._url_worker.cleanup()
self._hide_sync_widgets()
@@ -2195,6 +2295,11 @@ class MainWindow(QMainWindow):
if target is not None else None)
if playlist is not None and count:
msg += f" into “{playlist.name}”"
owned = self._url_owned
if owned:
msg += f" · {owned} already in your library"
if self._url_target is not None or self._url_new_pid:
msg += f", added in {'its' if owned == 1 else 'their'} place"
if summary["errors"]:
msg += f" · {len(summary['errors'])} couldn't be downloaded"
if self._url_note and count and self._url_identify:
+31 -1
View File
@@ -316,7 +316,12 @@ class SidebarArt(QWidget):
window below the playlist list's frame, like the visualizer, with the
cover inside its border. With no embedded art the panel is empty. A
click opens the big art window, or, on the empty panel, asks for the
track's art to be downloaded."""
track's art to be downloaded.
With nothing playing, the shown playlist's own cover (Round 130,
``playlist_art``) stands in, when it has one: the playing song's art
always wins, so the panel only shows a playlist's when there's no
song's to show."""
download_art_requested = pyqtSignal(int) # track id
has_art_changed = pyqtSignal(bool)
@@ -326,6 +331,9 @@ class SidebarArt(QWidget):
self._player = player
self._pixmap: QPixmap | None = None
self._track = None
self._playlist_pixmap: QPixmap | None = None
self._playlist_title = ""
self._showing_playlist = False
self._art_window = ArtWindow()
self._hovered = False
self._held = False
@@ -335,6 +343,22 @@ class SidebarArt(QWidget):
self.setFocusPolicy(Qt.FocusPolicy.TabFocus)
player.track_changed.connect(self.set_track)
def set_playlist_art(self, path, title: str = ""):
"""The shown playlist's cover file (None: no playlist shown, or one
with no cover), shown while nothing is playing."""
pixmap = None
if path is not None:
pixmap = QPixmap(str(path))
if pixmap.isNull():
pixmap = None
self._playlist_pixmap = pixmap
self._playlist_title = title
if self._track is None:
self.set_track(None)
def showing_playlist_art(self) -> bool:
return self._showing_playlist
def set_track(self, track):
self._track = track
self._pixmap = None
@@ -344,6 +368,10 @@ class SidebarArt(QWidget):
pixmap = QPixmap()
if pixmap.loadFromData(data):
self._pixmap = pixmap
self._showing_playlist = (track is None
and self._playlist_pixmap is not None)
if self._showing_playlist:
self._pixmap = self._playlist_pixmap
self._update_cursor()
if self._pixmap is not None:
self.setToolTip("Click to view full size")
@@ -375,6 +403,8 @@ class SidebarArt(QWidget):
self.set_track(self._track)
def _title(self) -> str:
if self._showing_playlist:
return self._playlist_title or "Playlist Art"
if self._track is None:
return "Album Art"
return (" — ".join(p for p in (self._track.artist, self._track.album) if p)
+96 -18
View File
@@ -5,7 +5,8 @@ from PyQt6.QtWidgets import (
QPushButton, QSizePolicy, QStyle, QStyleOptionSlider, QLayout, QSpacerItem,
)
from PyQt6.QtCore import Qt, QTimer, QEvent, QPoint, QPointF, QRect, QSize, pyqtSignal
from PyQt6.QtGui import QColor, QFont, QIcon, QPainter, QPen, QPixmap
from PyQt6.QtGui import (QColor, QFont, QFontInfo, QFontMetrics, QIcon,
QPainter, QPen, QPixmap)
from lintunes.tap_tempo import TapTempo
from lintunes.gui.icons import transport_icon
@@ -161,10 +162,16 @@ class NowPlayingText(QWidget):
from the text's own widths on every resize and every new song, so the
side-by-side shape is only ever used when nothing in it is cut off.
The labels' fonts are set by ``TransportBar._apply_now_playing_font``,
which calls ``arrange()`` after."""
Side by side, the words grow to fill the panel: the title up to the
whole height, artist and album up to half of it each, both by the same
share of the way from their normal size to that, as far as the width
allows (trav: "the song title should really max out that space"). The
stack keeps the normal sizes.
GAP = 18 # between the title and the artist/album column
The normal fonts come from ``TransportBar._apply_now_playing_font``
through ``set_fonts``."""
GAP = 18 # least space between the title and the column
LINE_GAP = 2 # between stacked lines
def __init__(self, parent=None):
@@ -174,9 +181,17 @@ class NowPlayingText(QWidget):
self.album = QLabel(self)
self._song: tuple[str, str, str] | None = None
self._lines = ("", "")
self._title_font = QFont(self.title.font())
self._line_font = QFont(self.artist.font())
self.side = False # side by side, as last arranged
self.arrange()
def set_fonts(self, title: QFont, line: QFont):
"""The normal (stacked) sizes; side by side grows from these."""
self._title_font = QFont(title)
self._line_font = QFont(line)
self.arrange()
def sizeHint(self):
return QSize(200, self.minimumSizeHint().height())
@@ -197,15 +212,69 @@ class NowPlayingText(QWidget):
def _width(self, label: QLabel, text: str) -> int:
return label.fontMetrics().horizontalAdvance(text) if text else 0
def fits_side(self, width: int) -> bool:
@staticmethod
def _sized(font: QFont, px: float) -> QFont:
sized = QFont(font)
sized.setPixelSize(max(1, round(px)))
return sized
@classmethod
def _largest_px(cls, font: QFont, height: int, lines: int) -> int:
"""The biggest pixel size at which ``lines`` lines fit ``height``."""
lo, hi = 1, max(2, height * 2)
while lo < hi:
mid = (lo + hi + 1) // 2
line = QFontMetrics(cls._sized(font, mid)).height()
if line * lines + cls.LINE_GAP * (lines - 1) <= height:
lo = mid
else:
hi = mid - 1
return lo
def side_fonts(self, width: int, height: int):
"""(title font, line font, gap) for side by side at this size, as
big as fits; None when even the normal sizes don't fit."""
if self._song is None:
return False
return None
title, artist, album = self._song
if not title or not (artist or album):
return False
right = max(self._width(self.artist, artist),
self._width(self.album, album))
return self._width(self.title, title) + self.GAP + right <= width
right = [t for t in (artist, album) if t]
if not title or not right:
return None
base_t = QFontInfo(self._title_font).pixelSize()
base_l = QFontInfo(self._line_font).pixelSize()
top_t = max(base_t, self._largest_px(self._title_font, height, 1))
top_l = max(base_l, self._largest_px(self._line_font, height,
len(right)))
def at(share):
tf = self._sized(self._title_font,
base_t + share * (top_t - base_t))
lf = self._sized(self._line_font,
base_l + share * (top_l - base_l))
gap = max(self.GAP, round(tf.pixelSize() * 0.6))
line = QFontMetrics(lf)
need = (QFontMetrics(tf).horizontalAdvance(title) + gap
+ max(line.horizontalAdvance(t) for t in right))
return need <= width, (tf, lf, gap)
fits, fonts = at(1.0)
if fits:
return fonts
fits, fonts = at(0.0)
if not fits:
return None
lo, hi = 0.0, 1.0
for _ in range(12):
mid = (lo + hi) / 2
ok, found = at(mid)
if ok:
lo, fonts = mid, found
else:
hi = mid
return fonts
def fits_side(self, width: int) -> bool:
return self.side_fonts(width, max(1, self.height())) is not None
def resizeEvent(self, event):
super().resizeEvent(event)
@@ -213,10 +282,15 @@ class NowPlayingText(QWidget):
def arrange(self):
w, h = self.width(), self.height()
self.side = self.fits_side(w)
fonts = self.side_fonts(w, h)
self.side = fonts is not None
left = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
centre = Qt.AlignmentFlag.AlignCenter
if self.side:
title_font, line_font, gap = fonts
self.title.setFont(title_font)
self.artist.setFont(line_font)
self.album.setFont(line_font)
title, artist, album = self._song
self.title.setText(title)
self.artist.setText(artist)
@@ -224,7 +298,7 @@ class NowPlayingText(QWidget):
tw = self._width(self.title, title)
rw = max(self._width(self.artist, artist),
self._width(self.album, album))
x = max(0, (w - (tw + self.GAP + rw)) // 2)
x = max(0, (w - (tw + gap + rw)) // 2)
self.title.setAlignment(left)
self.title.setGeometry(x, 0, tw + 1, h)
column = [lab for lab, text in ((self.artist, artist),
@@ -233,7 +307,7 @@ class NowPlayingText(QWidget):
y = (h - sum(heights) - self.LINE_GAP * (len(column) - 1)) // 2
for lab, lh in zip(column, heights):
lab.setAlignment(left)
lab.setGeometry(x + tw + self.GAP, y, rw + 1, lh)
lab.setGeometry(x + tw + gap, y, rw + 1, lh)
y += lh + self.LINE_GAP
self.artist.setVisible(bool(artist))
self.album.setVisible(bool(album))
@@ -245,6 +319,8 @@ class NowPlayingText(QWidget):
bottom = " — ".join(p for p in (artist, album) if p)
else:
top, bottom = self._lines
self.title.setFont(self._title_font)
self.artist.setFont(self._line_font)
# Too long for the panel: an ellipsis, never both ends cut off.
elide = Qt.TextElideMode.ElideRight
self.title.setText(self.title.fontMetrics().elidedText(top, elide, w))
@@ -1250,13 +1326,15 @@ class TransportBar(QWidget):
family = theme.now_playing_font_family(self._prefs)
base_pt = self.font().pointSize()
text_color = theme.gray(theme.gray_value(self._prefs, "color_now_playing_text"))
for label, delta in ((self._title_label, TITLE_PT_BUMP),
(self._artist_label, 0), (self._album_label, 0)):
fonts = []
for delta in (TITLE_PT_BUMP, 0):
font = QFont(family) if family else QFont(self.font())
font.setPointSize(max(1, base_pt + delta))
label.setFont(font)
fonts.append(font)
for label in (self._title_label, self._artist_label,
self._album_label):
label.setStyleSheet(f"color: {text_color.name()};")
self._np_text.arrange()
self._np_text.set_fonts(*fonts)
# ---- player events ----
+84 -11
View File
@@ -29,6 +29,13 @@ A list that has a name (a YouTube or SoundCloud playlist, a Spotify or
Apple Music album or playlist) offers to make a new playlist of the same name holding every
song imported (``new_playlist_name()``). Off unless ticked; the name can be
edited first.
Since Round 130 a Spotify or Apple Music list is checked against the
library (``library_match``) as it fills: a song already here is listed
"already in your library" and unticked. It still goes into the playlists,
as the copy already here, in its place (``link_rows()``), so the playlist
comes out the same and only the new songs download. Ticking it downloads
it again.
"""
from urllib.parse import parse_qs, urlsplit
@@ -39,6 +46,7 @@ from PyQt6.QtWidgets import (
QVBoxLayout,
)
from lintunes.library_match import LibraryMatcher
from lintunes.url_import import (
AppleMusicProbe, PlaylistProbe, SpotifyProbe, link_kind, looks_like_url,
)
@@ -72,8 +80,12 @@ def linked_song_id(url: str) -> str:
class UrlImportDialog(QDialog):
def __init__(self, target_description: str | None, parent=None, *,
cookies_browser: str | None = None):
cookies_browser: str | None = None, library_tracks=None):
"""``library_tracks``: a callable giving the library's tracks, to
find the songs of a Spotify/Apple list it already has."""
super().__init__(parent)
self._library_tracks = library_tracks
self._matcher = None
self.setWindowTitle("Import from URL")
self.setMinimumWidth(460)
self._cookies = cookies_browser
@@ -203,14 +215,43 @@ class UrlImportDialog(QDialog):
return [e["url"] for e in chosen] if chosen else [self.url()]
def spotify_tracks(self) -> list:
"""The chosen songs of a Spotify link, as ``SpotifyTrack``s (empty
for any other link): the ticked ones, or the link's one song."""
"""The songs of a Spotify/Apple link to download, as
``SpotifyTrack``s (empty for any other link): the ticked ones, or
the link's one song unless the library has it."""
if self._kind not in _CATALOGS:
return []
entries = self.chosen_entries() or (
[self._single] if self._single else [])
if self._picking:
entries = self.chosen_entries()
else:
entries = ([self._single] if self._single
and not self._single.get("owned") else [])
return [e["spotify"] for e in entries if e.get("spotify")]
def link_rows(self) -> list[dict] | None:
"""The playlist the link names, in its order, as it should come out
here: ``{"key", "owned", "download"}`` per song — downloaded
(ticked), or the library's own copy (``owned``, a track id) for an
unticked song it already has. Unticked songs it doesn't have are
left out. None for a link that isn't a Spotify/Apple list."""
if self._kind not in _CATALOGS:
return None
if self._picking and not self._just_song:
items = [self._list.item(i) for i in range(self._list.count())]
pairs = [(item.data(ENTRY_ROLE),
item.checkState() == Qt.CheckState.Checked)
for item in items]
elif self._single:
pairs = [(self._single, not self._single.get("owned"))]
else:
return None
rows = []
for entry, ticked in pairs:
if ticked or entry.get("owned"):
rows.append({"key": entry["id"],
"owned": None if ticked else entry["owned"],
"download": ticked})
return rows
def chosen_entries(self) -> list[dict]:
"""The ticked songs, in the list's order. Empty means "download the
link itself" (one song, or a link that was never listed)."""
@@ -226,11 +267,32 @@ class UrlImportDialog(QDialog):
return sum(1 for i in range(self._list.count())
if self._list.item(i).checkState() == Qt.CheckState.Checked)
def _owned_unticked(self) -> int:
return sum(1 for i in range(self._list.count())
if self._list.item(i).checkState() != Qt.CheckState.Checked
and self._list.item(i).data(ENTRY_ROLE).get("owned"))
def _mark_owned(self, entry: dict):
"""Note the library's copy of a Spotify/Apple song in the entry."""
song = entry.get("spotify")
if song is None or self._library_tracks is None:
return
if self._matcher is None:
self._matcher = LibraryMatcher(list(self._library_tracks()))
hit = self._matcher.find(song.artist, song.title, song.duration)
if hit is not None:
entry["owned"] = hit.track_id
def _update_ok(self, *_):
if self._picking:
n = self._checked_count()
self._ok.setText(f"Import {n} Song{'' if n == 1 else 's'}")
self._ok.setEnabled(n > 0 and not (
owned = self._owned_unticked()
if n or not owned:
self._ok.setText(f"Import {n} Song{'' if n == 1 else 's'}")
else:
self._ok.setText(f"Add {owned} Song{'' if owned == 1 else 's'}"
" From Library")
self._ok.setEnabled((n > 0 or owned > 0) and not (
self._make.isChecked()
and not self._make_name.text().strip()))
elif self._probe is not None:
@@ -293,6 +355,7 @@ class UrlImportDialog(QDialog):
if entry.get("id") in self._seen:
return
self._seen.add(entry.get("id"))
self._mark_owned(entry)
self._entries.append(entry)
if len(self._entries) == 1:
return # one song is not a playlist (yet)
@@ -331,13 +394,16 @@ class UrlImportDialog(QDialog):
def _add_row(self, entry: dict):
title = entry.get("title") or entry.get("id") or "(untitled)"
length = format_duration(entry.get("duration"))
item = QListWidgetItem(f"{title} {length}" if length else title)
text = f"{title} {length}" if length else title
if entry.get("owned"):
text += " · already in your library"
item = QListWidgetItem(text)
item.setData(ENTRY_ROLE, entry)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
if self._kind == "song_in_list":
checked = entry.get("id") == self._linked
else:
checked = True
checked = not entry.get("owned")
self._list.blockSignals(True)
item.setCheckState(Qt.CheckState.Checked if checked
else Qt.CheckState.Unchecked)
@@ -348,10 +414,16 @@ class UrlImportDialog(QDialog):
def _count_text(self, listing: bool) -> str:
n = len(self._entries)
if self._kind in _CATALOGS:
return (f"This {_CATALOGS[self._kind][0]} link has {n} songs"
owned = sum(1 for e in self._entries if e.get("owned"))
text = (f"This {_CATALOGS[self._kind][0]} link has {n} songs"
+ ("…" if listing else ".")
+ "\nEach one is found on YouTube by its artist, title "
"and length.")
if owned:
text += (f"\n{owned} {'is' if owned == 1 else 'are'} already "
"in your library, so unticked: the copies you have "
"go into the playlist in their place.")
return text
text = f"This link is a playlist: {n} songs"
if listing:
text += " so far, still listing…"
@@ -367,7 +439,8 @@ class UrlImportDialog(QDialog):
self._busy.hide()
if self._picking:
self._status.setText(self._count_text(listing=False))
if self._checked_count() == 0 and self._list.count():
if (self._kind == "song_in_list" and self._checked_count() == 0
and self._list.count()):
# The linked song wasn't in the list it came with.
self._list.item(0).setCheckState(Qt.CheckState.Checked)
self._update_ok()
+79
View File
@@ -0,0 +1,79 @@
"""Is this song already in the library? (Round 130.)
For Import from URL's Spotify and Apple Music lists: a song the library
already has is unticked in the checklist, and the copy already here goes
into the playlists in its place, so the playlist comes out the same and
only the new songs download.
Shazam's rule (``shazam.match_library``): the same artist and title once
"(feat. …)"/"(Remastered)" are stripped, or a title sharing 80 % of its
words with an artist in common. Plus a length check, because these lists
carry exact lengths: a library copy more than ``LENGTH_SLACK`` seconds off
is a live take or another edit, not this song. Built once per list, with an
index on title words, so a 100-song list against a 20,000-song library
doesn't compare every pair.
"""
from lintunes.shazam import key_of, toks
LENGTH_SLACK = 15 # seconds
class LibraryMatcher:
def __init__(self, tracks):
self._exact: dict[tuple[str, str], list] = {}
self._entries = []
self._by_word: dict[str, list[int]] = {}
for t in tracks:
artist, name = key_of(t.artist, t.name)
if not name:
continue
self._exact.setdefault((artist, name), []).append(t)
words = toks(t.name)
index = len(self._entries)
self._entries.append((words, toks(t.artist), t))
for w in words:
self._by_word.setdefault(w, []).append(index)
@staticmethod
def _seconds(track) -> float | None:
ms = getattr(track, "total_time", None)
return ms / 1000 if ms else None
def _length_ok(self, track, duration) -> bool:
have = self._seconds(track)
return not (duration and have) or abs(have - duration) <= LENGTH_SLACK
def _closest(self, tracks, duration):
ok = [t for t in tracks if self._length_ok(t, duration)]
if not ok:
return None
if not duration:
return ok[0]
return min(ok, key=lambda t: abs((self._seconds(t) or duration)
- duration))
def find(self, artist: str, title: str, duration: int | None = None):
"""The library's copy of this song, or None."""
hit = self._closest(self._exact.get(key_of(artist, title), []),
duration)
if hit is not None:
return hit
nt, at = toks(title), toks(artist)
if not nt:
return None
seen: set[int] = set()
best, best_score = None, 0.0
for w in nt:
for index in self._by_word.get(w, ()):
if index in seen:
continue
seen.add(index)
ltok, latok, t = self._entries[index]
ts = len(nt & ltok) / len(nt | ltok)
ars = (len(at & latok) / len(at | latok)
if at and latok else 0.0)
score = ts * .7 + ars * .3
if (ts >= 0.8 and (ars > 0 or not at) and score > best_score
and self._length_ok(t, duration)):
best, best_score = t, score
return best
+9 -5
View File
@@ -1,8 +1,9 @@
"""A playlist's own cover image (Round 130).
Spotify and Apple Music playlists (and albums) have a cover, and a playlist
made from one of their links in Import from URL keeps it. Nothing *shows* it
yet; this is only where it is kept.
made from one of their links in Import from URL keeps it. The sidebar art panel
shows it while nothing is playing and that playlist is shown
(``SidebarArt.set_playlist_art``).
One file per playlist, ``<data_dir>/playlist_art/<persistent_id>.jpg`` (or
``.png``), so it rides the Syncthing share with the playlists but stays out
@@ -82,14 +83,17 @@ def download(url: str) -> bytes:
return data
def fetch_in_background(url: str, data_dir: Path, pid: str):
def fetch_in_background(url: str, data_dir: Path, pid: str, saved=None):
"""Download ``url`` and keep it as the playlist's cover, on a daemon
thread. A failure is logged and otherwise ignored: the playlist is
complete without it."""
thread, then call ``saved(pid)`` *on that thread* (a Qt signal's emit
is the safe thing to pass). A failure is logged and otherwise ignored:
the playlist is complete without it."""
def run():
try:
path = save(data_dir, pid, download(url))
log.info("playlist art for %s saved to %s", pid, path)
if saved is not None:
saved(pid)
except Exception as e:
log.warning("playlist art for %s from %s: %s", pid, url, e)
threading.Thread(target=run, daemon=True).start()