1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2009-2014 Jack Kaliko <kaliko@azylum.org>
4 # This file is part of sima
6 # sima is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # sima is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with sima. If not, see <http://www.gnu.org/licenses/>.
21 Fetching similar artists from last.fm web services
24 # standard library import
27 from collections import deque
28 from hashlib import md5
30 # third parties components
33 from .plugin import Plugin
34 from .track import Track
35 from .meta import Artist
36 from ..utils.utils import WSError
39 """Caching decorator"""
40 def wrapper(*args, **kwargs):
41 #pylint: disable=W0212,C0111
43 similarities = [art for art in args[1]]
44 hashedlst = md5(''.join(similarities).encode('utf-8')).hexdigest()
45 if hashedlst in cls._cache.get('asearch'):
46 cls.log.debug('cached request')
47 results = cls._cache.get('asearch').get(hashedlst)
49 results = func(*args, **kwargs)
50 cls.log.debug('caching request')
51 cls._cache.get('asearch').update({hashedlst:list(results)})
52 random.shuffle(results)
57 class WebService(Plugin):
58 """similar artists webservice
61 def __init__(self, daemon):
62 Plugin.__init__(self, daemon)
63 self.daemon_conf = daemon.config
65 self.history = daemon.short_history
75 self.queue_mode = wrapper.get(self.plugin_conf.get('queue_mode'))
78 def _flush_cache(self):
80 Both flushes and instanciates _cache
82 name = self.__class__.__name__
83 if isinstance(self._cache, dict):
84 self.log.info('{0}: Flushing cache!'.format(name))
86 self.log.info('{0}: Initialising cache!'.format(name))
92 def _cleanup_cache(self):
93 """Avoid bloated cache
95 for _, val in self._cache.items():
96 if isinstance(val, dict):
100 def get_history(self, artist):
101 """Constructs list of Track for already played titles for an artist.
103 duration = self.daemon_conf.getint('sima', 'history_duration')
104 tracks_from_db = self.sdb.get_history(duration=duration, artist=artist)
105 # Construct Track() objects list from database history
106 played_tracks = [Track(artist=tr[-1], album=tr[1], title=tr[2],
107 file=tr[3]) for tr in tracks_from_db]
110 def filter_track(self, tracks):
112 Extract one unplayed track from a Track object list.
114 * not already in the queue
117 artist = tracks[0].artist
118 black_list = self.player.queue + self.to_add
119 not_in_hist = list(set(tracks) - set(self.get_history(artist=artist)))
120 if self.plugin_conf.get('queue_mode') != 'top' and not not_in_hist:
121 self.log.debug('All tracks already played for "{}"'.format(artist))
122 random.shuffle(not_in_hist)
124 for trk in [_ for _ in not_in_hist if _ not in black_list]:
125 # Should use albumartist heuristic as well
126 if self.plugin_conf.getboolean('single_album'):
127 if (trk.album == self.player.current.album or
128 trk.album in [tr.album for tr in self.to_add]):
129 self.log.debug('Found unplayed track ' +
130 'but from an album already queued: %s' % (trk))
132 candidate.append(trk)
135 self.to_add.append(random.choice(candidate))
138 def _get_artists_list_reorg(self, alist):
140 Move around items in artists_list in order to play first not recently
143 # TODO: move to utils as a decorator
144 duration = self.daemon_conf.getint('sima', 'history_duration')
146 for trk in self.sdb.get_history(duration=duration,
148 if trk[0] not in art_in_hist:
149 art_in_hist.append(trk[0])
150 art_in_hist.reverse()
151 art_not_in_hist = [ar for ar in alist if ar not in art_in_hist]
152 random.shuffle(art_not_in_hist)
153 art_not_in_hist.extend(art_in_hist)
154 self.log.info('{}'.format(
155 ' / '.join(art_not_in_hist)))
156 return art_not_in_hist
159 def get_artists_from_player(self, similarities):
161 Look in player library for availability of similar artists in
164 dynamic = self.plugin_conf.getint('max_art')
168 similarities.reverse()
169 while (len(results) < dynamic
170 and len(similarities) > 0):
171 art_pop = similarities.pop()
172 results.extend(self.player.fuzzy_find_artist(art_pop))
175 def ws_similar_artists(self, artist=None):
177 Retrieve similar artists from WebServive.
180 curr = self.player.current.__dict__
181 name = curr.get('artist')
182 mbid = curr.get('musicbrainz_artistid', None)
183 current = Artist(name=name, mbid=mbid)
186 # initialize artists deque list to construct from DB
188 as_artists = self.ws().get_similar(artist=current)
189 self.log.debug('Requesting {1} for "{0}"'.format(current,
192 # TODO: let's propagate Artist type
193 [as_art.append(str(art)) for art in as_artists]
194 except WSError as err:
195 self.log.warning('{0}: {1}'.format(self.ws.name, err))
197 self.log.debug('Fetched {0} artist(s)'.format(len(as_art)))
200 def get_recursive_similar_artist(self):
202 history = deque(self.history)
205 current = self.player.current
207 while depth < self.plugin_conf.getint('depth'):
208 if len(history) == 0:
210 trk = history.popleft()
211 if (trk.artist in [trk.artist for trk in extra_arts]
212 or trk.artist == current.artist):
214 extra_arts.append(trk)
216 self.log.info('EXTRA ARTS: {}'.format(
217 '/'.join([trk.artist for trk in extra_arts])))
218 for artist in extra_arts:
220 'Looking for artist similar to "{0.artist}" as well'.format(
222 similar = self.ws_similar_artists(artist=artist)
225 ret_extra.extend(self.get_artists_from_player(similar))
226 if current.artist in ret_extra:
227 ret_extra.remove(current.artist)
230 def get_local_similar_artists(self):
231 """Check against local player for similar artists
233 current = self.player.current
234 self.log.info('Looking for artist similar to "{0.artist}"'.format(current))
235 similar = self.ws_similar_artists()
237 self.log.info('Got nothing from {0}!'.format(self.ws.name))
239 self.log.info('First five similar artist(s): {}...'.format(
240 ' / '.join([a for a in list(similar)[0:5]])))
241 self.log.info('Looking availability in music library')
242 ret = self.get_artists_from_player(similar)
244 if len(self.history) >= 2:
245 if self.plugin_conf.getint('depth') > 1:
246 ret_extra = self.get_recursive_similar_artist()
248 ret = list(set(ret) | set(ret_extra))
250 self.log.warning('Got nothing from music library.')
251 self.log.warning('Try running in debug mode to guess why...')
253 self.log.info('Got {} artists in library'.format(len(ret)))
254 # Move around similars items to get in unplayed|not recently played
256 return self._get_artists_list_reorg(ret)
258 def _get_album_history(self, artist=None):
259 """Retrieve album history"""
260 duration = self.daemon_conf.getint('sima', 'history_duration')
262 for trk in self.sdb.get_history(artist=artist, duration=duration):
263 albums_list.add(trk[1])
266 def find_album(self, artists):
267 """Find albums to queue.
271 target_album_to_add = self.plugin_conf.getint('album_to_add')
272 for artist in artists:
273 self.log.info('Looking for an album to add for "%s"...' % artist)
274 albums = self.player.find_albums(artist)
275 # str conversion while Album type is not propagated
276 albums = [str(album) for album in albums]
278 self.log.debug('Albums candidate: {0:s}'.format(
281 # albums yet in history for this artist
283 albums_yet_in_hist = albums & self._get_album_history(artist=artist)
284 albums_not_in_hist = list(albums - albums_yet_in_hist)
285 # Get to next artist if there are no unplayed albums
286 if not albums_not_in_hist:
287 self.log.info('No album found for "%s"' % artist)
289 album_to_queue = str()
290 random.shuffle(albums_not_in_hist)
291 for album in albums_not_in_hist:
292 tracks = self.player.find_album(artist, album)
293 # Look if one track of the album is already queued
294 # Good heuristic, at least enough to guess if the whole album is
296 if tracks[0] in self.player.queue:
297 self.log.debug('"%s" already queued, skipping!' %
300 album_to_queue = album
301 if not album_to_queue:
302 self.log.info('No album found for "%s"' % artist)
304 self.log.info('{2} album candidate: {0} - {1}'.format(
305 artist, album_to_queue, self.ws.name))
307 self.to_add.extend(self.player.find_album(artist, album_to_queue))
308 if nb_album_add == target_album_to_add:
311 def find_top(self, artists):
313 find top tracks for artists in artists list.
316 nbtracks_target = self.plugin_conf.getint('track_to_add')
318 for artist in artists:
319 artist = Artist(name=artist)
320 if len(self.to_add) == nbtracks_target:
322 self.log.info('Looking for a top track for {0}'.format(artist))
325 titles = [t for t in webserv.get_toptrack(artist)]
326 except WSError as err:
327 self.log.warning('{0}: {1}'.format(self.ws.name, err))
328 if self.ws.ratelimit:
329 self.log.info('{0.name} ratelimit: {0.ratelimit}'.format(self.ws))
331 found = self.player.fuzzy_find_track(artist.name, trk.title)
333 self.log.debug('{0}'.format(found[0]))
334 if self.filter_track(found):
338 """Get some tracks for track queue mode
340 artists = self.get_local_similar_artists()
341 nbtracks_target = self.plugin_conf.getint('track_to_add')
342 for artist in artists:
343 self.log.debug('Trying to find titles to add for "{}"'.format(
345 found = self.player.find_track(artist)
347 self.log.debug('Found nothing to queue for {0}'.format(artist))
349 # find tracks not in history for artist
350 self.filter_track(found)
351 if len(self.to_add) == nbtracks_target:
354 self.log.debug('Found no tracks to queue, is your ' +
355 'history getting too large?')
357 for track in self.to_add:
358 self.log.info('{1} candidates: {0!s}'.format(track, self.ws.name))
361 """Get albums for album queue mode
363 artists = self.get_local_similar_artists()
364 self.find_album(artists)
367 """Get some tracks for top track queue mode
369 artists = self.get_local_similar_artists()
370 self.find_top(artists)
371 for track in self.to_add:
372 self.log.info('{1} candidates: {0!s}'.format(track, self.ws.name))
374 def callback_need_track(self):
375 self._cleanup_cache()
376 if not self.player.current:
377 self.log.info('No current track, cannot queue')
379 if not self.player.current.artist:
380 self.log.warning('No artist set for the current track')
381 self.log.debug(repr(self.player.current))
384 self.log.debug(self.ws.stats)
385 candidates = self.to_add
387 if self.plugin_conf.get('queue_mode') != 'album':
388 random.shuffle(candidates)
391 def callback_player_database(self):
395 # vim: ai ts=4 sw=4 sts=4 expandtab