]> kaliko git repositories - mpd-sima.git/blob - sima/plugins/lastfm.py
Some hesitation regarding blacklist decorator…
[mpd-sima.git] / sima / plugins / lastfm.py
1 # -*- coding: utf-8 -*-
2 """
3 Fetching similar artists from last.fm web services
4 """
5
6 # standart 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 componants
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._cache.get('asearch').update({hashedlst:list(results)})
34         random.shuffle(results)
35         return results
36     return wrapper
37
38
39 def blacklist(artist=False, album=False, track=False):
40     #pylint: disable=C0111,W0212
41     field = (artist, album, track)
42     def decorated(func):
43         def wrapper(*args, **kwargs):
44             cls = args[0]
45             boolgen = (bl for bl in field)
46             bl_fun = (cls._Plugin__daemon.sdb.get_bl_artist,
47                       cls._Plugin__daemon.sdb.get_bl_album,
48                       cls._Plugin__daemon.sdb.get_bl_track,)
49             #bl_getter = next(fn for fn, bl in zip(bl_fun, boolgen) if bl is True)
50             bl_getter = next(dropwhile(lambda _: not next(boolgen), bl_fun))
51             cls.log.debug('using {0} as bl filter'.format(bl_getter.__name__))
52             if artist:
53                 results = func(*args, **kwargs)
54                 for elem in results:
55                     if bl_getter(elem, add_not=True):
56                         cls.log.info('Blacklisted: {0}'.format(elem))
57                         results.remove(elem)
58                 return results
59             if track:
60                 for elem in args[1]:
61                     if bl_getter(elem, add_not=True):
62                         cls.log.info('Blacklisted: {0}'.format(elem))
63                         args[1].remove(elem)
64                 return func(*args, **kwargs)
65         return wrapper
66     return decorated
67
68
69 class Lastfm(Plugin):
70     """last.fm similar artists
71     """
72
73     def __init__(self, daemon):
74         Plugin.__init__(self, daemon)
75         self.daemon_conf = daemon.config
76         self.sdb = daemon.sdb
77         self.history = daemon.short_history
78         ##
79         self.to_add = list()
80         self._cache = None
81         self._flush_cache()
82         wrapper = {
83                 'track': self._track,
84                 'top': self._top,
85                 'album': self._album,
86                 }
87         self.queue_mode = wrapper.get(self.plugin_conf.get('queue_mode'))
88
89     def _flush_cache(self):
90         """
91         Both flushes and instanciates _cache
92         """
93         if isinstance(self._cache, dict):
94             self.log.info('Lastfm: Flushing cache!')
95         else:
96             self.log.info('Lastfm: Initialising cache!')
97         self._cache = {
98                 'artists': None,
99                 'asearch': dict(),
100                 'tsearch': dict(),
101                 }
102         self._cache['artists'] = frozenset(self.player.list('artist'))
103
104     def _cleanup_cache(self):
105         """Avoid bloated cache
106         """
107         for _ , val in self._cache.items():
108             if isinstance(val, dict):
109                 while len(val) > 150:
110                     val.popitem()
111
112     def get_history(self, artist):
113         """Constructs list of Track for already played titles for an artist.
114         """
115         duration = self.daemon_conf.getint('sima', 'history_duration')
116         tracks_from_db = self.sdb.get_history(duration=duration, artist=artist)
117         # Construct Track() objects list from database history
118         played_tracks = [Track(artist=tr[-1], album=tr[1], title=tr[2],
119                                file=tr[3]) for tr in tracks_from_db]
120         return played_tracks
121
122     #@blacklist(track=True)
123     def filter_track(self, tracks):
124         """
125         Extract one unplayed track from a Track object list.
126             * not in history
127             * not already in the queue
128             * not blacklisted
129         """
130         artist = tracks[0].artist
131         black_list = self.player.queue + self.to_add
132         not_in_hist = list(set(tracks) - set(self.get_history(artist=artist)))
133         if not not_in_hist:
134             self.log.debug('All tracks already played for "{}"'.format(artist))
135         random.shuffle(not_in_hist)
136         #candidate = [ trk for trk in not_in_hist if trk not in black_list 
137                       #if not self.sdb.get_bl_track(trk, add_not=True)]
138         candidate = []
139         for trk in [_ for _ in not_in_hist if _ not in black_list]:
140             if self.sdb.get_bl_track(trk, add_not=True):
141                 self.log.info('Blacklisted: {0}: '.format(trk))
142                 continue
143             if self.sdb.get_bl_album(trk, add_not=True):
144                 self.log.info('Blacklisted album: {0}: '.format(trk))
145                 continue
146             candidate.append(trk)
147         if not candidate:
148             self.log.debug('Unable to find title to add' +
149                            ' for "%s".' % artist)
150             return None
151         #@blacklist(track=True)
152         #def deco(self, args):
153             #return args
154         #candidate = deco(self, candidate)
155         self.to_add.append(random.choice(candidate))
156         return self.to_add
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 = int(self.plugin_conf.get('dynamic'))
186         if dynamic <= 0:
187             dynamic = 100
188         similarity = int(self.plugin_conf.get('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(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         history = deque(self.history)
227         history.popleft()
228         ret_extra = list()
229         depth = 0
230         current = self.player.current
231         extra_arts = list()
232         while depth < int(self.plugin_conf.get('depth')):
233             trk = history.popleft()
234             if trk.artist in [trk.artist for trk in extra_arts]:
235                 continue
236             extra_arts.append(trk)
237             depth += 1
238             if len(history) == 0:
239                 break
240         self.log.info('EXTRA ARTS: {}'.format(
241             '/'.join([trk.artist for trk in extra_arts])))
242         for artist in extra_arts:
243             self.log.debug('Looking for artist similar to "{0.artist}" as well'.format(artist))
244             similar = self.lfm_similar_artists(artist=artist)
245             similar = sorted(similar, key=lambda sim: sim[1], reverse=True)
246             ret_extra.extend(self.get_artists_from_player(similar))
247             if current.artist in ret_extra:
248                 ret_extra.remove(current.artist)
249         return ret_extra
250
251     def get_local_similar_artists(self):
252         """Check against local player for similar artists fetched from last.fm
253         """
254         current = self.player.current
255         self.log.info('Looking for artist similar to "{0.artist}"'.format(current))
256         similar = self.lfm_similar_artists()
257         if not similar:
258             self.log.info('Got nothing from last.fm!')
259             return []
260         similar = sorted(similar, key=lambda sim: sim[1], reverse=True)
261         self.log.info('First five similar artist(s): {}...'.format(
262                       ' / '.join([a for a, m in similar[0:5]])))
263         self.log.info('Looking availability in music library')
264         ret = self.get_artists_from_player(similar)
265         ret_extra = None
266         if len(self.history) >= 2:
267             ret_extra = self.get_recursive_similar_artist()
268         if not ret:
269             self.log.warning('Got nothing from music library.')
270             self.log.warning('Try running in debug mode to guess why...')
271             return []
272         if ret_extra:
273             ret = list(set(ret) | set(ret_extra))
274         self.log.info('Got {} artists in library'.format(len(ret)))
275         self.log.info(' / '.join(ret))
276         # Move around similars items to get in unplayed|not recently played
277         # artist first.
278         return self._get_artists_list_reorg(ret)
279
280     def _track(self):
281         """Get some tracks for track queue mode
282         """
283         artists = self.get_local_similar_artists()
284         nbtracks_target = int(self.plugin_conf.get('track_to_add'))
285         for artist in artists:
286             self.log.debug('Trying to find titles to add for "{}"'.format(
287                            artist))
288             found = self.player.find_track(artist)
289             # find tracks not in history for artist
290             self.filter_track(found)
291             if len(self.to_add) == nbtracks_target:
292                 break
293         if not self.to_add:
294             self.log.debug('Found no unplayed tracks, is your ' +
295                              'history getting too large?')
296             return None
297         for track in self.to_add:
298             self.log.info('last.fm candidate: {0!s}'.format(track))
299
300     def _album(self):
301         """Get albums for album queue mode
302         """
303         #artists = self.get_local_similar_artists()
304         pass
305
306     def _top(self):
307         """Get some tracks for top track queue mode
308         """
309         #artists = self.get_local_similar_artists()
310         pass
311
312     def callback_need_track(self):
313         self._cleanup_cache()
314         if not self.player.current:
315             self.log.info('Not currently playing track, cannot queue')
316             return None
317         self.queue_mode()
318         candidates = self.to_add
319         self.to_add = list()
320         return candidates
321
322     def callback_player_database(self):
323         self._flush_cache()
324
325 # VIM MODLINE
326 # vim: ai ts=4 sw=4 sts=4 expandtab