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