-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlastfm.py
196 lines (147 loc) · 6.14 KB
/
lastfm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import re
import datetime
from logging import getLogger
import pylast
from pylast import LastFMNetwork
API_KEY = "1932ab33ea535ba390526dae88a782af"
API_SEC = "aa8ee0a4c0a2bcc5bd33e506e7a5fefe"
log = getLogger(__name__)
class TooFewResults(Exception):
pass
def _getItemObj(item):
"""Extract the lastfm object from a list item."""
if isinstance(item, (pylast.PlayedTrack, pylast.LovedTrack)):
obj = item
else:
obj = item.item
return obj
def filterExcludes(items, excludes: dict) -> list:
exc_regexes = {}
for key, expressions in (excludes or {}).items():
exc_regexes[key] = list([re.compile(e) for e in excludes[key]]) if excludes[key] else []
excludes = exc_regexes
def f(item):
obj = _getItemObj(item)
def _artist(o):
if isinstance(o, pylast.Artist):
return o.name
elif isinstance(o, (pylast.Album, pylast.Track)):
return o.artist.name
elif isinstance(o, (pylast.PlayedTrack, pylast.LovedTrack)):
return o.track.artist.name
else:
raise NotImplementedError(f"FIXME: accessor for {o.__class__.__name__}")
def _album(o):
if isinstance(o, pylast.Album):
return o.title
elif isinstance(o, (pylast.Track, pylast.LovedTrack)):
a = o.get_album()
return a.title if a else None
elif isinstance(o, pylast.PlayedTrack):
return o.album
else:
raise NotImplementedError(f"FIXME: accessor for {o.__class__.__name__}")
def _track(o):
if isinstance(o, pylast.Track):
return o.title
elif isinstance(o, (pylast.PlayedTrack, pylast.LovedTrack)):
return o.track.title
else:
raise NotImplementedError(f"FIXME: accessor for {o.__class__.__name__}")
if isinstance(obj, pylast.Artist):
for regex in excludes["artist"]:
if regex.search(_artist(obj)):
return False
elif isinstance(obj, pylast.Album):
for regex in excludes["album"]:
if regex.search(_album(obj)):
return False
for regex in excludes["artist"]:
if regex.search(_artist(obj)):
return False
elif isinstance(obj, pylast.Track):
for regex in excludes["track"]:
if regex.search(_track(obj)):
return False
for regex in excludes["artist"]:
if regex.search(_artist(obj)):
return False
album = _album(obj) if len(excludes["album"]) else None
if album:
for regex in excludes["album"]:
if regex.search(album):
return False
elif isinstance(obj, pylast.PlayedTrack):
for regex in excludes["track"]:
if regex.search(_track(obj)):
return False
for regex in excludes["artist"]:
if regex.search(_artist(obj)):
return False
for regex in excludes["album"]:
if obj.album:
if regex.search(_album(obj)):
return False
return True
return list(filter(f, items) if excludes else items)
def uniqueArtist(items) -> list:
results = []
seen_artists = set()
for item in items:
obj = _getItemObj(item)
if obj.artist.name.lower() not in seen_artists:
results.append(item)
seen_artists.add(obj.artist.name.lower())
return results
def _lastfmGet(func, period, num=4, excludes=None, unique_artist=False, multi=1):
multi = multi or 1
if period[-1] == 's':
# Pylast periods are not plural, as are the constants are opts so chop
period = period[:-1]
tops = []
attempts, max_attempts = 1, 5
while len(tops) < num and attempts < max_attempts:
tops = filterExcludes(func(period, limit=(num * multi) + (125 * attempts)), excludes)
log.debug(f"{func} (attempt #{attempts}): returned {len(tops)} filtered items.")
if unique_artist:
tops = uniqueArtist(tops)
attempts += 1
tops = tops[:num]
if len(tops) != num:
raise TooFewResults(f"Unable to obtain {num} results.")
else:
return tops
def topArtists(user, period, num=5, excludes=None):
return _lastfmGet(user.get_top_artists, period, num=num, excludes=excludes)
def topAlbums(user, period, num=5, excludes: list=None, unique_artist=False):
return _lastfmGet(user.get_top_albums, period, num=num, excludes=excludes,
multi=2 if unique_artist else 1, unique_artist=unique_artist)
def topTracks(user, period, num=5, excludes=None, unique_artist=False):
return _lastfmGet(user.get_top_tracks, period, num=num, excludes=excludes,
multi=3 if unique_artist else 1,
unique_artist=unique_artist)
def User(username, password=None):
password = pylast.md5(password) if password else None
return pylast.User(username,
LastFMNetwork(api_key=API_KEY, api_secret=API_SEC,
password_hash=password))
PERIODS = (pylast.PERIOD_12MONTHS + 's', pylast.PERIOD_1MONTH,
pylast.PERIOD_3MONTHS + 's', pylast.PERIOD_6MONTHS + 's',
pylast.PERIOD_7DAYS + 's', pylast.PERIOD_OVERALL)
def periodToTimedelta(p):
for unit in ("days", "months", "month"):
if p.endswith(unit):
val = int(p[:p.find(unit)])
if unit == "days":
return datetime.timedelta(days=val)
else:
return datetime.timedelta(weeks=(val + 1) * 4)
raise ValueError(f"Unsupported period value: `{p}`")
def periodString(p):
for unit in ("days", "months", "month"):
if p.endswith(unit):
val = int(p[:p.find(unit)])
td = periodToTimedelta(p)
return f"in the last {val} {unit} "\
f"(since {datetime.date.today() - td:%b %d, %Y})"
return p