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