]> kaliko git repositories - mpd-sima.git/blob - sima/plugins/lastfm.py
blacklisting 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 def blacklist(artist=False, album=False, track=False):
39     field = (bl for bl in (artist, album, track))
40     def decorated(func):
41         def wrapper(*args, **kwargs):
42             cls = args[0]
43             bl_fun = (cls._Plugin__daemon.sdb.get_bl_artist,
44                       cls._Plugin__daemon.sdb.get_bl_album,
45                       cls._Plugin__daemon.sdb.get_bl_track,)
46             #bl_getter = next(fn for fn, bl in zip(bl_fun, field) if bl is True)
47             bl_getter = next(dropwhile(lambda _: not next(field), bl_fun))
48             results = func(*args, **kwargs)
49             cls.log.debug('using {0} as bl filter'.format(bl_getter.__name__))
50             for elem in results:
51                 if bl_getter(elem, add_not=True):
52                     cls.log.info('Blacklisted: {0}'.format(elem))
53                     results.remove(elem)
54             return results
55         return wrapper
56     return decorated
57
58
59 class Lastfm(Plugin):
60     """last.fm similar artists
61     """
62
63     def __init__(self, daemon):
64         Plugin.__init__(self, daemon)
65         self.daemon_conf = daemon.config
66         self.sdb = daemon.sdb
67         self.history = daemon.short_history
68         ##
69         self.to_add = list()
70         self._cache = None
71         self._flush_cache()
72         wrapper = {
73                 'track': self._track,
74                 'top': self._top,
75                 'album': self._album,
76                 }
77         self.queue_mode = wrapper.get(self.plugin_conf.get('queue_mode'))
78
79     def _flush_cache(self):
80         """
81         Both flushes and instanciates _cache
82         """
83         if isinstance(self._cache, dict):
84             self.log.info('Lastfm: Flushing cache!')
85         else:
86             self.log.info('Lastfm: Initialising cache!')
87         self._cache = {
88                 'artists': None,
89                 'asearch': dict(),
90                 'tsearch': dict(),
91                 }
92         self._cache['artists'] = frozenset(self.player.list('artist'))
93
94     def _cleanup_cache(self):
95         """Avoid bloated cache
96         """
97         for _ , val in self._cache.items():
98             if isinstance(val, dict):
99                 while len(val) > 150:
100                     val.popitem()
101
102     def get_history(self, artist):
103         """Constructs list of Track for already played titles for an artist.
104         """
105         duration = self.daemon_conf.getint('sima', 'history_duration')
106         tracks_from_db = self.sdb.get_history(duration=duration, artist=artist)
107         # Construct Track() objects list from database history
108         played_tracks = [Track(artist=tr[-1], album=tr[1], title=tr[2],
109                                file=tr[3]) for tr in tracks_from_db]
110         return played_tracks
111
112     def filter_track(self, tracks):
113         """
114         Extract one unplayed track from a Track object list.
115             * not in history
116             * not already in the queue
117         """
118         artist = tracks[0].artist
119         black_list = self.player.queue + self.to_add
120         not_in_hist = list(set(tracks) - set(self.get_history(artist=artist)))
121         if not not_in_hist:
122             self.log.debug('All tracks already played for "{}"'.format(artist))
123         random.shuffle(not_in_hist)
124         candidate = [ trk for trk in not_in_hist if trk not in black_list ]
125         if not candidate:
126             self.log.debug('Unable to find title to add' +
127                           ' for "%s".' % artist)
128             return None
129         self.to_add.append(random.choice(candidate))
130
131     def _get_artists_list_reorg(self, alist):
132         """
133         Move around items in artists_list in order to play first not recently
134         played artists
135         """
136         # TODO: move to utils as a decorator
137         duration = self.daemon_conf.getint('sima', 'history_duration')
138         art_in_hist = list()
139         for trk in self.sdb.get_history(duration=duration,
140                                         artists=alist):
141             if trk[0] not in art_in_hist:
142                 art_in_hist.append(trk[0])
143         art_in_hist.reverse()
144         art_not_in_hist = [ ar for ar in alist if ar not in art_in_hist ]
145         random.shuffle(art_not_in_hist)
146         art_not_in_hist.extend(art_in_hist)
147         self.log.debug('history ordered: {}'.format(
148                        ' / '.join(art_not_in_hist)))
149         return art_not_in_hist
150
151     @blacklist(artist=True)
152     @cache
153     def get_artists_from_player(self, similarities):
154         """
155         Look in player library for availability of similar artists in
156         similarities
157         """
158         dynamic = int(self.plugin_conf.get('dynamic'))
159         if dynamic <= 0:
160             dynamic = 100
161         similarity = int(self.plugin_conf.get('similarity'))
162         results = list()
163         similarities.reverse()
164         while (len(results) < dynamic
165             and len(similarities) > 0):
166             art_pop, match = similarities.pop()
167             if match < similarity:
168                 break
169             results.extend(self.player.fuzzy_find(art_pop))
170         results and self.log.debug('Similarity: %d%%' % match) # pylint: disable=w0106
171         return results
172
173     def lfm_similar_artists(self, artist=None):
174         """
175         Retrieve similar artists on last.fm server.
176         """
177         if artist is None:
178             current = self.player.current
179         else:
180             current = artist
181         simafm = SimaFM()
182         # initialize artists deque list to construct from DB
183         as_art = deque()
184         as_artists = simafm.get_similar(artist=current.artist)
185         self.log.debug('Requesting last.fm for "{0.artist}"'.format(current))
186         try:
187             [as_art.append((a, m)) for a, m in as_artists]
188         except XmlFMHTTPError as err:
189             self.log.warning('last.fm http error: %s' % err)
190         except XmlFMNotFound as err:
191             self.log.warning("last.fm: %s" % err)
192         except XmlFMError as err:
193             self.log.warning('last.fm module error: %s' % err)
194         if as_art:
195             self.log.debug('Fetched %d artist(s) from last.fm' % len(as_art))
196         return as_art
197
198     def get_recursive_similar_artist(self):
199         history = deque(self.history)
200         history.popleft()
201         ret_extra = list()
202         depth = 0
203         current = self.player.current
204         extra_arts = list()
205         while depth < int(self.plugin_conf.get('depth')):
206             trk = history.popleft()
207             if trk.artist in [trk.artist for trk in extra_arts]:
208                 continue
209             extra_arts.append(trk)
210             depth += 1
211             if len(history) == 0:
212                 break
213         self.log.info('EXTRA ARTS: {}'.format(
214             '/'.join([trk.artist for trk in extra_arts])))
215         for artist in extra_arts:
216             self.log.debug('Looking for artist similar to "{0.artist}" as well'.format(artist))
217             similar = self.lfm_similar_artists(artist=artist)
218             similar = sorted(similar, key=lambda sim: sim[1], reverse=True)
219             ret_extra.extend(self.get_artists_from_player(similar))
220             if current.artist in ret_extra:
221                 ret_extra.remove(current.artist)
222         return ret_extra
223
224     def get_local_similar_artists(self):
225         """Check against local player for similar artists fetched from last.fm
226         """
227         current = self.player.current
228         self.log.info('Looking for artist similar to "{0.artist}"'.format(current))
229         similar = self.lfm_similar_artists()
230         if not similar:
231             self.log.info('Got nothing from last.fm!')
232             return []
233         similar = sorted(similar, key=lambda sim: sim[1], reverse=True)
234         self.log.info('First five similar artist(s): {}...'.format(
235                       ' / '.join([a for a, m in similar[0:5]])))
236         self.log.info('Looking availability in music library')
237         ret = self.get_artists_from_player(similar)
238         ret_extra = None
239         if len(self.history) >= 2:
240             ret_extra = self.get_recursive_similar_artist()
241         if not ret:
242             self.log.warning('Got nothing from music library.')
243             self.log.warning('Try running in debug mode to guess why...')
244             return []
245         if ret_extra:
246             ret = list(set(ret) | set(ret_extra))
247         self.log.info('Got {} artists in library'.format(len(ret)))
248         self.log.info(' / '.join(ret))
249         # Move around similars items to get in unplayed|not recently played
250         # artist first.
251         return self._get_artists_list_reorg(ret)
252
253     def _track(self):
254         """Get some tracks for track queue mode
255         """
256         artists = self.get_local_similar_artists()
257         nbtracks_target = int(self.plugin_conf.get('track_to_add'))
258         for artist in artists:
259             self.log.debug('Trying to find titles to add for "{}"'.format(
260                            artist))
261             found = self.player.find_track(artist)
262             # find tracks not in history for artist
263             self.filter_track(found)
264             if len(self.to_add) == nbtracks_target:
265                 break
266         if not self.to_add:
267             self.log.debug('Found no unplayed tracks, is your ' +
268                              'history getting too large?')
269             return None
270         for track in self.to_add:
271             self.log.info('last.fm candidate: {0!s}'.format(track))
272
273     def _album(self):
274         """Get albums for album queue mode
275         """
276         #artists = self.get_local_similar_artists()
277         pass
278
279     def _top(self):
280         """Get some tracks for top track queue mode
281         """
282         #artists = self.get_local_similar_artists()
283         pass
284
285     def callback_need_track(self):
286         self._cleanup_cache()
287         if not self.player.current:
288             self.log.info('Not currently playing track, cannot queue')
289             return None
290         self.queue_mode()
291         candidates = self.to_add
292         self.to_add = list()
293         return candidates
294
295     def callback_player_database(self):
296         self._flush_cache()
297
298 # VIM MODLINE
299 # vim: ai ts=4 sw=4 sts=4 expandtab