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