1 # -*- coding: utf-8 -*-
3 Fetching similar artists from last.fm web services
6 # standard library import
9 from collections import deque
10 from itertools import dropwhile
11 from hashlib import md5
13 # third parties components
16 from ...lib.plugin import Plugin
17 from ...lib.simafm import SimaFM, XmlFMHTTPError, XmlFMNotFound, XmlFMError
18 from ...lib.track import Track
22 """Caching decorator"""
23 def wrapper(*args, **kwargs):
24 #pylint: disable=W0212,C0111
26 similarities = [art + str(match) for art, match in args[1]]
27 hashedlst = md5(''.join(similarities).encode('utf-8')).hexdigest()
28 if hashedlst in cls._cache.get('asearch'):
29 cls.log.debug('cached request')
30 results = cls._cache.get('asearch').get(hashedlst)
32 results = func(*args, **kwargs)
33 cls.log.debug('caching request')
34 cls._cache.get('asearch').update({hashedlst:list(results)})
35 random.shuffle(results)
40 def blacklist(artist=False, album=False, track=False):
41 #pylint: disable=C0111,W0212
42 field = (artist, album, track)
44 def wrapper(*args, **kwargs):
46 boolgen = (bl for bl in field)
47 bl_fun = (cls._Plugin__daemon.sdb.get_bl_artist,
48 cls._Plugin__daemon.sdb.get_bl_album,
49 cls._Plugin__daemon.sdb.get_bl_track,)
50 #bl_getter = next(fn for fn, bl in zip(bl_fun, boolgen) if bl is True)
51 bl_getter = next(dropwhile(lambda _: not next(boolgen), bl_fun))
52 cls.log.debug('using {0} as bl filter'.format(bl_getter.__name__))
54 results = func(*args, **kwargs)
56 if bl_getter(elem, add_not=True):
57 cls.log.info('Blacklisted: {0}'.format(elem))
62 if bl_getter(elem, add_not=True):
63 cls.log.info('Blacklisted: {0}'.format(elem))
65 return func(*args, **kwargs)
71 """last.fm similar artists
74 def __init__(self, daemon):
75 Plugin.__init__(self, daemon)
76 self.daemon_conf = daemon.config
78 self.history = daemon.short_history
88 self.queue_mode = wrapper.get(self.plugin_conf.get('queue_mode'))
90 def _flush_cache(self):
92 Both flushes and instanciates _cache
94 if isinstance(self._cache, dict):
95 self.log.info('Lastfm: Flushing cache!')
97 self.log.info('Lastfm: Initialising cache!')
103 def _cleanup_cache(self):
104 """Avoid bloated cache
106 for _ , val in self._cache.items():
107 if isinstance(val, dict):
108 while len(val) > 150:
111 def get_history(self, artist):
112 """Constructs list of Track for already played titles for an artist.
114 duration = self.daemon_conf.getint('sima', 'history_duration')
115 tracks_from_db = self.sdb.get_history(duration=duration, artist=artist)
116 # Construct Track() objects list from database history
117 played_tracks = [Track(artist=tr[-1], album=tr[1], title=tr[2],
118 file=tr[3]) for tr in tracks_from_db]
121 def filter_track(self, tracks):
123 Extract one unplayed track from a Track object list.
125 * not already in the queue
128 artist = tracks[0].artist
129 black_list = self.player.queue + self.to_add
130 not_in_hist = list(set(tracks) - set(self.get_history(artist=artist)))
132 self.log.debug('All tracks already played for "{}"'.format(artist))
133 random.shuffle(not_in_hist)
134 #candidate = [ trk for trk in not_in_hist if trk not in black_list
135 #if not self.sdb.get_bl_track(trk, add_not=True)]
137 for trk in [_ for _ in not_in_hist if _ not in black_list]:
138 if self.sdb.get_bl_track(trk, add_not=True):
139 self.log.info('Blacklisted: {0}: '.format(trk))
141 if self.sdb.get_bl_album(trk, add_not=True):
142 self.log.info('Blacklisted album: {0}: '.format(trk))
144 # Should use albumartist heuristic as well
145 if self.plugin_conf.getboolean('single_album'):
146 if (trk.album == self.player.current.album or
147 trk.album in [tr.album for tr in self.to_add]):
148 self.log.debug('Found unplayed track ' +
149 'but from an album already queued: %s' % (trk))
151 candidate.append(trk)
153 self.log.debug('Unable to find title to add' +
154 ' for "%s".' % artist)
156 self.to_add.append(random.choice(candidate))
158 def _get_artists_list_reorg(self, alist):
160 Move around items in artists_list in order to play first not recently
163 # TODO: move to utils as a decorator
164 duration = self.daemon_conf.getint('sima', 'history_duration')
166 for trk in self.sdb.get_history(duration=duration,
168 if trk[0] not in art_in_hist:
169 art_in_hist.append(trk[0])
170 art_in_hist.reverse()
171 art_not_in_hist = [ ar for ar in alist if ar not in art_in_hist ]
172 random.shuffle(art_not_in_hist)
173 art_not_in_hist.extend(art_in_hist)
174 self.log.debug('history ordered: {}'.format(
175 ' / '.join(art_not_in_hist)))
176 return art_not_in_hist
178 @blacklist(artist=True)
180 def get_artists_from_player(self, similarities):
182 Look in player library for availability of similar artists in
185 dynamic = self.plugin_conf.getint('dynamic')
188 similarity = self.plugin_conf.getint('similarity')
190 similarities.reverse()
191 while (len(results) < dynamic
192 and len(similarities) > 0):
193 art_pop, match = similarities.pop()
194 if match < similarity:
196 results.extend(self.player.fuzzy_find_artist(art_pop))
197 results and self.log.debug('Similarity: %d%%' % match) # pylint: disable=w0106
200 def lfm_similar_artists(self, artist=None):
202 Retrieve similar artists on last.fm server.
205 current = self.player.current
209 # initialize artists deque list to construct from DB
211 as_artists = simafm.get_similar(artist=current.artist)
212 self.log.debug('Requesting last.fm for "{0.artist}"'.format(current))
214 [as_art.append((a, m)) for a, m in as_artists]
215 except XmlFMHTTPError as err:
216 self.log.warning('last.fm http error: %s' % err)
217 except XmlFMNotFound as err:
218 self.log.warning("last.fm: %s" % err)
219 except XmlFMError as err:
220 self.log.warning('last.fm module error: %s' % err)
222 self.log.debug('Fetched %d artist(s) from last.fm' % len(as_art))
225 def get_recursive_similar_artist(self):
227 history = deque(self.history)
230 current = self.player.current
232 while depth < self.plugin_conf.getint('depth'):
233 if len(history) == 0:
235 trk = history.popleft()
236 if (trk.artist in [trk.artist for trk in extra_arts]
237 or trk.artist == current.artist):
239 extra_arts.append(trk)
241 self.log.info('EXTRA ARTS: {}'.format(
242 '/'.join([trk.artist for trk in extra_arts])))
243 for artist in extra_arts:
244 self.log.debug('Looking for artist similar to "{0.artist}" as well'.format(artist))
245 similar = self.lfm_similar_artists(artist=artist)
248 similar = sorted(similar, key=lambda sim: sim[1], reverse=True)
249 ret_extra.extend(self.get_artists_from_player(similar))
250 if current.artist in ret_extra:
251 ret_extra.remove(current.artist)
254 def get_local_similar_artists(self):
255 """Check against local player for similar artists fetched from last.fm
257 current = self.player.current
258 self.log.info('Looking for artist similar to "{0.artist}"'.format(current))
259 similar = self.lfm_similar_artists()
261 self.log.info('Got nothing from last.fm!')
263 similar = sorted(similar, key=lambda sim: sim[1], reverse=True)
264 self.log.info('First five similar artist(s): {}...'.format(
265 ' / '.join([a for a, m in similar[0:5]])))
266 self.log.info('Looking availability in music library')
267 ret = self.get_artists_from_player(similar)
269 if len(self.history) >= 2:
270 ret_extra = self.get_recursive_similar_artist()
272 self.log.warning('Got nothing from music library.')
273 self.log.warning('Try running in debug mode to guess why...')
276 ret = list(set(ret) | set(ret_extra))
277 self.log.info('Got {} artists in library'.format(len(ret)))
278 self.log.info(' / '.join(ret))
279 # Move around similars items to get in unplayed|not recently played
281 return self._get_artists_list_reorg(ret)
283 def _get_album_history(self, artist=None):
284 """Retrieve album history"""
285 duration = self.daemon_conf.getint('sima', 'history_duration')
287 for trk in self.sdb.get_history(artist=artist, duration=duration):
288 albums_list.add(trk[1])
291 def find_album(self, artists):
292 """Find albums to queue.
296 target_album_to_add = self.plugin_conf.getint('album_to_add')
297 for artist in artists:
298 self.log.info('Looking for an album to add for "%s"...' % artist)
299 albums = self.player.find_albums(artist)
300 # albums yet in history for this artist
301 albums_yet_in_hist = albums & self._get_album_history(artist=artist)
302 albums_not_in_hist = list(albums - albums_yet_in_hist)
303 # Get to next artist if there are no unplayed albums
304 if not albums_not_in_hist:
305 self.log.info('No album found for "%s"' % artist)
307 album_to_queue = str()
308 random.shuffle(albums_not_in_hist)
309 for album in albums_not_in_hist:
310 tracks = self.player.find_album(artist, album)
311 if tracks and self.sdb.get_bl_album(tracks[0], add_not=True):
312 self.log.info('Blacklisted album: "%s"' % album)
313 self.log.debug('using track: "%s"' % tracks[0])
315 # Look if one track of the album is already queued
316 # Good heuristic, at least enough to guess if the whole album is
318 if tracks[0] in self.player.queue:
319 self.log.debug('"%s" already queued, skipping!' %
322 album_to_queue = album
323 if not album_to_queue:
324 self.log.info('No album found for "%s"' % artist)
326 self.log.info('last.fm album candidate: {0} - {1}'.format(
327 artist, album_to_queue))
329 self.to_add.extend(self.player.find_album(artist, album_to_queue))
330 if nb_album_add == target_album_to_add:
334 """Get some tracks for track queue mode
336 artists = self.get_local_similar_artists()
337 nbtracks_target = self.plugin_conf.getint('track_to_add')
338 for artist in artists:
339 self.log.debug('Trying to find titles to add for "{}"'.format(
341 found = self.player.find_track(artist)
342 # find tracks not in history for artist
343 self.filter_track(found)
344 if len(self.to_add) == nbtracks_target:
347 self.log.debug('Found no tracks to queue, is your ' +
348 'history getting too large?')
350 for track in self.to_add:
351 self.log.info('last.fm candidate: {0!s}'.format(track))
354 """Get albums for album queue mode
356 artists = self.get_local_similar_artists()
357 self.find_album(artists)
360 """Get some tracks for top track queue mode
362 #artists = self.get_local_similar_artists()
365 def callback_need_track(self):
366 self._cleanup_cache()
367 if not self.player.current:
368 self.log.info('Not currently playing track, cannot queue')
371 candidates = self.to_add
373 if self.plugin_conf.get('queue_mode') != 'album':
374 random.shuffle(candidates)
377 def callback_player_database(self):
381 # vim: ai ts=4 sw=4 sts=4 expandtab