discoverylidarr/lastfm_helpers.py

48 lines
1.4 KiB
Python
Raw Permalink Normal View History

2025-06-23 10:31:25 +02:00
from config import *
import requests, time, urllib.parse
from collections import defaultdict
from datetime import datetime, timedelta
def lf_request(method, **params):
2025-06-23 09:23:58 +00:00
# Fixa 'from_' → 'from' och 'to_' → 'to' (Last.fm accepterar inte Python-säkra namn)
for alt, real in (("from_", "from"), ("to_", "to")):
if alt in params:
params[real] = params.pop(alt)
2025-06-23 10:31:25 +02:00
url = "https://ws.audioscrobbler.com/2.0/"
params.update({
"method": method,
"api_key": LASTFM_API_KEY,
"format": "json"
})
try:
r = requests.get(url, params=params)
r.raise_for_status()
return r.json()
except Exception as e:
print(f"[LFM ERR] {e}")
return None
def recent_artists():
since = int((datetime.utcnow() - timedelta(days=30 * RECENT_MONTHS)).timestamp())
counts = defaultdict(int)
page = 1
while True:
js = lf_request(
"user.getRecentTracks", user=LASTFM_USERNAME,
limit=200, page=page, from_=since
)
if not js:
break
for t in js.get("recenttracks", {}).get("track", []):
a = t["artist"]
counts[(a["#text"], a.get("mbid", ""))] += 1
attr = js.get("recenttracks", {}).get("@attr", {})
if page >= int(attr.get("totalPages", 1)):
break
page += 1
return [(n, m) for (n, m), c in counts.items() if c >= MIN_PLAYS]