Mulberry/mulberry/online.py
Mulberry 615b21d64a
Mulberry 1.1.0: Material You music player for Linux and Windows
- KDE/Windows accent-driven Material 3 theme, live updating
- Library, tabbed playlists, smart/saved lists, queue, ratings
- mpv and Qt Multimedia engines, EQ, ReplayGain, gapless
- Synced lyrics (LRCLIB, NetEase, local .lrc), covers, MusicBrainz tags
- Last.fm/ListenBrainz scrobbling, MPRIS, Windows media keys
- Audio CD playback and ripping
- PyInstaller, Inno Setup and AppImage builds via GitHub Actions

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
2026-10-09 23:00:48 -05:00

399 lines
16 KiB
Python

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Online metadata: MusicBrainz tags, cover art (Cover Art Archive, iTunes,
Deezer, Last.fm), synced lyrics (LRCLIB), artist info (Last.fm / Wikipedia),
AcoustID fingerprint lookup. All functions are blocking — call via run_async."""
from __future__ import annotations
import json
import re
import shutil
import subprocess
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from .config import USER_AGENT, settings
from .song import Song
_mb_lock = threading.Lock()
_mb_last = [0.0]
def http_get(url: str, params: dict | None = None, timeout=12, headers=None, raw=False):
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json",
**(headers or {})})
with urllib.request.urlopen(req, timeout=timeout) as r:
data = r.read()
if raw:
return data
return json.loads(data.decode("utf-8", "replace"))
def http_post(url: str, data: dict | bytes, timeout=12, headers=None):
body = data if isinstance(data, bytes) else urllib.parse.urlencode(data).encode()
req = urllib.request.Request(url, data=body, method="POST",
headers={"User-Agent": USER_AGENT, **(headers or {})})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8", "replace") or "{}")
def mb_get(path: str, params: dict):
with _mb_lock: # MusicBrainz: max 1 request/second
wait = 1.05 - (time.time() - _mb_last[0])
if wait > 0:
time.sleep(wait)
_mb_last[0] = time.time()
return http_get(f"https://musicbrainz.org/ws/2/{path}", {**params, "fmt": "json"})
def _clean(s: str) -> str:
s = re.sub(r"\s*[\(\[](feat\.?|ft\.?|with|remaster(ed)?|\d{4} remaster|live|explicit|bonus)[^\)\]]*[\)\]]", "", s, flags=re.I)
return s.strip()
def _q(s: str) -> str:
return re.sub(r'([+\-&|!(){}\[\]^"~*?:\\/])', r"\\\1", s)
# ------------------------------------------------------------------ MusicBrainz
def musicbrainz_search(song: Song, limit=15) -> list[dict]:
"""Search recordings; returns flattened candidates (one per release)."""
parts = []
if song.title:
parts.append(f'recording:"{_q(_clean(song.title))}"')
if song.display_artist():
parts.append(f'artist:"{_q(song.display_artist())}"')
if song.album:
parts.append(f'release:"{_q(_clean(song.album))}"')
if not parts:
return []
res = mb_get("recording", {"query": " AND ".join(parts[:2]) + (f" AND ({parts[2]})" if len(parts) > 2 else ""),
"limit": limit})
out = []
for rec in res.get("recordings", []):
artist = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rec.get("artist-credit", []))
for rel in rec.get("releases", [])[:4] or [{}]:
media = (rel.get("media") or [{}])[0]
trk = (media.get("track") or [{}])[0]
ra = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rel.get("artist-credit", [])) or artist
out.append({
"title": rec.get("title", ""), "artist": artist, "album": rel.get("title", ""),
"albumartist": ra, "year": int((rel.get("date") or "0")[:4] or 0),
"track": int(re.sub(r"\D", "", str(trk.get("number", "0"))) or 0),
"disc": int(media.get("position", 0) or 0),
"length": (rec.get("length") or 0) / 1000,
"mb_trackid": rec.get("id", ""), "mb_albumid": rel.get("id", ""),
"score": int(rec.get("score", 0)), "country": rel.get("country", ""),
"status": rel.get("status", ""),
})
# prefer close length + official releases
if song.length:
for c in out:
if c["length"]:
c["score"] -= min(40, abs(c["length"] - song.length) * 2)
for c in out:
if c["status"] == "Official":
c["score"] += 5
out.sort(key=lambda c: -c["score"])
return out
def musicbrainz_genre(mb_albumid: str) -> str:
try:
r = mb_get(f"release/{mb_albumid}", {"inc": "genres+release-groups"})
g = sorted(r.get("genres", []), key=lambda x: -x.get("count", 0))
return g[0]["name"].title() if g else ""
except Exception: # noqa: BLE001
return ""
def acoustid_lookup(path: str) -> list[dict]:
key = settings.get("online/acoustid_key")
fpcalc = shutil.which("fpcalc")
if not key or not fpcalc:
raise RuntimeError("AcoustID needs an API key (Settings › Metadata) and the 'fpcalc' tool (chromaprint).")
out = subprocess.run([fpcalc, "-json", path], capture_output=True, text=True, timeout=60)
fp = json.loads(out.stdout)
res = http_post("https://api.acoustid.org/v2/lookup", {
"client": key, "meta": "recordings releases", "duration": int(fp["duration"]),
"fingerprint": fp["fingerprint"]})
cands = []
for r in res.get("results", []):
for rec in r.get("recordings", []) or []:
artist = ", ".join(a["name"] for a in rec.get("artists", []))
for rel in (rec.get("releases") or [{}])[:3]:
cands.append({"title": rec.get("title", ""), "artist": artist, "album": rel.get("title", ""),
"albumartist": artist, "year": (rel.get("date") or {}).get("year", 0),
"track": 0, "disc": 0, "mb_trackid": rec.get("id", ""),
"mb_albumid": rel.get("id", ""), "score": int(r.get("score", 0) * 100),
"length": rec.get("duration", 0)})
return cands
# ------------------------------------------------------------------ covers
def cover_candidates(artist: str, album: str, title: str = "") -> list[dict]:
"""Return [{'url','thumb','source','size'}] from several providers."""
out: list[dict] = []
term = f"{artist} {album or title}".strip()
errors = []
def itunes():
r = http_get("https://itunes.apple.com/search", {"term": term, "entity": "album" if album else "song", "limit": 8})
for it in r.get("results", []):
u = it.get("artworkUrl100")
if u:
out.append({"url": u.replace("100x100bb", "1200x1200bb"), "thumb": u.replace("100x100bb", "300x300bb"),
"source": "iTunes", "label": f"{it.get('artistName', '')} – {it.get('collectionName', '')}"})
def deezer():
r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'})
for it in (r.get("data") or [])[:8]:
if it.get("cover_xl"):
out.append({"url": it["cover_xl"], "thumb": it.get("cover_medium") or it["cover_xl"],
"source": "Deezer", "label": f"{it.get('artist', {}).get('name', '')} – {it.get('title', '')}"})
def caa():
if not album:
return
r = mb_get("release", {"query": f'release:"{_q(album)}" AND artist:"{_q(artist)}"', "limit": 5})
for rel in r.get("releases", [])[:5]:
rid = rel["id"]
out.append({"url": f"https://coverartarchive.org/release/{rid}/front",
"thumb": f"https://coverartarchive.org/release/{rid}/front-250",
"source": "Cover Art Archive",
"label": f"{rel.get('title', '')} ({(rel.get('date') or '')[:4]})"})
def lastfm():
from .scrobble import LastFM
key = LastFM.key()[0]
if not key or not album:
return
r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "album.getinfo", "api_key": key,
"artist": artist, "album": album, "format": "json"})
imgs = r.get("album", {}).get("image", [])
if imgs and imgs[-1].get("#text"):
u = imgs[-1]["#text"]
out.append({"url": re.sub(r"/\d+x\d+/", "/", u), "thumb": u, "source": "Last.fm", "label": album})
threads = []
for fn in (itunes, deezer, caa, lastfm):
def wrap(f=fn):
try:
f()
except Exception as e: # noqa: BLE001
errors.append(str(e))
t = threading.Thread(target=wrap, daemon=True)
t.start()
threads.append(t)
for t in threads:
t.join(20)
order = {"Cover Art Archive": 0, "iTunes": 1, "Deezer": 2, "Last.fm": 3}
out.sort(key=lambda c: order.get(c["source"], 9))
return out
def best_cover(artist: str, album: str, title: str = "") -> bytes | None:
"""Automatic fetch: try providers in order, return image bytes."""
if not artist and not album:
return None
for fn in (_auto_itunes, _auto_deezer):
try:
u = fn(artist, album, title)
if u:
data = http_get(u, raw=True, timeout=15)
if data and len(data) > 1000:
return data
except Exception: # noqa: BLE001
continue
return None
def _norm(s):
return re.sub(r"[^a-z0-9]", "", (s or "").lower())
def _auto_itunes(artist, album, title):
term = f"{artist} {album or title}"
r = http_get("https://itunes.apple.com/search", {"term": term, "entity": "album" if album else "song", "limit": 6})
for it in r.get("results", []):
if _norm(artist) and _norm(artist) not in _norm(it.get("artistName")) and _norm(it.get("artistName")) not in _norm(artist):
continue
if album and _norm(_clean(album))[:12] not in _norm(it.get("collectionName")):
continue
u = it.get("artworkUrl100")
if u:
return u.replace("100x100bb", "1000x1000bb")
return None
def _auto_deezer(artist, album, title):
r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'})
for it in r.get("data") or []:
if _norm(artist) in _norm(it.get("artist", {}).get("name")):
return it.get("cover_xl")
return None
def download(url: str) -> bytes:
return http_get(url, raw=True, timeout=20)
# ------------------------------------------------------------------ lyrics
def _lyr_query(song: Song):
artist = song.display_artist()
title = song.display_title()
if song.is_stream and song.stream_title and " - " in song.stream_title:
artist, title = [x.strip() for x in song.stream_title.split(" - ", 1)]
return artist, title
def lyrics_lrclib(song: Song) -> str:
artist, title = _lyr_query(song)
if not title:
return ""
params = {"artist_name": artist, "track_name": _clean(title)}
if song.album and not song.is_stream:
params["album_name"] = song.album
if song.duration() and not song.is_stream:
params["duration"] = int(round(song.duration()))
try:
r = http_get("https://lrclib.net/api/get", params)
if r.get("instrumental"):
return "[instrumental]"
txt = r.get("syncedLyrics") or r.get("plainLyrics") or ""
if txt:
return txt
except urllib.error.HTTPError:
pass
r = http_get("https://lrclib.net/api/search", {"track_name": _clean(title), "artist_name": artist})
best = None
for it in r or []:
if song.duration() and it.get("duration") and abs(it["duration"] - song.duration()) > 6:
continue
if it.get("syncedLyrics"):
best = it
break
best = best or it
return (best.get("syncedLyrics") or best.get("plainLyrics") or "") if best else ""
_NE_HEADERS = {"Referer": "https://music.163.com/",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/124.0 Safari/537.36"}
_NE_CREDIT = re.compile(r"^\s*\[[^\]]*\]\s*(作词|作曲|编曲|制作人|监制|混音|母带|和声|吉他|贝斯|鼓|词|曲|"
r"Lyricist|Lyrics by|Composer|Composed by|Arranger|Producer|Written by)\s*[::]", re.I)
def lyrics_netease(song: Song) -> str:
artist, title = _lyr_query(song)
if not title:
return ""
q = f"{_clean(title)} {artist}".strip()
r = http_get("https://music.163.com/api/search/get/web",
{"s": q, "type": 1, "offset": 0, "limit": 10}, headers=_NE_HEADERS)
songs = (r.get("result") or {}).get("songs") or []
best, best_score = None, -1e9
for it in songs:
score = 0.0
names = " ".join(a.get("name", "") for a in it.get("artists", []))
if _norm(artist) and (_norm(artist) in _norm(names) or _norm(names) in _norm(artist)):
score += 50
if _norm(_clean(title)) == _norm(_clean(it.get("name", ""))):
score += 30
if song.duration() and it.get("duration"):
score -= min(40, abs(it["duration"] / 1000 - song.duration()) * 4)
if score > best_score:
best, best_score = it, score
if not best or best_score < 0:
return ""
lr = http_get("https://music.163.com/api/song/lyric",
{"id": best["id"], "lv": 1, "kv": 1, "tv": -1}, headers=_NE_HEADERS)
txt = ((lr.get("lrc") or {}).get("lyric") or "").strip()
if lr.get("nolyric") or lr.get("uncollected"):
return ""
return "\n".join(ln for ln in txt.splitlines() if not _NE_CREDIT.match(ln))
ONLINE_PROVIDERS = {"lrclib": ("LRCLIB", lyrics_lrclib), "netease": ("NetEase", lyrics_netease)}
def fetch_lyrics(song: Song, source: str = "auto") -> tuple[str, str]:
"""Return (lyrics_text, provider label). In auto mode synced results win:
LRCLIB first, then NetEase; a plain result is kept only as a fallback."""
order = ["lrclib", "netease"] if source == "auto" else [source]
fallback = ("", "")
errors = []
for key in order:
if key not in ONLINE_PROVIDERS:
continue
label, fn = ONLINE_PROVIDERS[key]
try:
txt = fn(song)
except Exception as e: # noqa: BLE001
errors.append(str(e))
continue
if not txt:
continue
if txt == "[instrumental]" or LRC_RE.search(txt):
return txt, label
if not fallback[0]:
fallback = (txt, label)
if fallback[0]:
return fallback
if errors and len(errors) == len(order):
raise RuntimeError(errors[0])
return "", ""
LRC_RE = re.compile(r"\[(\d+):(\d+(?:[.:]\d+)?)\]")
def parse_lrc(text: str) -> tuple[list[tuple[float, str]], bool]:
"""Return ([(time, line)], synced). Unsynced text -> times are -1."""
lines = []
offset = 0.0
m = re.search(r"\[offset:\s*([-+]?\d+)\]", text or "", re.I)
if m:
offset = int(m.group(1)) / 1000
synced = False
for raw in (text or "").splitlines():
stamps = LRC_RE.findall(raw)
content = LRC_RE.sub("", raw).strip()
content = re.sub(r"<\d+:\d+(?:\.\d+)?>", "", content) # enhanced LRC word stamps
if stamps:
synced = True
for mm, ss in stamps:
t = int(mm) * 60 + float(ss.replace(":", ".")) - offset
lines.append((max(t, 0.0), content))
elif not re.match(r"^\[[a-z]+:.*\]$", raw.strip(), re.I):
lines.append((-1.0, raw.strip()))
if synced:
lines = sorted([x for x in lines if x[0] >= 0], key=lambda x: x[0])
return lines, synced
# ------------------------------------------------------------------ artist info
def artist_info(artist: str) -> str:
from .scrobble import LastFM
key = LastFM.key()[0]
if key:
try:
r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "artist.getinfo", "artist": artist,
"api_key": key, "format": "json", "autocorrect": 1})
txt = r.get("artist", {}).get("bio", {}).get("content", "")
txt = re.sub(r"<a href.*?</a>\.?", "", txt).strip()
if txt:
return txt
except Exception: # noqa: BLE001
pass
try:
r = http_get("https://en.wikipedia.org/api/rest_v1/page/summary/" + urllib.parse.quote(artist.replace(" ", "_")))
if r.get("type") == "disambiguation":
r = http_get("https://en.wikipedia.org/api/rest_v1/page/summary/" +
urllib.parse.quote(artist.replace(" ", "_") + "_(band)"))
return r.get("extract", "")
except Exception: # noqa: BLE001
return ""