621 lines
22 KiB
Python
621 lines
22 KiB
Python
from __future__ import annotations
|
||
|
||
import math
|
||
import sys
|
||
import time
|
||
import urllib.parse
|
||
from collections import Counter, defaultdict
|
||
from datetime import datetime, timezone
|
||
|
||
from .cache import is_fresh, load_json, save_json
|
||
from .config import Settings
|
||
from .lastfm import LastFM, LastFMError
|
||
from .navidrome import Navidrome
|
||
from .net import RateLimiter
|
||
from .text import best_match, normalize, track_key
|
||
|
||
|
||
def _log(message: str) -> None:
|
||
print(f"[lastrecc] {message}", file=sys.stderr, flush=True)
|
||
|
||
|
||
def _iso(timestamp: int | float) -> str:
|
||
return datetime.fromtimestamp(timestamp, timezone.utc).isoformat().replace("+00:00", "Z")
|
||
|
||
|
||
def _int(value) -> int:
|
||
try:
|
||
return int(value)
|
||
except (TypeError, ValueError):
|
||
return 0
|
||
|
||
|
||
def _duration_seconds(value) -> int:
|
||
seconds = _int(value)
|
||
if seconds > 10_000: # Last.fm's track.getInfo returns milliseconds
|
||
seconds //= 1000
|
||
return seconds
|
||
|
||
|
||
def _recency_weight(timestamp: int, now: int, half_life_days: float = 14.0) -> float:
|
||
age_days = max(0.0, (now - timestamp) / 86400.0)
|
||
return 0.5 ** (age_days / half_life_days)
|
||
|
||
|
||
def _artist_of(track: dict) -> str:
|
||
artist = track.get("artist")
|
||
if isinstance(artist, dict):
|
||
return artist.get("name") or ""
|
||
return artist or ""
|
||
|
||
|
||
def _candidate(
|
||
*,
|
||
artist: str,
|
||
title: str,
|
||
source: str,
|
||
seed: dict,
|
||
similarity: float,
|
||
playcount: int = 0,
|
||
url: str = "",
|
||
image: str | None = None,
|
||
) -> dict:
|
||
return {
|
||
"artist": artist.strip(),
|
||
"title": title.strip(),
|
||
"album": "",
|
||
"source": source,
|
||
"seed": seed,
|
||
"similarity": max(0.0, min(1.0, similarity)),
|
||
"playcount": playcount,
|
||
"url": url,
|
||
"image_hint": image,
|
||
"sources": [{"source": source, "seed": seed, "similarity": similarity}],
|
||
}
|
||
|
||
|
||
def build_feed(settings: Settings, force: bool = False) -> dict:
|
||
feed_path = settings.cache_dir / "feed.json"
|
||
if not force:
|
||
cached = load_json(feed_path)
|
||
if (
|
||
cached
|
||
and cached.get("window", {}).get("days") == settings.days
|
||
and is_fresh(feed_path, 15 * 60)
|
||
):
|
||
return cached
|
||
|
||
_log(f"building {settings.days}-day feed for {settings.navidrome_user}")
|
||
nav = Navidrome(settings)
|
||
lastfm = LastFM(
|
||
settings.lastfm_api_key,
|
||
settings.cache_dir,
|
||
rate_limiter=RateLimiter(settings.lastfm_rate),
|
||
)
|
||
|
||
all_scrobbles = nav.get_scrobbles(force=force)
|
||
if not all_scrobbles:
|
||
raise RuntimeError("No scrobbles found for this Navidrome user")
|
||
|
||
now = int(time.time())
|
||
window_start = now - settings.days * 86400
|
||
week = [
|
||
item
|
||
for item in all_scrobbles
|
||
if _int(item.get("submissionTime")) >= window_start
|
||
]
|
||
if not week:
|
||
raise RuntimeError(f"No plays in the last {settings.days} days")
|
||
|
||
all_ids = {item["mediaFileId"] for item in all_scrobbles if item.get("mediaFileId")}
|
||
week_ids = {item["mediaFileId"] for item in week if item.get("mediaFileId")}
|
||
_log(f"{len(week)} plays / {len(week_ids)} tracks in window; resolving metadata")
|
||
songs = nav.get_songs(all_ids)
|
||
_log(f"resolved metadata for {len(songs)} of {len(all_ids)} tracks")
|
||
|
||
artist_plays: Counter[str] = Counter()
|
||
artist_weight: defaultdict[str, float] = defaultdict(float)
|
||
track_plays: Counter[tuple[str, str]] = Counter()
|
||
track_weight: defaultdict[tuple[str, str], float] = defaultdict(float)
|
||
album_plays: Counter[tuple[str, str]] = Counter()
|
||
day_plays: Counter[str] = Counter()
|
||
total_seconds = 0
|
||
before_ids = {
|
||
item["mediaFileId"]
|
||
for item in all_scrobbles
|
||
if _int(item.get("submissionTime")) < window_start and item.get("mediaFileId")
|
||
}
|
||
|
||
for item in week:
|
||
song = songs.get(item.get("mediaFileId"))
|
||
if not song:
|
||
continue
|
||
artist = song.get("artist") or "Unknown artist"
|
||
title = song.get("title") or ""
|
||
album = song.get("album") or ""
|
||
if not title:
|
||
continue
|
||
weight = _recency_weight(_int(item.get("submissionTime")), now)
|
||
artist_plays[artist] += 1
|
||
artist_weight[artist] += weight
|
||
track_plays[(artist, title)] += 1
|
||
track_weight[(artist, title)] += weight
|
||
if album:
|
||
album_plays[(album, artist)] += 1
|
||
total_seconds += _duration_seconds(song.get("duration"))
|
||
day = datetime.fromtimestamp(_int(item.get("submissionTime")), timezone.utc)
|
||
day_plays[day.strftime("%Y-%m-%d")] += 1
|
||
|
||
history_keys = {
|
||
track_key(song.get("artist") or "", song.get("title") or "")
|
||
for song in songs.values()
|
||
if song.get("artist") and song.get("title")
|
||
}
|
||
history_artists = {normalize(song.get("artist") or "") for song in songs.values()}
|
||
|
||
top_artist_rows = sorted(
|
||
artist_weight.items(), key=lambda item: item[1], reverse=True
|
||
)[: settings.seed_artists]
|
||
if not top_artist_rows:
|
||
raise RuntimeError("Could not determine top artists")
|
||
max_artist_weight = top_artist_rows[0][1] or 1.0
|
||
seed_artists = [
|
||
{
|
||
"name": name,
|
||
"plays": artist_plays[name],
|
||
"weight": weight / max_artist_weight,
|
||
}
|
||
for name, weight in top_artist_rows
|
||
]
|
||
seed_artist_names = {seed["name"] for seed in seed_artists}
|
||
seed_artist_norm = {normalize(name) for name in seed_artist_names}
|
||
|
||
top_track_rows = sorted(
|
||
track_weight.items(), key=lambda item: item[1], reverse=True
|
||
)[: settings.seed_tracks]
|
||
max_track_weight = top_track_rows[0][1] if top_track_rows else 1.0
|
||
seed_tracks = [
|
||
{
|
||
"artist": artist,
|
||
"title": title,
|
||
"plays": track_plays[(artist, title)],
|
||
"weight": weight / max_track_weight,
|
||
}
|
||
for (artist, title), weight in top_track_rows
|
||
if title
|
||
]
|
||
|
||
_log(
|
||
"seeds: "
|
||
+ ", ".join(f"{seed['name']} ({seed['plays']})" for seed in seed_artists[:5])
|
||
)
|
||
|
||
candidates: dict[str, dict] = {}
|
||
|
||
def add_candidate(
|
||
*,
|
||
artist: str,
|
||
title: str,
|
||
source: str,
|
||
seed: dict,
|
||
similarity: float,
|
||
playcount: int = 0,
|
||
url: str = "",
|
||
image: str | None = None,
|
||
) -> None:
|
||
artist = (artist or "").strip()
|
||
title = (title or "").strip()
|
||
if not artist or not title:
|
||
return
|
||
key = track_key(artist, title)
|
||
if key in history_keys:
|
||
return
|
||
base = max(0.0, min(1.0, similarity)) * seed["weight"]
|
||
entry = _candidate(
|
||
artist=artist,
|
||
title=title,
|
||
source=source,
|
||
seed=seed,
|
||
similarity=similarity,
|
||
playcount=playcount,
|
||
url=url,
|
||
image=image,
|
||
)
|
||
entry["base"] = base
|
||
existing = candidates.get(key)
|
||
if existing:
|
||
existing["sources"].append(entry["sources"][0])
|
||
if base > existing.get("base", 0):
|
||
entry["sources"] = existing["sources"]
|
||
candidates[key] = entry
|
||
return
|
||
candidates[key] = entry
|
||
|
||
# Similar artists -> their top tracks
|
||
for index, seed in enumerate(seed_artists, start=1):
|
||
_log(f"artist seeds {index}/{len(seed_artists)}: {seed['name']}")
|
||
try:
|
||
similar = lastfm.artist_similar(seed["name"], limit=20)
|
||
except LastFMError as exc:
|
||
_log(f" skip {seed['name']}: {exc}")
|
||
continue
|
||
ranked = [
|
||
item
|
||
for item in similar
|
||
if item.get("name")
|
||
and normalize(item.get("name")) != normalize(seed["name"])
|
||
]
|
||
ranked.sort(key=lambda item: lastfm.match(item.get("match")), reverse=True)
|
||
for similar_artist in ranked[: settings.similar_artists_per_seed]:
|
||
similar_name = similar_artist.get("name") or ""
|
||
similarity = lastfm.match(similar_artist.get("match"))
|
||
try:
|
||
tracks = lastfm.artist_top_tracks(
|
||
similar_name, limit=settings.top_tracks_per_artist
|
||
)
|
||
except LastFMError:
|
||
continue
|
||
for track in tracks:
|
||
add_candidate(
|
||
artist=_artist_of(track) or similar_name,
|
||
title=track.get("name") or "",
|
||
source="artist",
|
||
seed={
|
||
"type": "artist",
|
||
"artist": seed["name"],
|
||
"title": None,
|
||
"plays": seed["plays"],
|
||
"weight": seed["weight"],
|
||
},
|
||
similarity=similarity,
|
||
playcount=_int(track.get("playcount")),
|
||
url=track.get("url") or "",
|
||
)
|
||
|
||
# Similar tracks
|
||
for index, seed in enumerate(seed_tracks, start=1):
|
||
_log(f"track seeds {index}/{len(seed_tracks)}: {seed['artist']} — {seed['title']}")
|
||
try:
|
||
similar = lastfm.track_similar(
|
||
seed["artist"], seed["title"], limit=settings.similar_tracks_per_seed
|
||
)
|
||
except LastFMError as exc:
|
||
_log(f" skip: {exc}")
|
||
continue
|
||
for track in similar:
|
||
artist = _artist_of(track)
|
||
title = track.get("name") or ""
|
||
if not artist or not title:
|
||
continue
|
||
add_candidate(
|
||
artist=artist,
|
||
title=title,
|
||
source="track",
|
||
seed={
|
||
"type": "track",
|
||
"artist": seed["artist"],
|
||
"title": seed["title"],
|
||
"plays": seed["plays"],
|
||
"weight": seed["weight"],
|
||
},
|
||
similarity=lastfm.match(track.get("match")),
|
||
playcount=_int(track.get("playcount")),
|
||
url=track.get("url") or "",
|
||
image=LastFM.image_from_track(track),
|
||
)
|
||
|
||
if not candidates:
|
||
_log("Last.fm returned no new track candidates; using unplayed albums only")
|
||
|
||
_log(f"{len(candidates)} candidates before ranking")
|
||
for candidate in candidates.values():
|
||
artist_norm = normalize(candidate["artist"])
|
||
novelty = 1.0
|
||
if artist_norm not in history_artists:
|
||
novelty = 1.12
|
||
elif artist_norm not in seed_artist_norm:
|
||
novelty = 1.05
|
||
candidate["score"] = (
|
||
candidate["base"]
|
||
* (1.0 + math.log1p(candidate["playcount"]) / 30.0)
|
||
* novelty
|
||
)
|
||
|
||
ranked = sorted(candidates.values(), key=lambda item: item["score"], reverse=True)
|
||
shortlist: list[dict] = []
|
||
per_artist: Counter[str] = Counter()
|
||
for candidate in ranked:
|
||
artist_norm = normalize(candidate["artist"])
|
||
if per_artist[artist_norm] >= 2:
|
||
continue
|
||
shortlist.append(candidate)
|
||
per_artist[artist_norm] += 1
|
||
if len(shortlist) >= settings.feed_size + 18:
|
||
break
|
||
|
||
_log(f"enriching {len(shortlist)} shortlisted tracks")
|
||
enriched: list[dict] = []
|
||
for index, candidate in enumerate(shortlist, start=1):
|
||
info: dict = {}
|
||
try:
|
||
info = lastfm.track_info(candidate["artist"], candidate["title"])
|
||
except LastFMError:
|
||
pass
|
||
|
||
album = ""
|
||
image = candidate.get("image_hint")
|
||
lastfm_url = candidate.get("url") or ""
|
||
duration = 0
|
||
if info:
|
||
album_obj = info.get("album") or {}
|
||
if isinstance(album_obj, dict):
|
||
album = album_obj.get("title") or ""
|
||
image = LastFM.image_from_track(info) or image
|
||
lastfm_url = info.get("url") or lastfm_url
|
||
duration = _duration_seconds(info.get("duration"))
|
||
|
||
nav_match = None
|
||
try:
|
||
results = nav.search_songs(
|
||
f"{candidate['artist']} {candidate['title']}", limit=5
|
||
)
|
||
nav_match = best_match(results, candidate["artist"], candidate["title"])
|
||
except Exception as exc: # noqa: BLE001 - one bad match must not kill the feed
|
||
_log(f" library search failed for {candidate['artist']}: {exc}")
|
||
|
||
card = dict(candidate)
|
||
card["type"] = "track"
|
||
card["album"] = album
|
||
card["duration"] = duration
|
||
card["lastfm_url"] = lastfm_url or (
|
||
"https://www.last.fm/music/"
|
||
+ urllib.parse.quote(candidate["artist"], safe="")
|
||
+ "/_/"
|
||
+ urllib.parse.quote(candidate["title"], safe="")
|
||
)
|
||
card["image"] = image
|
||
card["image_remote"] = image
|
||
card["playable"] = False
|
||
card["song_id"] = None
|
||
card["album_id"] = None
|
||
card["stream_url"] = None
|
||
card["navidrome_url"] = None
|
||
card["in_library"] = False
|
||
|
||
if nav_match:
|
||
card["playable"] = True
|
||
card["in_library"] = True
|
||
card["song_id"] = nav_match.get("id")
|
||
card["album_id"] = nav_match.get("albumId")
|
||
card["album"] = nav_match.get("album") or album
|
||
card["duration"] = _duration_seconds(nav_match.get("duration")) or duration
|
||
cover_id = nav_match.get("coverArt")
|
||
if cover_id:
|
||
card["image"] = f"/api/cover/{urllib.parse.quote(str(cover_id), safe='')}?size=300"
|
||
if card["song_id"]:
|
||
card["stream_url"] = (
|
||
f"/api/stream/{urllib.parse.quote(str(card['song_id']), safe='')}"
|
||
)
|
||
card["navidrome_url"] = nav.page_url(
|
||
album_id=card["album_id"], song_id=card["song_id"]
|
||
)
|
||
|
||
card["similarity"] = round(card["similarity"], 4)
|
||
card["match_pct"] = max(1, min(99, round(card["similarity"] * 100)))
|
||
card["score"] = round(card["score"], 4)
|
||
if card["playable"]:
|
||
card["score"] = round(card["score"] * 1.18, 4)
|
||
card["is_new_artist"] = normalize(card["artist"]) not in history_artists
|
||
|
||
seed = card["seed"]
|
||
if seed["type"] == "track":
|
||
card["reason"] = f"Similar to “{seed['title']}” by {seed['artist']}"
|
||
card["reason_kind"] = "similar_track"
|
||
if normalize(card["artist"]) == normalize(seed["artist"]):
|
||
card["reason"] = f"Another track near “{seed['title']}”"
|
||
else:
|
||
seed_norm = normalize(seed["artist"])
|
||
card_norm = normalize(card["artist"])
|
||
if card_norm == seed_norm:
|
||
card["reason"] = f"An unheard track from {card['artist']}"
|
||
card["reason_kind"] = "known_artist"
|
||
elif card_norm in seed_artist_norm:
|
||
card["reason"] = (
|
||
f"More from {card['artist']}, an artist you played "
|
||
f"{artist_plays.get(card['artist'], 0)}×"
|
||
)
|
||
card["reason_kind"] = "known_artist"
|
||
else:
|
||
card["reason"] = (
|
||
f"Because you played {seed['artist']} {seed['plays']}× this week"
|
||
)
|
||
card["reason_kind"] = "similar_artist"
|
||
|
||
if card["is_new_artist"] and card["reason_kind"] == "similar_artist":
|
||
card["reason"] = f"New artist · because you played {seed['artist']}"
|
||
|
||
# If several seeds point at the same track, say so — closer to the
|
||
# "Similar to X, Y and Z" explanations on Last.fm's own home page.
|
||
source_artists: list[str] = []
|
||
source_tracks: list[str] = []
|
||
for source in card.get("sources", []):
|
||
seed_info = source.get("seed") or {}
|
||
if seed_info.get("type") == "artist" and seed_info.get("artist"):
|
||
if seed_info["artist"] not in source_artists:
|
||
source_artists.append(seed_info["artist"])
|
||
if seed_info.get("type") == "track" and seed_info.get("title"):
|
||
label = f"“{seed_info['title']}”"
|
||
if label not in source_tracks:
|
||
source_tracks.append(label)
|
||
if card["reason_kind"] == "similar_artist" and len(source_artists) >= 2:
|
||
names = source_artists[:3]
|
||
card["reason"] = "Similar to " + ", ".join(names[:-1]) + " and " + names[-1]
|
||
elif card["reason_kind"] == "similar_track" and len(source_tracks) >= 2:
|
||
card["reason"] = "Similar to " + ", ".join(source_tracks[:2]) + " and more"
|
||
|
||
card["id"] = track_key(card["artist"], card["title"])
|
||
enriched.append(card)
|
||
if index % 10 == 0:
|
||
_log(f" enriched {index}/{len(shortlist)}")
|
||
|
||
# Unplayed albums from artists joren already listens to. This is the
|
||
# "you've scrobbled this artist before, but not this release" card.
|
||
history_album_ids = {
|
||
song.get("albumId") for song in songs.values() if song.get("albumId")
|
||
}
|
||
history_album_keys = {
|
||
(normalize(song.get("artist") or ""), normalize(song.get("album") or ""))
|
||
for song in songs.values()
|
||
if song.get("album") and song.get("artist")
|
||
}
|
||
artist_ids: dict[str, str] = {}
|
||
for item in week:
|
||
song = songs.get(item.get("mediaFileId"))
|
||
if song and song.get("artistId"):
|
||
artist_ids.setdefault(normalize(song.get("artist") or ""), song["artistId"])
|
||
|
||
album_cards: list[dict] = []
|
||
for seed in seed_artists:
|
||
artist_id = artist_ids.get(normalize(seed["name"]))
|
||
if not artist_id:
|
||
continue
|
||
try:
|
||
data = nav.subsonic("getArtist", id=artist_id)
|
||
except Exception as exc: # noqa: BLE001
|
||
_log(f" album lookup failed for {seed['name']}: {exc}")
|
||
continue
|
||
artist_data = data.get("artist", {}) or {}
|
||
albums = artist_data.get("album", [])
|
||
if isinstance(albums, dict):
|
||
albums = [albums]
|
||
unplayed = []
|
||
for album in albums:
|
||
if not isinstance(album, dict):
|
||
continue
|
||
album_id = album.get("id")
|
||
album_name = album.get("name") or ""
|
||
if not album_id or not album_name:
|
||
continue
|
||
if album_id in history_album_ids:
|
||
continue
|
||
if (normalize(seed["name"]), normalize(album_name)) in history_album_keys:
|
||
continue
|
||
if _int(album.get("songCount")) < 3:
|
||
continue
|
||
unplayed.append(album)
|
||
if not unplayed:
|
||
continue
|
||
unplayed.sort(
|
||
key=lambda album: (_int(album.get("year")), str(album.get("created") or "")),
|
||
reverse=True,
|
||
)
|
||
album = unplayed[0]
|
||
cover = album.get("coverArt")
|
||
album_cards.append(
|
||
{
|
||
"id": "album::" + track_key(seed["name"], album["name"]),
|
||
"type": "album",
|
||
"artist": seed["name"],
|
||
"title": album["name"],
|
||
"album": album["name"],
|
||
"track_count": _int(album.get("songCount")),
|
||
"duration": _int(album.get("duration")),
|
||
"image": (
|
||
f"/api/cover/{urllib.parse.quote(str(cover), safe='')}?size=300"
|
||
if cover
|
||
else None
|
||
),
|
||
"image_remote": None,
|
||
"playable": True,
|
||
"in_library": True,
|
||
"song_id": None,
|
||
"album_id": album["id"],
|
||
"stream_url": None,
|
||
"navidrome_url": nav.page_url(album_id=album["id"]),
|
||
"lastfm_url": (
|
||
"https://www.last.fm/music/"
|
||
+ urllib.parse.quote(seed["name"], safe="")
|
||
+ "/"
|
||
+ urllib.parse.quote(album["name"], safe="")
|
||
),
|
||
"similarity": 1.0,
|
||
"match_pct": 100,
|
||
"score": round(0.66 + 0.28 * seed["weight"], 4),
|
||
"is_new_artist": False,
|
||
"reason": f"An album you haven't played from {seed['name']}",
|
||
"reason_kind": "unplayed_album",
|
||
"seed": {
|
||
"type": "artist",
|
||
"artist": seed["name"],
|
||
"title": None,
|
||
"plays": seed["plays"],
|
||
"weight": seed["weight"],
|
||
},
|
||
}
|
||
)
|
||
_log(f"added {len(album_cards)} unplayed album cards")
|
||
|
||
if album_cards:
|
||
enriched.extend(album_cards)
|
||
enriched.sort(key=lambda card: card["score"], reverse=True)
|
||
|
||
# Final diversity pass and trim.
|
||
final: list[dict] = []
|
||
artist_count: Counter[str] = Counter()
|
||
album_count: Counter[tuple[str, str]] = Counter()
|
||
for card in enriched:
|
||
artist_norm = normalize(card["artist"])
|
||
album_norm = normalize(card.get("album") or "")
|
||
if artist_count[artist_norm] >= 2:
|
||
continue
|
||
if album_norm and album_count[(artist_norm, album_norm)] >= 1:
|
||
continue
|
||
final.append(card)
|
||
artist_count[artist_norm] += 1
|
||
if album_norm:
|
||
album_count[(artist_norm, album_norm)] += 1
|
||
if len(final) >= settings.feed_size:
|
||
break
|
||
|
||
if not final:
|
||
raise RuntimeError("No recommendations could be built for this window")
|
||
|
||
stats = {
|
||
"plays": len(week),
|
||
"unique_tracks": len(week_ids),
|
||
"artists": len(artist_plays),
|
||
"albums": len(album_plays),
|
||
"hours": round(total_seconds / 3600.0, 1),
|
||
"first_time_tracks": len(week_ids - before_ids),
|
||
"top_artists": [
|
||
{"name": name, "plays": plays}
|
||
for name, plays in artist_plays.most_common(12)
|
||
],
|
||
"top_tracks": [
|
||
{"title": title, "artist": artist, "plays": plays}
|
||
for (artist, title), plays in track_plays.most_common(10)
|
||
],
|
||
"top_albums": [
|
||
{"album": album, "artist": artist, "plays": plays}
|
||
for (album, artist), plays in album_plays.most_common(8)
|
||
],
|
||
"days": [
|
||
{"day": day, "plays": plays}
|
||
for day, plays in sorted(day_plays.items())
|
||
],
|
||
}
|
||
|
||
feed = {
|
||
"generated_at": _iso(now),
|
||
"window": {
|
||
"days": settings.days,
|
||
"start": _iso(window_start),
|
||
"end": _iso(now),
|
||
},
|
||
"stats": stats,
|
||
"cards": final,
|
||
}
|
||
save_json(feed_path, feed)
|
||
_log(f"feed ready: {len(final)} cards ({sum(1 for c in final if c['playable'])} playable)")
|
||
return feed
|