Initial commit: LastRecc discovery feed and weekly engine
This commit is contained in:
40 files changed
+6972
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""LastRecc: a personal, Last.fm-powered discovery feed for Navidrome."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,83 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
from .config import Settings
|
||||
from .recommend import build_feed
|
||||
from .server import serve
|
||||
|
||||
|
||||
def _settings(args: argparse.Namespace) -> Settings:
|
||||
settings = Settings.load()
|
||||
if getattr(args, "days", None):
|
||||
settings = settings.with_days(args.days)
|
||||
return settings
|
||||
|
||||
|
||||
def cmd_build(args: argparse.Namespace) -> int:
|
||||
settings = _settings(args)
|
||||
feed = build_feed(settings, force=args.refresh)
|
||||
stats = feed.get("stats", {})
|
||||
cards = feed.get("cards", [])
|
||||
playable = sum(1 for card in cards if card.get("playable"))
|
||||
print(
|
||||
f"Built {len(cards)} cards ({playable} playable) from "
|
||||
f"{stats.get('plays', 0)} plays / {stats.get('artists', 0)} artists"
|
||||
)
|
||||
print(f"Window: {feed['window']['start']} → {feed['window']['end']}")
|
||||
print(f"Cache: {settings.cache_dir / 'feed.json'}")
|
||||
if args.json:
|
||||
print(json.dumps(feed, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_serve(args: argparse.Namespace) -> int:
|
||||
settings = _settings(args)
|
||||
if args.warm:
|
||||
print("Warming feed cache…", file=sys.stderr)
|
||||
build_feed(settings)
|
||||
serve(settings, host=args.host, port=args.port)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_stats(args: argparse.Namespace) -> int:
|
||||
settings = _settings(args)
|
||||
from .cache import load_json
|
||||
|
||||
feed = load_json(settings.cache_dir / "feed.json")
|
||||
if not feed:
|
||||
print("No cached feed yet. Run: python -m lastrecc build", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(feed.get("stats", {}), ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="lastrecc", description="Personal Last.fm + Navidrome discovery feed")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
build = sub.add_parser("build", help="Build the recommendation feed")
|
||||
build.add_argument("--days", type=int, default=None, help="Rolling window in days (default: .env DAYS)")
|
||||
build.add_argument("--refresh", action="store_true", help="Ignore caches and rebuild")
|
||||
build.add_argument("--json", action="store_true", help="Print the full feed JSON")
|
||||
build.set_defaults(func=cmd_build)
|
||||
|
||||
server = sub.add_parser("serve", help="Serve the feed UI")
|
||||
server.add_argument("--days", type=int, default=None)
|
||||
server.add_argument("--host", default="127.0.0.1")
|
||||
server.add_argument("--port", type=int, default=8787)
|
||||
server.add_argument("--warm", action="store_true", help="Build before serving")
|
||||
server.set_defaults(func=cmd_serve)
|
||||
|
||||
stats = sub.add_parser("stats", help="Print cached feed stats")
|
||||
stats.add_argument("--days", type=int, default=None)
|
||||
stats.set_defaults(func=cmd_stats)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,59 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def load_json(path: Path, default: Any = None) -> Any:
|
||||
try:
|
||||
with path.open(encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
except (FileNotFoundError, json.JSONDecodeError, OSError):
|
||||
return default
|
||||
|
||||
|
||||
def save_json(path: Path, data: Any) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
json.dump(data, handle, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def is_fresh(path: Path, ttl_seconds: float) -> bool:
|
||||
try:
|
||||
return time.time() - path.stat().st_mtime < ttl_seconds
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
class JsonCache:
|
||||
"""Small file cache keyed by a stable hash of the request."""
|
||||
|
||||
def __init__(self, directory: Path, ttl_seconds: float = 7 * 24 * 3600):
|
||||
self.directory = directory
|
||||
self.ttl_seconds = ttl_seconds
|
||||
|
||||
def _path(self, key: str) -> Path:
|
||||
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()
|
||||
return self.directory / f"{digest}.json"
|
||||
|
||||
def get(self, key: str) -> Any:
|
||||
path = self._path(key)
|
||||
if not is_fresh(path, self.ttl_seconds):
|
||||
return None
|
||||
return load_json(path)
|
||||
|
||||
def set(self, key: str, value: Any) -> None:
|
||||
save_json(self._path(key), value)
|
||||
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def _load_dotenv(path: Path) -> None:
|
||||
"""Tiny .env loader so the app stays dependency-free."""
|
||||
if not path.exists():
|
||||
return
|
||||
for raw in path.read_text(encoding="utf-8").splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if line.startswith("export "):
|
||||
line = line[7:]
|
||||
if "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
||||
value = value[1:-1]
|
||||
os.environ.setdefault(key, value)
|
||||
|
||||
|
||||
_load_dotenv(ROOT / ".env")
|
||||
|
||||
|
||||
def _env(name: str, default: str | None = None, required: bool = False) -> str:
|
||||
value = os.environ.get(name, default)
|
||||
if required and not value:
|
||||
raise RuntimeError(f"Missing {name}. Copy .env.example to .env and fill it in.")
|
||||
return value or ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
navidrome_url: str
|
||||
navidrome_user: str
|
||||
navidrome_password: str
|
||||
navidrome_basic_user: str
|
||||
navidrome_basic_password: str
|
||||
lastfm_api_key: str
|
||||
days: int = 7
|
||||
feed_size: int = 36
|
||||
seed_artists: int = 10
|
||||
seed_tracks: int = 10
|
||||
similar_artists_per_seed: int = 5
|
||||
top_tracks_per_artist: int = 4
|
||||
similar_tracks_per_seed: int = 12
|
||||
cache_dir: Path = ROOT / ".cache"
|
||||
web_dir: Path = ROOT / "web"
|
||||
lastfm_rate: float = 4.0
|
||||
navidrome_rate: float = 8.0
|
||||
|
||||
@classmethod
|
||||
def load(cls) -> "Settings":
|
||||
return cls(
|
||||
navidrome_url=_env("NAVIDROME_URL", required=True).rstrip("/"),
|
||||
navidrome_user=_env("NAVIDROME_USER", required=True),
|
||||
navidrome_password=_env("NAVIDROME_PASSWORD", required=True),
|
||||
navidrome_basic_user=_env("NAVIDROME_BASIC_USER"),
|
||||
navidrome_basic_password=_env("NAVIDROME_BASIC_PASSWORD"),
|
||||
lastfm_api_key=_env("LASTFM_API_KEY", required=True),
|
||||
days=int(_env("DAYS", "7")),
|
||||
feed_size=int(_env("FEED_SIZE", "36")),
|
||||
seed_artists=int(_env("SEED_ARTISTS", "10")),
|
||||
seed_tracks=int(_env("SEED_TRACKS", "10")),
|
||||
similar_artists_per_seed=int(_env("SIMILAR_ARTISTS_PER_SEED", "5")),
|
||||
top_tracks_per_artist=int(_env("TOP_TRACKS_PER_ARTIST", "4")),
|
||||
similar_tracks_per_seed=int(_env("SIMILAR_TRACKS_PER_SEED", "12")),
|
||||
cache_dir=Path(_env("CACHE_DIR", str(ROOT / ".cache"))).expanduser(),
|
||||
web_dir=ROOT / "web",
|
||||
lastfm_rate=float(_env("LASTFM_RATE", "4.0")),
|
||||
navidrome_rate=float(_env("NAVIDROME_RATE", "8.0")),
|
||||
)
|
||||
|
||||
def with_days(self, days: int) -> "Settings":
|
||||
return replace(self, days=max(1, min(days, 90)))
|
||||
|
||||
|
||||
def basic_auth(settings: Settings) -> tuple[str, str] | None:
|
||||
if settings.navidrome_basic_user:
|
||||
return settings.navidrome_basic_user, settings.navidrome_basic_password
|
||||
return None
|
||||
@@ -0,0 +1,139 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import urllib.error
|
||||
from typing import Any
|
||||
|
||||
from .cache import JsonCache
|
||||
from .net import HttpClient, HttpError, RateLimiter
|
||||
|
||||
|
||||
API_ROOT = "https://ws.audioscrobbler.com/2.0/"
|
||||
PLACEHOLDER_HASH = "2a96cbd8b46e442fc41c2b86b821562f"
|
||||
|
||||
|
||||
class LastFMError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _as_list(value: Any) -> list[dict]:
|
||||
if isinstance(value, dict):
|
||||
return [value]
|
||||
if isinstance(value, list):
|
||||
return [item for item in value if isinstance(item, dict)]
|
||||
return []
|
||||
|
||||
|
||||
def _match(value: Any) -> float:
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _image(images: Any) -> str | None:
|
||||
for image in reversed(_as_list(images)):
|
||||
url = (image.get("#text") or "").strip()
|
||||
if url and PLACEHOLDER_HASH not in url:
|
||||
return url
|
||||
return None
|
||||
|
||||
|
||||
def _artist_name(track: dict) -> str:
|
||||
artist = track.get("artist")
|
||||
if isinstance(artist, dict):
|
||||
return artist.get("name") or artist.get("#text") or ""
|
||||
if isinstance(artist, str):
|
||||
return artist
|
||||
return track.get("artistName") or ""
|
||||
|
||||
|
||||
class LastFM:
|
||||
def __init__(self, api_key: str, cache_dir, rate_limiter: RateLimiter | None = None):
|
||||
self.api_key = api_key
|
||||
self.http = HttpClient(
|
||||
"LastRecc/0.1 (https://github.com/lastrecc)",
|
||||
rate_limiter=rate_limiter or RateLimiter(4.0),
|
||||
)
|
||||
self.cache = JsonCache(cache_dir / "lastfm", ttl_seconds=14 * 24 * 3600)
|
||||
|
||||
def _call(self, method: str, **params: Any) -> dict:
|
||||
clean = {key: value for key, value in params.items() if value is not None}
|
||||
cache_key = method + "::" + hashlib.sha256(
|
||||
json.dumps(clean, sort_keys=True, ensure_ascii=False).encode("utf-8")
|
||||
).hexdigest()
|
||||
cached = self.cache.get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
query = {"method": method, "api_key": self.api_key, "format": "json", **clean}
|
||||
try:
|
||||
data = self.http.get_json(API_ROOT, params=query)
|
||||
except (HttpError, urllib.error.URLError, TimeoutError, OSError) as exc:
|
||||
raise LastFMError(f"Last.fm {method} failed: {exc}") from exc
|
||||
except ValueError as exc:
|
||||
raise LastFMError(f"Last.fm {method} returned invalid JSON") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise LastFMError(f"Last.fm {method} returned no data")
|
||||
if data.get("error"):
|
||||
raise LastFMError(f"Last.fm {method}: {data.get('message', 'unknown error')}")
|
||||
self.cache.set(cache_key, data)
|
||||
return data
|
||||
|
||||
# ----------------------------------------------------------------- artists
|
||||
def artist_similar(self, artist: str, limit: int = 20) -> list[dict]:
|
||||
data = self._call("artist.getSimilar", artist=artist, limit=limit, autocorrect=1)
|
||||
return _as_list(data.get("similarartists", {}).get("artist"))
|
||||
|
||||
def artist_top_tracks(self, artist: str, limit: int = 5) -> list[dict]:
|
||||
data = self._call("artist.getTopTracks", artist=artist, limit=limit, autocorrect=1)
|
||||
return _as_list(data.get("toptracks", {}).get("track"))
|
||||
|
||||
def artist_top_albums(self, artist: str, limit: int = 5) -> list[dict]:
|
||||
data = self._call("artist.getTopAlbums", artist=artist, limit=limit, autocorrect=1)
|
||||
return _as_list(data.get("topalbums", {}).get("album"))
|
||||
|
||||
def artist_info(self, artist: str) -> dict:
|
||||
data = self._call("artist.getInfo", artist=artist, autocorrect=1)
|
||||
return data.get("artist", {}) or {}
|
||||
|
||||
# ------------------------------------------------------------------ tracks
|
||||
def track_similar(self, artist: str, track: str, limit: int = 15) -> list[dict]:
|
||||
data = self._call(
|
||||
"track.getSimilar",
|
||||
artist=artist,
|
||||
track=track,
|
||||
limit=limit,
|
||||
autocorrect=1,
|
||||
)
|
||||
return _as_list(data.get("similartracks", {}).get("track"))
|
||||
|
||||
def track_info(self, artist: str, track: str) -> dict:
|
||||
data = self._call("track.getInfo", artist=artist, track=track, autocorrect=1)
|
||||
return data.get("track", {}) or {}
|
||||
|
||||
# ------------------------------------------------------------------ albums
|
||||
def album_info(self, artist: str, album: str) -> dict:
|
||||
data = self._call("album.getInfo", artist=artist, album=album, autocorrect=1)
|
||||
return data.get("album", {}) or {}
|
||||
|
||||
# ------------------------------------------------------------------- utils
|
||||
@staticmethod
|
||||
def image_from_track(track: dict) -> str | None:
|
||||
album = track.get("album")
|
||||
if isinstance(album, dict):
|
||||
return _image(album.get("image")) or _image(track.get("image"))
|
||||
return _image(track.get("image"))
|
||||
|
||||
@staticmethod
|
||||
def image_from_album(album: dict) -> str | None:
|
||||
return _image(album.get("image"))
|
||||
|
||||
@staticmethod
|
||||
def artist_name(track: dict) -> str:
|
||||
return _artist_name(track)
|
||||
|
||||
@staticmethod
|
||||
def match(value: Any) -> float:
|
||||
return _match(value)
|
||||
@@ -0,0 +1,203 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from typing import Any
|
||||
|
||||
from .cache import is_fresh, load_json, save_json
|
||||
from .config import Settings, basic_auth
|
||||
from .net import HttpClient, HttpError, RateLimiter
|
||||
|
||||
|
||||
class NavidromeError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class Navidrome:
|
||||
"""Navidrome native API + Subsonic API client."""
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.base = settings.navidrome_url
|
||||
self.http = HttpClient(
|
||||
"LastRecc/0.1 (https://github.com/lastrecc)",
|
||||
rate_limiter=RateLimiter(settings.navidrome_rate),
|
||||
basic_auth=basic_auth(settings),
|
||||
default_headers={"X-ND-Client-Unique-Id": "lastrecc"},
|
||||
)
|
||||
self._token: str | None = None
|
||||
self._salt: str | None = None
|
||||
self._subsonic_token: str | None = None
|
||||
self._login_lock = threading.Lock()
|
||||
self._songs: dict[str, dict] = {}
|
||||
self._songs_path = settings.cache_dir / "navidrome_songs.json"
|
||||
self._songs_loaded = False
|
||||
|
||||
# ------------------------------------------------------------------ auth
|
||||
def login(self, force: bool = False) -> None:
|
||||
with self._login_lock:
|
||||
if self._token and not force:
|
||||
return
|
||||
try:
|
||||
data = self.http.post_json(
|
||||
f"{self.base}/auth/login",
|
||||
{
|
||||
"username": self.settings.navidrome_user,
|
||||
"password": self.settings.navidrome_password,
|
||||
},
|
||||
)
|
||||
except HttpError as exc:
|
||||
raise NavidromeError(f"Navidrome login failed: {exc}") from exc
|
||||
if not data or "token" not in data:
|
||||
raise NavidromeError("Navidrome login returned no token")
|
||||
self._token = data["token"]
|
||||
self._salt = data.get("subsonicSalt")
|
||||
self._subsonic_token = data.get("subsonicToken")
|
||||
|
||||
def _native_headers(self) -> dict[str, str]:
|
||||
self.login()
|
||||
return {"X-ND-Authorization": f"Bearer {self._token}"}
|
||||
|
||||
def _native_request(self, url: str) -> tuple[int, dict[str, str], bytes]:
|
||||
for attempt in range(2):
|
||||
try:
|
||||
return self.http.request(url, headers=self._native_headers())
|
||||
except HttpError as exc:
|
||||
if exc.status == 401 and attempt == 0:
|
||||
self.login(force=True)
|
||||
continue
|
||||
raise
|
||||
raise NavidromeError("Navidrome request failed after re-authentication")
|
||||
|
||||
# --------------------------------------------------------------- scrobbles
|
||||
def get_scrobbles(self, force: bool = False, ttl: int = 600) -> list[dict]:
|
||||
path = self.settings.cache_dir / "scrobbles.json"
|
||||
if not force and is_fresh(path, ttl):
|
||||
cached = load_json(path)
|
||||
if cached and isinstance(cached.get("items"), list):
|
||||
return cached["items"]
|
||||
|
||||
items: list[dict] = []
|
||||
start = 0
|
||||
total = None
|
||||
while True:
|
||||
url = (
|
||||
f"{self.base}/api/scrobble"
|
||||
f"?_end=5000&_order=DESC&_sort=submission_time&_start={start}"
|
||||
)
|
||||
_, headers, payload = self._native_request(url)
|
||||
chunk = json.loads(payload.decode("utf-8")) if payload else []
|
||||
if not isinstance(chunk, list):
|
||||
raise NavidromeError(f"Unexpected scrobble response: {chunk!r}")
|
||||
items.extend(chunk)
|
||||
total = int(headers.get("X-Total-Count", len(items)))
|
||||
if not chunk or len(items) >= total:
|
||||
break
|
||||
start += len(chunk)
|
||||
if start > 200_000:
|
||||
break
|
||||
save_json(path, {"fetched_at": time.time(), "items": items})
|
||||
return items
|
||||
|
||||
# ------------------------------------------------------------------- songs
|
||||
def _load_songs(self) -> None:
|
||||
if self._songs_loaded:
|
||||
return
|
||||
cached = load_json(self._songs_path, {})
|
||||
if isinstance(cached, dict):
|
||||
self._songs = {str(k): v for k, v in cached.items() if isinstance(v, dict)}
|
||||
self._songs_loaded = True
|
||||
|
||||
def get_songs(self, ids: set[str] | list[str]) -> dict[str, dict]:
|
||||
"""Fetch song metadata for IDs, batching and caching aggressively."""
|
||||
self._load_songs()
|
||||
missing = [song_id for song_id in ids if song_id not in self._songs]
|
||||
if not missing:
|
||||
return {song_id: self._songs[song_id] for song_id in ids}
|
||||
|
||||
for offset in range(0, len(missing), 80):
|
||||
chunk = missing[offset : offset + 80]
|
||||
query = urllib.parse.urlencode([("id", song_id) for song_id in chunk])
|
||||
try:
|
||||
_, _, payload = self._native_request(f"{self.base}/api/song?{query}")
|
||||
songs = json.loads(payload.decode("utf-8")) if payload else []
|
||||
except (HttpError, NavidromeError) as exc:
|
||||
print(f" ! song metadata batch failed: {exc}", file=sys.stderr)
|
||||
continue
|
||||
if not isinstance(songs, list):
|
||||
continue
|
||||
for song in songs:
|
||||
if song.get("id"):
|
||||
self._songs[song["id"]] = song
|
||||
if (offset // 80) % 5 == 0:
|
||||
save_json(self._songs_path, self._songs)
|
||||
print(
|
||||
f" · metadata {min(offset + 80, len(missing))}/{len(missing)}",
|
||||
file=sys.stderr,
|
||||
end="\r",
|
||||
)
|
||||
save_json(self._songs_path, self._songs)
|
||||
print(" " * 60, file=sys.stderr, end="\r")
|
||||
return {song_id: self._songs[song_id] for song_id in ids if song_id in self._songs}
|
||||
|
||||
# ---------------------------------------------------------------- subsonic
|
||||
def _subsonic_params(self) -> dict[str, str]:
|
||||
self.login()
|
||||
if not self._salt or not self._subsonic_token:
|
||||
raise NavidromeError("Navidrome did not return Subsonic credentials")
|
||||
return {
|
||||
"u": self.settings.navidrome_user,
|
||||
"t": self._subsonic_token,
|
||||
"s": self._salt,
|
||||
"v": "1.16.1",
|
||||
"c": "LastRecc",
|
||||
"f": "json",
|
||||
}
|
||||
|
||||
def subsonic(self, method: str, **params: Any) -> dict:
|
||||
query = self._subsonic_params()
|
||||
query.update({key: value for key, value in params.items() if value is not None})
|
||||
url = f"{self.base}/rest/{method}.view?{urllib.parse.urlencode(query)}"
|
||||
data = self.http.get_json(url)
|
||||
response = (data or {}).get("subsonic-response", {})
|
||||
if response.get("status") != "ok":
|
||||
error = response.get("error", {})
|
||||
raise NavidromeError(f"Subsonic {method} failed: {error or response}")
|
||||
return response
|
||||
|
||||
def search_songs(self, query: str, limit: int = 5) -> list[dict]:
|
||||
try:
|
||||
data = self.subsonic(
|
||||
"search3",
|
||||
query=query,
|
||||
songCount=limit,
|
||||
albumCount=0,
|
||||
artistCount=0,
|
||||
)
|
||||
except (HttpError, NavidromeError):
|
||||
return []
|
||||
result = data.get("searchResult3", {})
|
||||
songs = result.get("song", [])
|
||||
if isinstance(songs, dict):
|
||||
songs = [songs]
|
||||
return [song for song in songs if isinstance(song, dict)]
|
||||
|
||||
def cover_url(self, cover_id: str, size: int = 300) -> str:
|
||||
query = self._subsonic_params()
|
||||
query.update({"id": cover_id, "size": str(size)})
|
||||
return f"{self.base}/rest/getCoverArt.view?{urllib.parse.urlencode(query)}"
|
||||
|
||||
def stream_url(self, song_id: str) -> str:
|
||||
query = self._subsonic_params()
|
||||
query.update({"id": song_id})
|
||||
return f"{self.base}/rest/stream.view?{urllib.parse.urlencode(query)}"
|
||||
|
||||
def page_url(self, album_id: str | None = None, song_id: str | None = None) -> str:
|
||||
if album_id:
|
||||
return f"{self.base}/app/#/album/{urllib.parse.quote(album_id)}/show"
|
||||
if song_id:
|
||||
return f"{self.base}/app/#/song/{urllib.parse.quote(song_id)}/show"
|
||||
return f"{self.base}/app/"
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
|
||||
|
||||
class HttpError(RuntimeError):
|
||||
def __init__(self, status: int, url: str, body: str = ""):
|
||||
# Never put API keys / Subsonic tokens from the query string into logs.
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
safe_url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
|
||||
self.status = status
|
||||
self.url = safe_url
|
||||
self.body = body
|
||||
super().__init__(f"HTTP {status} for {safe_url}: {body[:240]}")
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""A simple shared token bucket. Good enough for personal API use."""
|
||||
|
||||
def __init__(self, rate_per_second: float):
|
||||
self.interval = 1.0 / max(rate_per_second, 0.1)
|
||||
self._next = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def wait(self) -> None:
|
||||
with self._lock:
|
||||
now = time.monotonic()
|
||||
if now < self._next:
|
||||
delay = self._next - now
|
||||
else:
|
||||
delay = 0.0
|
||||
self._next = max(now, self._next) + self.interval
|
||||
if delay:
|
||||
time.sleep(delay)
|
||||
|
||||
|
||||
class HttpClient:
|
||||
def __init__(
|
||||
self,
|
||||
user_agent: str,
|
||||
*,
|
||||
rate_limiter: RateLimiter | None = None,
|
||||
basic_auth: tuple[str, str] | None = None,
|
||||
default_headers: dict[str, str] | None = None,
|
||||
timeout: float = 60.0,
|
||||
):
|
||||
self.user_agent = user_agent
|
||||
self.rate_limiter = rate_limiter
|
||||
self.basic_auth = basic_auth
|
||||
self.default_headers = default_headers or {}
|
||||
self.timeout = timeout
|
||||
|
||||
def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
|
||||
headers = {
|
||||
"User-Agent": self.user_agent,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Encoding": "identity",
|
||||
}
|
||||
headers.update(self.default_headers)
|
||||
if self.basic_auth:
|
||||
token = base64.b64encode(
|
||||
f"{self.basic_auth[0]}:{self.basic_auth[1]}".encode()
|
||||
).decode()
|
||||
headers["Authorization"] = f"Basic {token}"
|
||||
if extra:
|
||||
headers.update(extra)
|
||||
return headers
|
||||
|
||||
def open(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
method: str = "GET",
|
||||
data: Any = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
timeout: float | None = None,
|
||||
):
|
||||
body = None
|
||||
final_headers = self._headers(headers)
|
||||
if data is not None:
|
||||
if isinstance(data, (dict, list)):
|
||||
body = json.dumps(data).encode("utf-8")
|
||||
final_headers.setdefault("Content-Type", "application/json")
|
||||
elif isinstance(data, str):
|
||||
body = data.encode("utf-8")
|
||||
else:
|
||||
body = data
|
||||
if self.rate_limiter:
|
||||
self.rate_limiter.wait()
|
||||
request = urllib.request.Request(url, data=body, headers=final_headers, method=method)
|
||||
return urllib.request.urlopen(request, timeout=timeout or self.timeout)
|
||||
|
||||
def request(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
method: str = "GET",
|
||||
data: Any = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
retries: int = 3,
|
||||
) -> tuple[int, dict[str, str], bytes]:
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(retries + 1):
|
||||
try:
|
||||
with self.open(url, method=method, data=data, headers=headers) as response:
|
||||
return response.status, dict(response.headers), response.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
payload = exc.read().decode("utf-8", "replace")
|
||||
last_error = HttpError(exc.code, url, payload)
|
||||
if exc.code not in (429, 500, 502, 503, 504) or attempt == retries:
|
||||
raise last_error
|
||||
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
||||
last_error = exc
|
||||
if attempt == retries:
|
||||
raise
|
||||
time.sleep((2**attempt) * 0.5 + random.random() * 0.3)
|
||||
raise RuntimeError(f"Request failed: {last_error}")
|
||||
|
||||
def get_json(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
params: dict[str, Any] | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
if params:
|
||||
query = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
|
||||
url = f"{url}{'&' if '?' in url else '?'}{query}"
|
||||
status, _, payload = self.request(url, headers=headers)
|
||||
if not payload:
|
||||
return None
|
||||
return json.loads(payload.decode("utf-8"))
|
||||
|
||||
def post_json(
|
||||
self,
|
||||
url: str,
|
||||
data: Any,
|
||||
*,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
status, _, payload = self.request(url, method="POST", data=data, headers=headers)
|
||||
if not payload:
|
||||
return None
|
||||
return json.loads(payload.decode("utf-8"))
|
||||
@@ -0,0 +1,620 @@
|
||||
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
|
||||
@@ -0,0 +1,271 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import mimetypes
|
||||
import sys
|
||||
import threading
|
||||
import traceback
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from .cache import is_fresh, load_json, save_json
|
||||
from .config import Settings
|
||||
from .navidrome import Navidrome
|
||||
from .net import HttpError
|
||||
from .recommend import build_feed
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.nav = Navidrome(settings)
|
||||
self.build_lock = threading.Lock()
|
||||
self.cover_dir = settings.cache_dir / "covers"
|
||||
self.cover_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def feed(self, days: int | None = None, refresh: bool = False) -> dict:
|
||||
settings = self.settings.with_days(days) if days else self.settings
|
||||
with self.build_lock:
|
||||
return build_feed(settings, force=refresh)
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "LastRecc/0.1"
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
@property
|
||||
def app(self) -> App:
|
||||
return self.server.app # type: ignore[attr-defined]
|
||||
|
||||
def log_message(self, fmt: str, *args) -> None:
|
||||
sys.stderr.write(f"[http] {self.address_string()} {fmt % args}\n")
|
||||
|
||||
# ------------------------------------------------------------------ helpers
|
||||
def _json(self, status: int, data: dict) -> None:
|
||||
payload = json.dumps(data, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def _error(self, status: int, message: str) -> None:
|
||||
self._json(status, {"error": message})
|
||||
|
||||
def _serve_file(self, path: Path) -> None:
|
||||
if not path.is_file():
|
||||
self._error(HTTPStatus.NOT_FOUND, "Not found")
|
||||
return
|
||||
content_type = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
|
||||
payload = path.read_bytes()
|
||||
self.send_response(HTTPStatus.OK)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.send_header("Cache-Control", "no-cache" if path.name.endswith(".html") else "public, max-age=300")
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
# --------------------------------------------------------------------- GET
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
path = parsed.path
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
|
||||
if path in ("/", "/index.html"):
|
||||
self._serve_file(self.app.settings.web_dir / "index.html")
|
||||
return
|
||||
if path.startswith("/static/"):
|
||||
relative = path[len("/static/") :]
|
||||
target = (self.app.settings.web_dir / relative).resolve()
|
||||
web_root = self.app.settings.web_dir.resolve()
|
||||
if web_root not in target.parents and target != web_root:
|
||||
self._error(HTTPStatus.FORBIDDEN, "Forbidden")
|
||||
return
|
||||
self._serve_file(target)
|
||||
return
|
||||
if path == "/api/health":
|
||||
cached = load_json(self.app.settings.cache_dir / "feed.json")
|
||||
self._json(
|
||||
HTTPStatus.OK,
|
||||
{
|
||||
"ok": True,
|
||||
"user": self.app.settings.navidrome_user,
|
||||
"cached_feed": bool(cached),
|
||||
"generated_at": (cached or {}).get("generated_at"),
|
||||
},
|
||||
)
|
||||
return
|
||||
if path == "/api/feed":
|
||||
days = None
|
||||
if query.get("days"):
|
||||
try:
|
||||
days = int(query["days"][0])
|
||||
except ValueError:
|
||||
self._error(HTTPStatus.BAD_REQUEST, "days must be an integer")
|
||||
return
|
||||
refresh = query.get("refresh", ["0"])[0].lower() in ("1", "true", "yes")
|
||||
try:
|
||||
feed = self.app.feed(days=days, refresh=refresh)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
traceback.print_exc()
|
||||
self._error(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc))
|
||||
return
|
||||
self._json(HTTPStatus.OK, feed)
|
||||
return
|
||||
if path.startswith("/api/cover/"):
|
||||
cover_id = urllib.parse.unquote(path[len("/api/cover/") :])
|
||||
try:
|
||||
size = int(query.get("size", ["300"])[0])
|
||||
except ValueError:
|
||||
size = 300
|
||||
size = max(100, min(size, 600))
|
||||
self._cover(cover_id, size)
|
||||
return
|
||||
if path.startswith("/api/stream/"):
|
||||
song_id = urllib.parse.unquote(path[len("/api/stream/") :])
|
||||
self._stream(song_id)
|
||||
return
|
||||
self._error(HTTPStatus.NOT_FOUND, "Not found")
|
||||
|
||||
def do_HEAD(self) -> None: # noqa: N802
|
||||
# Good enough for browsers probing covers/audio.
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
if parsed.path in ("/", "/index.html"):
|
||||
path = self.app.settings.web_dir / "index.html"
|
||||
elif parsed.path.startswith("/static/"):
|
||||
web_root = self.app.settings.web_dir.resolve()
|
||||
path = (web_root / parsed.path[len("/static/") :]).resolve()
|
||||
if web_root not in path.parents and path != web_root:
|
||||
self.send_response(HTTPStatus.FORBIDDEN)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
else:
|
||||
self.send_response(HTTPStatus.NOT_FOUND)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
if not path.is_file():
|
||||
self.send_response(HTTPStatus.NOT_FOUND)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
self.send_response(HTTPStatus.OK)
|
||||
self.send_header("Content-Type", mimetypes.guess_type(str(path))[0] or "application/octet-stream")
|
||||
self.send_header("Content-Length", str(path.stat().st_size))
|
||||
self.end_headers()
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
if parsed.path == "/api/refresh":
|
||||
try:
|
||||
feed = self.app.feed(refresh=True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
traceback.print_exc()
|
||||
self._error(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc))
|
||||
return
|
||||
self._json(HTTPStatus.OK, feed)
|
||||
return
|
||||
self._error(HTTPStatus.NOT_FOUND, "Not found")
|
||||
|
||||
# ------------------------------------------------------------------- proxy
|
||||
def _cover(self, cover_id: str, size: int) -> None:
|
||||
if not cover_id:
|
||||
self._error(HTTPStatus.BAD_REQUEST, "Missing cover id")
|
||||
return
|
||||
cache_key = hashlib.sha256(f"{cover_id}:{size}".encode()).hexdigest()
|
||||
cache_path = self.app.cover_dir / f"{cache_key}.bin"
|
||||
content_type = "image/jpeg"
|
||||
if cache_path.exists() and is_fresh(cache_path, 7 * 24 * 3600):
|
||||
meta_path = cache_path.with_suffix(".json")
|
||||
meta = load_json(meta_path, {}) or {}
|
||||
content_type = meta.get("content_type", content_type)
|
||||
payload = cache_path.read_bytes()
|
||||
else:
|
||||
url = self.app.nav.cover_url(cover_id, size)
|
||||
try:
|
||||
_, headers, payload = self.app.nav.http.request(url)
|
||||
except (HttpError, urllib.error.HTTPError, urllib.error.URLError, OSError) as exc:
|
||||
self._error(HTTPStatus.BAD_GATEWAY, f"Cover fetch failed: {exc}")
|
||||
return
|
||||
content_type = headers.get("Content-Type", content_type)
|
||||
cache_path.write_bytes(payload)
|
||||
save_json(cache_path.with_suffix(".json"), {"content_type": content_type})
|
||||
self.send_response(HTTPStatus.OK)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.send_header("Cache-Control", "public, max-age=604800")
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def _stream(self, song_id: str) -> None:
|
||||
if not song_id:
|
||||
self._error(HTTPStatus.BAD_REQUEST, "Missing song id")
|
||||
return
|
||||
url = self.app.nav.stream_url(song_id)
|
||||
headers = {}
|
||||
range_header = self.headers.get("Range")
|
||||
if range_header:
|
||||
headers["Range"] = range_header
|
||||
try:
|
||||
upstream = self.app.nav.http.open(url, headers=headers)
|
||||
except urllib.error.HTTPError as exc:
|
||||
self._error(exc.code, f"Stream failed: {exc.reason}")
|
||||
return
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
self._error(HTTPStatus.BAD_GATEWAY, f"Stream failed: {exc}")
|
||||
return
|
||||
with upstream:
|
||||
status = upstream.status
|
||||
self.send_response(status)
|
||||
content_length = upstream.headers.get("Content-Length")
|
||||
for header in (
|
||||
"Content-Type",
|
||||
"Content-Length",
|
||||
"Content-Range",
|
||||
"Accept-Ranges",
|
||||
"ETag",
|
||||
"Last-Modified",
|
||||
):
|
||||
value = upstream.headers.get(header)
|
||||
if value:
|
||||
self.send_header(header, value)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
if not content_length:
|
||||
self.send_header("Connection", "close")
|
||||
self.close_connection = True
|
||||
self.end_headers()
|
||||
try:
|
||||
while True:
|
||||
chunk = upstream.read(64 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
self.wfile.write(chunk)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
|
||||
|
||||
class Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
allow_reuse_address = True
|
||||
|
||||
def __init__(self, address, handler, app: App):
|
||||
super().__init__(address, handler)
|
||||
self.app = app
|
||||
|
||||
|
||||
def serve(settings: Settings, host: str = "127.0.0.1", port: int = 8787) -> None:
|
||||
app = App(settings)
|
||||
server = Server((host, port), Handler, app)
|
||||
print(f"LastRecc → http://{host}:{port}", file=sys.stderr)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("\nbye", file=sys.stderr)
|
||||
finally:
|
||||
server.server_close()
|
||||
@@ -0,0 +1,62 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
|
||||
_PARENS = re.compile(r"\([^)]*\)|\[[^\]]*\]")
|
||||
_FEAT = re.compile(r"\b(feat\.?|ft\.?|featuring|with)\b.*$", re.IGNORECASE)
|
||||
_NON_WORD = re.compile(r"[^\w]+", re.UNICODE)
|
||||
|
||||
|
||||
def normalize(value: str) -> str:
|
||||
"""Normalize artist/title strings while preserving non-Latin scripts."""
|
||||
if not value:
|
||||
return ""
|
||||
text = unicodedata.normalize("NFKC", value).casefold()
|
||||
text = _PARENS.sub(" ", text)
|
||||
text = _FEAT.sub(" ", text)
|
||||
text = _NON_WORD.sub(" ", text)
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def track_key(artist: str, title: str) -> str:
|
||||
return f"{normalize(artist)}::{normalize(title)}"
|
||||
|
||||
|
||||
def similarity(left: str, right: str) -> float:
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
return difflib.SequenceMatcher(None, left, right).ratio()
|
||||
|
||||
|
||||
def best_match(items: list[dict], artist: str, title: str) -> dict | None:
|
||||
"""Find the closest song in a small Navidrome search result."""
|
||||
want_artist = normalize(artist)
|
||||
want_title = normalize(title)
|
||||
best = None
|
||||
best_score = 0.0
|
||||
for item in items:
|
||||
got_artist = normalize(item.get("artist") or "")
|
||||
got_title = normalize(item.get("title") or "")
|
||||
if not got_artist or not got_title:
|
||||
continue
|
||||
if got_artist == want_artist and got_title == want_title:
|
||||
return item
|
||||
title_score = similarity(got_title, want_title)
|
||||
artist_score = similarity(got_artist, want_artist)
|
||||
score = title_score * 0.65 + artist_score * 0.35
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best = item
|
||||
if best and best_score >= 0.86:
|
||||
return best
|
||||
return None
|
||||
|
||||
|
||||
def human_duration(seconds: int | float | None) -> str:
|
||||
if not seconds:
|
||||
return ""
|
||||
seconds = int(seconds)
|
||||
return f"{seconds // 60}:{seconds % 60:02d}"
|
||||
Reference in new issue
Block a user