Files
lintunes/lintunes/shazam.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

725 lines
28 KiB
Python

"""Connections ▸ Import Shazams… (Round 103): the songs trav Shazamed on the
Rabbit, found on YouTube and imported, ported from the ``/shazam-import``
skill (``~/.claude/skills/shazam-import``).
Shazam keeps its history in ``library.db`` inside its app sandbox. MTP
doesn't show it, ``run-as`` is refused (the app isn't debuggable) and
``adb backup`` is refused (no allowBackup). The R1's ROM is a userdebug GSI,
so root adbd is the way in: ``ShazamReader`` runs ``adb root``, pulls the
database **and its -wal** (the newest Shazams sit in the write-ahead log and
are invisible without it), and puts adbd back with ``adb unroot`` if it was
the one that rooted it.
Which Shazams have been dealt with lives in the synced preferences
(``shazam_import.handled``, request id → date), so the other desktop doesn't
offer them again either. A song is handled once it's imported, unticked on
purpose, or already in the library; one that failed to download is not, so
it comes back next time.
Picking the YouTube result is the point of the feature. "The original song"
means: not live, not a cover, not karaoke or an instrumental, not a clean
(censored) edit, not a vinyl rip filmed on a turntable, not sped up, slowed
or remixed — unless the Shazam title itself says so. Every such word rejects
a result outright. Then **length** decides: the iTunes Search API (no key,
``art_search``'s endpoint) knows the recording's canonical duration, and a
result that disagrees by more than 20 s is another take. A live album must
never supply that length, or the filter steers toward the concert. Among the
survivors, a ``- Topic`` channel (YouTube's own audio-only upload of the
release) beats the artist's own channel beats a stranger's "(Official
Audio)", and a music video, which often carries a skit, counts against.
Measured on real searches (Round 103): without the artist's channel ahead
of "Audio", fan uploads beat Kendrick's and Outkast's own.
Shaped like ``spotify_link``: pure helpers first (tested against a synthetic
database and canned results), then adb and the network.
"""
import json
import logging
import os
import re
import shutil
import sqlite3
import subprocess
import tempfile
import threading
import time
import unicodedata
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
import requests
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import tagging, url_import
log = logging.getLogger(__name__)
DEVICE_DB = "/data/user/0/com.shazam.android/databases/library.db"
ITUNES_SEARCH = "https://itunes.apple.com/search"
ITUNES_LOOKUP = "https://itunes.apple.com/lookup"
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64)"
TIMEOUT = 20
# YouTube results listed per search.
SEARCH_RESULTS = 8
# Results downloaded per song before giving up on it.
TRIES = 3
# A downloaded file this far from its listed length was cut short.
TRUNCATED_SLACK = 20
# The preferences key: {"handled": {request id: "YYYY-MM-DD"}}.
PREFS_KEY = "shazam_import"
# Where the /shazam-import skill kept the ones it fetched. Read once, so the
# first in-app import doesn't offer them all again.
LEGACY_STATE = Path(os.environ.get(
"XDG_STATE_HOME", str(Path.home() / ".local" / "state"))) \
/ "lintunes-shazam-import" / "state.json"
@dataclass
class ShazamSong:
request_id: str
when: datetime
title: str
artist: str = ""
year: int | None = None
genre: str = ""
upc: str = "" # the release barcode in the artwork URL
in_library: str = "" # "Artist — Title" of a library match
# Filled in by the lookup: Apple's length and album for the recording.
canon_secs: int | None = None
album: str = ""
album_artist: str = ""
album_confident: bool = False
def label(self) -> str:
return f"{self.artist} — {self.title}" if self.artist else self.title
def fold(text: str) -> str:
text = unicodedata.normalize("NFC", text or "").casefold()
return " ".join(re.sub(r"[^\w\s]+", " ", text).split())
_STOP = {"the", "a", "an", "of", "and", "version", "original", "feat"}
def toks(text: str) -> set[str]:
return {w for w in fold(text).split() if w not in _STOP and len(w) > 1}
# ---- reading Shazam's database ----
def _year(text) -> int | None:
m = re.match(r"\s*(\d{4})", str(text or ""))
return int(m.group(1)) if m else None
def read_shazams(db_path) -> list[ShazamSong]:
"""Every Shazam with a title, newest first. A Shazam of the same song
twice is two rows; ``dedupe`` keeps the newest."""
db = sqlite3.connect(str(db_path))
try:
rows = db.execute("""
select t.request_id, t.timestamp, tr.track_key, tr.track_title,
tr.release_date, tr.cover_art
from tag t left join track tr on tr.track_key = t.track_key
order by t.timestamp desc""").fetchall()
artists: dict[str, list[str]] = {}
for key, name in db.execute("""
select aat.track_key, a.artist_name
from apple_artist_track aat
join artist a on a.artist_id = aat.artist_adam_id"""):
artists.setdefault(key, []).append(name)
genres: dict[str, list[str]] = {}
# 'mz' genres are opaque Apple ids; 'editorial' ones are words.
for key, genre in db.execute(
"select track_key, genre_id from track_genre "
"where genre_type = 'editorial'"):
genres.setdefault(key, []).append(genre)
finally:
db.close()
songs = []
for rid, ts, key, title, release, art in rows:
if not title:
continue
m = re.search(r"/(\d{11,13})_cover", art or "")
songs.append(ShazamSong(
request_id=str(rid),
when=datetime.fromtimestamp((ts or 0) / 1000),
title=title,
artist=", ".join(dict.fromkeys(artists.get(key) or [])),
year=_year(release),
genre=", ".join(dict.fromkeys(genres.get(key) or [])),
upc=m.group(1) if m else ""))
return songs
def dedupe(songs: list[ShazamSong]) -> list[ShazamSong]:
"""One row per song (the newest Shazam of it), in the order given."""
seen, out = set(), []
for song in songs:
key = key_of(song.artist, song.title)
if key not in seen:
seen.add(key)
out.append(song)
return out
# ---- what's been dealt with ----
def handled_ids(prefs) -> set[str]:
return set((prefs.get(PREFS_KEY) or {}).get("handled", {}))
def mark_handled(prefs, request_ids, when: datetime | None = None):
"""Add ids to the synced list, in one save."""
data = dict(prefs.get(PREFS_KEY) or {})
handled = dict(data.get("handled", {}))
stamp = (when or datetime.now()).strftime("%Y-%m-%d")
added = False
for rid in request_ids:
if rid not in handled:
handled[rid] = stamp
added = True
if added:
data["handled"] = handled
prefs.set(PREFS_KEY, data)
def legacy_handled(path: Path = LEGACY_STATE) -> set[str]:
"""Ids the /shazam-import skill already fetched on this machine."""
try:
return set(json.loads(path.read_text(encoding="utf-8"))
.get("done", {}))
except (OSError, ValueError, AttributeError):
return set()
# ---- already in the library? ----
_PARENS = re.compile(r"[\(\[]\s*(feat|ft|with|remaster|remastered|original|"
r"official|explicit|bonus|deluxe|mono|stereo|single "
r"version|album version|radio edit)\b[^\)\]]*[\)\]]", re.I)
_FEAT = re.compile(r"\s+(feat\.?|ft\.?|featuring)\s+.*$", re.I)
def key_of(artist: str, title: str) -> tuple[str, str]:
t = _FEAT.sub(" ", _PARENS.sub(" ", title or ""))
t = re.sub(r"^the\s+", "", fold(t))
return fold(artist), t
def match_library(songs: list[ShazamSong], tracks) -> None:
"""Set ``in_library`` on every song the library already has: the same
artist and title once "(feat. …)"/"(Remastered)" are stripped, or a
title sharing 80 % of its words with an artist in common."""
exact, index = {}, []
for t in tracks:
a, n = key_of(t.artist, t.name)
if not n:
continue
exact.setdefault((a, n), t)
index.append((toks(t.name), toks(t.artist), t))
for song in songs:
hit = exact.get(key_of(song.artist, song.title))
if hit is None:
nt, at = toks(song.title), toks(song.artist)
best, best_score = None, 0.0
for ltok, latok, t in index:
if not nt or not (nt & ltok):
continue
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:
best, best_score = t, score
hit = best
if hit is not None:
song.in_library = (f"{hit.artist} — {hit.name}" if hit.artist
else hit.name)
# ---- choosing the YouTube result ----
# Each rejects a result whose title (or, for the first few, channel) says
# it — unless the Shazam title says so too: a Shazam of a live recording
# wants the live recording.
_NOT_THE_SONG = {
"live": r"live|concert|tiny desk|boiler room|festival|unplugged|"
r"rehearsal|soundcheck|in.studio|session|acoustic",
"cover": r"cover(ed)?( by)?|tribute|in the style of|made famous by|"
r"originally (performed|by)",
"karaoke": r"karaoke|instrumental|backing track|no vocals|"
r"without vocals|minus one|sing ?along|sing king",
"clean": r"clean( version| edit)?|censored|radio clean",
"vinyl": r"vinyl|turntable|record player|needle ?drop|phonograph|"
r"gramophone|\d{2} ?rpm",
"altered": r"sped up|speed up|slowed|reverb|nightcore|8d( audio)?|"
r"bass ?boost(ed)?|remix|mashup|lo-?fi|chopped|screwed|"
r"extended|loop|1 hour|10 hours",
"other": r"reaction|reacts?|tutorial|lesson|how to play|"
r"drum cam|guitar|piano version|full album|dj set|mix ?tape|"
r"megamix|lyrics? breakdown|explained|review|teaser|snippet|"
r"preview|short",
}
_NOT_THE_SONG_RE = {why: re.compile(rf"\b({pattern})\b", re.I)
for why, pattern in _NOT_THE_SONG.items()}
# Words about the *upload*, which a channel name can carry too.
_CHANNEL_CHECKED = ("cover", "karaoke")
_VIDEO = re.compile(r"\b(official (music )?video|music video|mv|videoclip)\b",
re.I)
_AUDIO = re.compile(r"(official audio|full audio|\(audio\)|\[audio\]|"
r"\bvisuali[sz]er\b|\bhq audio\b|\bfull song\b|"
r"\baudio oficial\b)", re.I)
_LYRICS = re.compile(r"\b(lyrics?|lyric video|letra)\b", re.I)
def not_the_song(title: str, channel: str, wanted: str) -> str:
"""Why a result isn't the plain studio recording, or ''."""
for why, regex in _NOT_THE_SONG_RE.items():
if regex.search(wanted or ""):
continue
if regex.search(title or ""):
return why
if why in _CHANNEL_CHECKED and regex.search(channel or ""):
return why
return ""
def score_hit(hit: dict, song: ShazamSong) -> tuple[float | None, str]:
"""(score, why) for one search result; score None means rejected."""
title, channel = hit.get("title") or "", hit.get("channel") or ""
reason = not_the_song(title, channel, song.title)
if reason:
return None, reason
want = toks(song.title)
overlap = len(want & toks(title)) / len(want) if want else 0
if overlap < 0.6:
return None, "title mismatch"
score, why = overlap * 20, []
if channel.endswith("- Topic"):
score += 40
why.append("Topic")
# The artist's own channel counts for more than a stranger's "(Audio)":
# a label's upload titled just the song is the release's own audio.
if toks(song.artist) & toks(channel):
score += 25
why.append("artist's channel")
if _AUDIO.search(title):
score += 15
why.append("audio")
if fold(title) in (fold(song.title),
fold(f"{song.artist} {song.title}")):
score += 10
why.append("just the title")
if _LYRICS.search(title):
score += 3
why.append("lyrics")
if _VIDEO.search(title):
score -= 15
why.append("music video")
length = hit.get("duration")
if song.canon_secs and length:
off = abs(length - song.canon_secs)
if off <= 3:
score += 45
why.append("exact length")
elif off <= 8:
score += 30
why.append("±8 s")
elif off <= 20:
score += 8
why.append("±20 s")
else:
return None, f"length off by {off:.0f} s"
elif length and (length < 45 or length > 1500):
return None, "implausible length"
score += min(hit.get("views") or 0, 5_000_000) / 1_000_000
return score, "+".join(why) or "-"
def rank_hits(hits: list[dict], song: ShazamSong) -> list[dict]:
"""The results that are the song, best first (YouTube's order breaks a
tie). Each gets ``score`` and ``why``."""
scored = []
for position, hit in enumerate(hits):
score, why = score_hit(hit, song)
if score is not None:
scored.append((-score, position, {**hit, "score": score,
"why": why}))
return [hit for *_k, hit in sorted(scored, key=lambda x: x[:2])]
def search_queries(song: ShazamSong) -> list[tuple[str, str]]:
"""(yt-dlp search prefix, query) in the order tried: YouTube as Shazam
names it, YouTube without "(… Remix)"-style suffixes (what finds a DJ
edit), then SoundCloud."""
plain = f"{song.artist} {song.title}".strip()
bare = re.sub(r"\s*[\(\[].*?[\)\]]", "", plain).strip()
queries = [("ytsearch", plain)]
if bare and bare != plain:
queries.append(("ytsearch", bare))
queries.append(("scsearch", plain))
return queries
_COMPILATION = re.compile(r"\b(greatest hits|best of|the hits|collection|"
r"anthology|essential|essentials|definitive|"
r"gold|now that's what)\b", re.I)
def canonical_from_results(results: list[dict], song: ShazamSong):
"""The iTunes Search result that is this recording → (seconds, album,
album artist, confident), or None. A live album never supplies it."""
want, want_artist = toks(song.title), toks(song.artist)
best, best_score = None, -1.0
for item in results:
got = toks(item.get("trackName", ""))
if not got:
continue
score = len(want & got) / len(want | got) if want else 0
if want_artist & toks(item.get("artistName", "")):
score += 0.5
if "live" in got and "live" not in want:
score -= 0.6
collection = fold(item.get("collectionName", "")).split()
if (("live" in collection or "concert" in collection)
and "live" not in want):
score -= 0.8
# The album it came out on, not a hits collection it's also on.
if _COMPILATION.search(item.get("collectionName", "")):
score -= 0.3
if song.year and _year(item.get("releaseDate")) == song.year:
score += 0.3
if score > best_score:
best, best_score = item, score
if not best or not best.get("trackTimeMillis"):
return None
return (best["trackTimeMillis"] // 1000, best.get("collectionName", ""),
best.get("artistName", ""), best_score >= 0.9)
def tag_fields(song: ShazamSong) -> dict:
"""What Shazam (and Apple, when it was sure) knows, as Track fields for
``tagging.write_tags``. Apple's album only when its match was confident
or the barcode named it: a loose match hands back a compilation."""
fields = {"name": song.title, "artist": song.artist}
if song.year:
fields["year"] = song.year
if song.genre:
fields["genre"] = song.genre
if song.album and (song.album_confident or song.upc):
fields["album"] = song.album
if song.album_artist:
fields["album_artist"] = song.album_artist
return {k: v for k, v in fields.items() if v}
# ---- network ----
def _itunes(url: str, **params) -> list[dict]:
resp = requests.get(url, params=params, timeout=TIMEOUT,
headers={"User-Agent": USER_AGENT})
resp.raise_for_status()
return resp.json().get("results", [])
def look_up(song: ShazamSong) -> None:
"""Fill in Apple's length and album. Failing is fine: the search then
runs without a length filter."""
try:
found = canonical_from_results(_itunes(
ITUNES_SEARCH, term=f"{song.artist} {song.title}".strip(),
entity="song", media="music", limit=8), song)
except (requests.RequestException, ValueError) as e:
log.info("shazam: iTunes lookup for %s failed: %s", song.label(), e)
found = None
if found is not None:
song.canon_secs, song.album, song.album_artist, \
song.album_confident = found
if not song.album and song.upc:
try:
for item in _itunes(ITUNES_LOOKUP, upc=song.upc, entity="song",
limit=30):
if item.get("wrapperType") == "collection":
song.album = item.get("collectionName", "")
song.album_artist = item.get("artistName", "")
break
except (requests.RequestException, ValueError):
pass
def file_seconds(path) -> float | None:
try:
import mutagen
audio = mutagen.File(str(path))
return audio.info.length if audio is not None else None
except Exception:
return None
# ---- adb ----
class ShazamError(Exception):
pass
def _adb(adb: str, serial: str, *args, timeout: int = 30):
return subprocess.run([adb, "-s", serial, *args], capture_output=True,
text=True, timeout=timeout)
def pull_database(adb: str, serial: str, dest: Path, status=lambda s: None):
"""Copy Shazam's database (+ -wal, -shm) into ``dest`` → its path.
Roots adbd for the copy if it wasn't already, and unroots it after."""
def whoami():
try:
return _adb(adb, serial, "shell", "whoami").stdout.strip()
except subprocess.SubprocessError:
return ""
rooted_here = False
if whoami() != "root":
status("Asking the Rabbit for root adb…")
out = _adb(adb, serial, "root")
said = (out.stdout + out.stderr).strip()
if "cannot run as root" in said:
raise ShazamError(
"The Rabbit refused root adb (“" + said + "”), and Shazam's "
"history can't be read without it.")
rooted_here = True
# adbd restarts: the device drops off and comes back.
deadline = time.monotonic() + 30
while whoami() != "root":
if time.monotonic() > deadline:
raise ShazamError("The Rabbit didn't come back as root after "
"adb root. Unplug it, plug it back in, and "
"try again.")
try:
_adb(adb, serial, "wait-for-device", timeout=10)
except subprocess.SubprocessError:
pass
time.sleep(0.5)
try:
status("Copying Shazam's history…")
for suffix in ("", "-wal", "-shm"):
out = _adb(adb, serial, "pull", DEVICE_DB + suffix,
str(dest / f"library.db{suffix}"), timeout=60)
if out.returncode != 0 and suffix == "":
raise ShazamError(
"Couldn't copy Shazam's history off the Rabbit — is "
"Shazam installed?\n\n" + (out.stderr or out.stdout)
.strip())
finally:
if rooted_here:
# Don't leave the device with a root adbd.
try:
_adb(adb, serial, "unroot", timeout=15)
except subprocess.SubprocessError:
pass
return dest / "library.db"
class ShazamReader(QObject):
"""Reads the Rabbit's Shazams on a daemon thread. ``read`` carries every
Shazam (newest first, one per song); ``status`` narrates for the
preview dialog; ``failed`` says why there's nothing."""
status = pyqtSignal(str)
read = pyqtSignal(list)
failed = pyqtSignal(str)
def start(self):
threading.Thread(target=self._run, daemon=True).start()
def _run(self):
from lintunes.andtunes import install
temp = Path(tempfile.mkdtemp(prefix="lintunes-shazam-"))
try:
adb = install.adb_path()
if adb is None:
raise ShazamError("Reading Shazams needs adb, which isn't "
"installed (Fedora: android-tools).")
self.status.emit("Looking for the Rabbit…")
serial = install.rabbit_serial(adb)
if serial is None:
raise ShazamError(
"No Rabbit found over adb. Plug it in, unlock it, and "
"allow USB debugging if it asks.")
db = pull_database(adb, serial, temp, self.status.emit)
songs = dedupe(read_shazams(db))
except (ShazamError, OSError, sqlite3.Error,
subprocess.SubprocessError) as e:
self.failed.emit(str(e))
return
finally:
shutil.rmtree(temp, ignore_errors=True)
self.read.emit(songs)
# ---- the import ----
class ShazamImportWorker(url_import.UrlImportWorker):
"""``UrlImportWorker``'s threading, cancel and cookie retry, for a list
of Shazams: each is looked up on iTunes, searched for, the best result
downloaded (the next if that fails or comes back short), and Shazam's
tags written in before ``landed``.
``stage`` (request id, text) narrates each song for the window:
Looking up, Searching, Downloading n %, Converting, Tagging.
``landed`` is (request id, mp3 path). ``item_failed`` is (request id,
reason). ``finished`` as UrlImportWorker's; ``failed`` only when nothing
landed because YouTube wanted a signed-in browser, or yt-dlp can't run.
"""
stage = pyqtSignal(str, str)
landed = pyqtSignal(str, str)
def __init__(self, songs, parent=None, *, cookies_browser=None,
lookup=look_up):
super().__init__([], parent, cookies_browser=cookies_browser)
self._songs = list(songs)
self._lookup = lookup
self._song: ShazamSong | None = None
self._mode = ""
self._query = ("", "")
self._hits: list[dict] = []
self._files: list[str] = []
def _command(self, cookies_browser):
if self._mode == "search":
prefix, query = self._query
return url_import.build_search_command(
query, SEARCH_RESULTS, cookies_browser, prefix)
return url_import.build_command(self._query[1], self.temp_dir,
cookies_browser)
def _on_parsed(self, parsed):
kind = parsed[0]
rid = self._song.request_id if self._song else ""
if self._mode == "search":
if kind == "hit":
self._hits.append(parsed[1])
return True
return False
if kind == "progress":
self.progress.emit(parsed[1])
self.stage.emit(rid, f"Downloading {parsed[1]}%")
elif kind == "postprocess" and parsed[1:] == ("ExtractAudio",
"started"):
self.stage.emit(rid, "Converting to mp3…")
elif kind == "file" and not self._cancel.is_set():
self._files.append(parsed[1])
return True
return False
def _on_error(self, error):
pass # reported per song
def _search(self, song):
"""→ (results best first, ERROR lines of the last search), or None
when yt-dlp couldn't run."""
errors = []
for prefix, query in search_queries(song):
if self._cancel.is_set():
break
self._mode, self._query, self._hits = "search", (prefix,
query), []
result = self._run_with_retry()
if result is None:
return None
errors = result[1]
ranked = rank_hits(self._hits, song)
if ranked:
return ranked, errors
return [], errors
def _download(self, hit):
"""→ (path or '', why not), or None when yt-dlp couldn't run."""
self._mode, self._query, self._files = "download", ("", hit["url"]), []
result = self._run_with_retry()
if result is None:
return None
if not self._files:
errors = result[1]
return "", errors[-1] if errors else "download failed"
path = self._files[-1]
length, listed = file_seconds(path), hit.get("duration")
if length is None:
return "", "the download isn't a playable file"
if listed and abs(length - listed) > TRUNCATED_SLACK:
Path(path).unlink(missing_ok=True)
return "", (f"the download was cut short ({length:.0f} s of "
f"{listed} s)")
return path, ""
def _run(self):
landed, errors, bot_errors = 0, [], []
for song in self._songs:
if self._cancel.is_set():
break
rid = self._song_started(song)
self.stage.emit(rid, "Looking up…")
self._lookup(song)
if self._cancel.is_set():
break
self.stage.emit(rid, "Searching YouTube…")
searched = self._search(song)
if searched is None:
return
hits, run_errors = searched
path, reason = "", ""
if not hits:
reason = (run_errors[-1] if run_errors else
"nothing found that's just the song (no studio "
"version on YouTube or SoundCloud)")
if run_errors and url_import.is_bot_check(run_errors[-1]):
bot_errors = run_errors
for hit in hits[:TRIES]:
if self._cancel.is_set():
break
self.stage.emit(rid, "Downloading…")
got = self._download(hit)
if got is None:
return
path, reason = got
if path:
log.info("shazam: %s ← %s (%s)", song.label(),
hit["url"], hit.get("why"))
break
if self._cancel.is_set() and not path:
break
if not path:
errors.append(f"{song.label()}: {reason}")
self.item_failed.emit(rid, reason)
continue
self.stage.emit(rid, "Tagging…")
try:
tagging.write_tags(path, tag_fields(song))
except Exception as e: # untagged still beats not imported
log.warning("shazam tags for %s: %s", path, e)
landed += 1
self.landed.emit(rid, path)
cancelled = self._cancel.is_set()
self._busy = False
if landed == 0 and not cancelled and bot_errors:
self._fail_nothing(bot_errors, self._cookies, 1, "download")
return
self.finished.emit({"downloaded": landed, "errors": errors,
"cancelled": cancelled})
def _song_started(self, song) -> str:
self._song = song
index = self._songs.index(song) + 1
self.item_started.emit(index, len(self._songs), song.request_id,
song.label())
return song.request_id