]> kaliko git repositories - mpd-sima.git/blob - sima/plugins/internal/lastfm.py
Some refactoring around player
[mpd-sima.git] / sima / plugins / internal / lastfm.py
1 # -*- coding: utf-8 -*-
2 """
3 Fetching similar artists from last.fm web services
4 """
5
6 # standard library import
7 import random
8
9 from collections import deque
10 from itertools import dropwhile
11 from hashlib import md5
12
13 # third parties components
14
15 # local import
16 from ...lib.plugin import Plugin
17 from ...lib.simafm import SimaFM, XmlFMHTTPError, XmlFMNotFound, XmlFMError
18 from ...lib.track import Track
19
20
21 def cache(func):
22     """Caching decorator"""
23     def wrapper(*args, **kwargs):
24         #pylint: disable=W0212,C0111
25         cls = args[0]
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)
31         else:
32             results = func(*args, **kwargs)
33             cls.log.debug('caching request')
34             cls._cache.get('asearch').update({hashedlst:list(results)})
35         random.shuffle(results)
36         return results
37     return wrapper
38
39
40 def blacklist(artist=False, album=False, track=False):
41     #pylint: disable=C0111,W0212
42     field = (artist, album, track)
43     def decorated(func):
44         def wrapper(*args, **kwargs):
45             cls = args[0]
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__))
53             if artist:
54                 results = func(*args, **kwargs)
55                 for elem in results:
56                     if bl_getter(elem, add_not=True):
57                         cls.log.info('Blacklisted: {0}'.format(elem))
58                         results.remove(elem)
59                 return results
60             if track:
61                 for elem in args[1]:
62                     if bl_getter(elem, add_not=True):
63                         cls.log.info('Blacklisted: {0}'.format(elem))
64                         args[1].remove(elem)
65                 return func(*args, **kwargs)
66         return wrapper
67     return decorated
68
69
70 class Lastfm(Plugin):
71     """last.fm similar artists
72     """
73
74     def __init__(self, daemon):
75         Plugin.__init__(self, daemon)
76         self.daemon_conf = daemon.config
77         self.sdb = daemon.sdb
78         self.history = daemon.short_history
79         ##
80         self.to_add = list()
81         self._cache = None
82         self._flush_cache()
83         wrapper = {
84                 'track': self._track,
85                 'top': self._top,
86                 'album': self._album,
87                 }
88         self.queue_mode = wrapper.get(self.plugin_conf.get('queue_mode'))
89
90     def _flush_cache(self):
91         """
92         Both flushes and instanciates _cache
93         """
94         if isinstance(self._cache, dict):
95             self.log.info('Lastfm: Flushing cache!')
96         else:
97             self.log.info('Lastfm: Initialising cache!')
98         self._cache = {
99                 'asearch': dict(),
100                 'tsearch': dict(),
101                 }
102
103     def _cleanup_cache(self):
104         """Avoid bloated cache
105         """
106         for _ , val in self._cache.items():
107             if isinstance(val, dict):
108                 while len(val) > 150:
109                     val.popitem()
110
111     def get_history(self, artist):
112         """Constructs list of Track for already played titles for an artist.
113         """
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]
119         return played_tracks
120
121     def filter_track(self, tracks):
122         """
123         Extract one unplayed track from a Track object list.
124             * not in history
125             * not already in the queue
126             * not blacklisted
127         """
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)))
131         if not not_in_hist:
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)]
136         candidate = []
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))
140                 continue
141             if self.sdb.get_bl_album(trk, add_not=True):
142                 self.log.info('Blacklisted album: {0}: '.format(trk))
143                 continue
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))
150                     continue
151             candidate.append(trk)
152         if not candidate:
153             self.log.debug('Unable to find title to add' +
154                            ' for "%s".' % artist)
155             return None
156         self.to_add.append(random.choice(candidate))
157
158     def _get_artists_list_reorg(self, alist):
159         """
160         Move around items in artists_list in order to play first not recently
161         played artists
162         """
163         # TODO: move to utils as a decorator
164         duration = self.daemon_conf.getint('sima', 'history_duration')
165         art_in_hist = list()
166         for trk in self.sdb.get_history(duration=duration,
167                                         artists=alist):
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
177
178     @blacklist(artist=True)
179     @cache
180     def get_artists_from_player(self, similarities):
181         """
182         Look in player library for availability of similar artists in
183         similarities
184         """
185         dynamic = self.plugin_conf.getint('dynamic')
186         if dynamic <= 0:
187             dynamic = 100
188         similarity = self.plugin_conf.getint('similarity')
189         results = list()
190         similarities.reverse()
191         while (len(results) < dynamic
192             and len(similarities) > 0):
193             art_pop, match = similarities.pop()
194             if match < similarity:
195                 break
196             results.extend(self.player.fuzzy_find_artist(art_pop))
197         results and self.log.debug('Similarity: %d%%' % match) # pylint: disable=w0106
198         return results
199
200     def lfm_similar_artists(self, artist=None):
201         """
202         Retrieve similar artists on last.fm server.
203         """
204         if artist is None:
205             current = self.player.current
206         else:
207             current = artist
208         simafm = SimaFM()
209         # initialize artists deque list to construct from DB
210         as_art = deque()
211         as_artists = simafm.get_similar(artist=current.artist)
212         self.log.debug('Requesting last.fm for "{0.artist}"'.format(current))
213         try:
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)
221         if as_art:
222             self.log.debug('Fetched %d artist(s) from last.fm' % len(as_art))
223         return as_art
224
225     def get_recursive_similar_artist(self):
226         ret_extra = list()
227         history = deque(self.history)
228         history.popleft()
229         depth = 0
230         current = self.player.current
231         extra_arts = list()
232         while depth < self.plugin_conf.getint('depth'):
233             if len(history) == 0:
234                 break
235             trk = history.popleft()
236             if (trk.artist in [trk.artist for trk in extra_arts]
237                 or trk.artist == current.artist):
238                 continue
239             extra_arts.append(trk)
240             depth += 1
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)
246             if not similar:
247                 return ret_extra
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)
252         return ret_extra
253
254     def get_local_similar_artists(self):
255         """Check against local player for similar artists fetched from last.fm
256         """
257         current = self.player.current
258         self.log.info('Looking for artist similar to "{0.artist}"'.format(current))
259         similar = self.lfm_similar_artists()
260         if not similar:
261             self.log.info('Got nothing from last.fm!')
262             return []
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)
268         ret_extra = None
269         if len(self.history) >= 2:
270             ret_extra = self.get_recursive_similar_artist()
271         if not ret:
272             self.log.warning('Got nothing from music library.')
273             self.log.warning('Try running in debug mode to guess why...')
274             return []
275         if ret_extra:
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
280         # artist first.
281         return self._get_artists_list_reorg(ret)
282
283     def _get_album_history(self, artist=None):
284         """Retrieve album history"""
285         duration = self.daemon_conf.getint('sima', 'history_duration')
286         albums_list = set()
287         for trk in self.sdb.get_history(artist=artist, duration=duration):
288             albums_list.add(trk[1])
289         return albums_list
290
291     def find_album(self, artists):
292         """Find albums to queue.
293         """
294         self.to_add = list()
295         nb_album_add = 0
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)
306                 continue
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])
314                     continue
315                 # Look if one track of the album is already queued
316                 # Good heuristic, at least enough to guess if the whole album is
317                 # already queued.
318                 if tracks[0] in self.player.queue:
319                     self.log.debug('"%s" already queued, skipping!' %
320                             tracks[0].album)
321                     continue
322                 album_to_queue = album
323             if not album_to_queue:
324                 self.log.info('No album found for "%s"' % artist)
325                 continue
326             self.log.info('last.fm album candidate: {0} - {1}'.format(
327                            artist, album_to_queue))
328             nb_album_add += 1
329             self.to_add.extend(self.player.find_album(artist, album_to_queue))
330             if nb_album_add == target_album_to_add:
331                 return True
332
333     def _track(self):
334         """Get some tracks for track queue mode
335         """
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(
340                            artist))
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:
345                 break
346         if not self.to_add:
347             self.log.debug('Found no tracks to queue, is your ' +
348                             'history getting too large?')
349             return None
350         for track in self.to_add:
351             self.log.info('last.fm candidate: {0!s}'.format(track))
352
353     def _album(self):
354         """Get albums for album queue mode
355         """
356         artists = self.get_local_similar_artists()
357         self.find_album(artists)
358
359     def _top(self):
360         """Get some tracks for top track queue mode
361         """
362         #artists = self.get_local_similar_artists()
363         pass
364
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')
369             return None
370         self.queue_mode()
371         candidates = self.to_add
372         self.to_add = list()
373         if self.plugin_conf.get('queue_mode') != 'album':
374             random.shuffle(candidates)
375         return candidates
376
377     def callback_player_database(self):
378         self._flush_cache()
379
380 # VIM MODLINE
381 # vim: ai ts=4 sw=4 sts=4 expandtab