1 # -*- coding: utf-8 -*-
3 Fetching similar artists from last.fm web services
6 # standart library import
9 from collections import deque
10 from hashlib import md5
12 # third parties componants
15 from ..lib.plugin import Plugin
16 from ..lib.simafm import SimaFM, XmlFMHTTPError, XmlFMNotFound, XmlFMError
17 from ..lib.track import Track
21 """Caching decorator"""
22 def wrapper(*args, **kwargs):
23 #pylint: disable=W0212,C0111
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)
31 results = func(*args, **kwargs)
32 cls._cache.get('asearch').update({hashedlst:list(results)})
33 random.shuffle(results)
39 """last.fm similar artists
42 def __init__(self, daemon):
43 Plugin.__init__(self, daemon)
44 self.daemon_conf = daemon.config
46 self.history = daemon.short_history
56 self.queue_mode = wrapper.get(self.plugin_conf.get('queue_mode'))
58 def _flush_cache(self):
60 Both flushes and instanciates _cache
62 if isinstance(self._cache, dict):
63 self.log.info('Lastfm: Flushing cache!')
65 self.log.info('Lastfm: Initialising cache!')
71 self._cache['artists'] = frozenset(self.player.list('artist'))
73 def _cleanup_cache(self):
74 """Avoid bloated cache
76 # TODO: call cleanup once its dict instance are used somewhere XXX
77 for _ , val in self._cache.items():
78 if isinstance(val, dict):
82 def get_history(self, artist):
83 """Constructs list of Track for already played titles for an artist.
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]
92 def filter_track(self, tracks):
94 Extract one unplayed track from a Track object list.
96 * not already in the queue
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)))
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 ]
106 self.log.debug('Unable to find title to add' +
107 ' for "%s".' % artist)
109 self.to_add.append(random.choice(candidate))
111 def _get_artists_list_reorg(self, alist):
113 Move around items in artists_list in order to play first not recently
116 # TODO: move to utils as a decorator
117 duration = self.daemon_conf.getint('sima', 'history_duration')
119 for trk in self.sdb.get_history(duration=duration,
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
132 def get_artists_from_player(self, similarities):
134 Look in player library for availability of similar artists in
137 dynamic = int(self.plugin_conf.get('dynamic'))
140 similarity = int(self.plugin_conf.get('similarity'))
142 similarities.reverse()
143 while (len(results) < dynamic
144 and len(similarities) > 0):
145 art_pop, match = similarities.pop()
146 if match < similarity:
148 results.extend(self.player.fuzzy_find(art_pop))
149 results and self.log.debug('Similarity: %d%%' % match) # pylint: disable=w0106
152 def lfm_similar_artists(self, artist=None):
154 Retrieve similar artists on last.fm server.
157 current = self.player.current
161 # initialize artists deque list to construct from DB
163 as_artists = simafm.get_similar(artist=current.artist)
164 self.log.debug('Requesting last.fm for "{0.artist}"'.format(current))
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)
174 self.log.debug('Fetched %d artist(s) from last.fm' % len(as_art))
177 def get_recursive_similar_artist(self):
178 history = deque(self.history)
182 current = self.player.current
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]:
188 extra_arts.append(trk)
190 if len(history) == 0:
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)
203 def get_local_similar_artists(self):
204 """Check against local player for similar artists fetched from last.fm
206 current = self.player.current
207 self.log.info('Looking for artist similar to "{0.artist}"'.format(current))
208 similar = self.lfm_similar_artists()
210 self.log.info('Got nothing from last.fm!')
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)
218 if len(self.history) >= 2:
219 ret_extra = self.get_recursive_similar_artist()
221 self.log.warning('Got nothing from music library.')
222 self.log.warning('Try running in debug mode to guess why...')
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
230 return self._get_artists_list_reorg(ret)
233 """Get some tracks for track queue mode
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(
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:
246 self.log.debug('Found no unplayed tracks, is your ' +
247 'history getting too large?')
249 for track in self.to_add:
250 self.log.info('last.fm candidate: {0!s}'.format(track))
253 """Get albums for album queue mode
255 #artists = self.get_local_similar_artists()
259 """Get some tracks for top track queue mode
261 #artists = self.get_local_similar_artists()
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')
270 candidates = self.to_add
274 def callback_player_database(self):
278 # vim: ai ts=4 sw=4 sts=4 expandtab