Files
lintunes/lintunes/library_match.py
T

80 lines
3.1 KiB
Python

"""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