def test_search_for_artist(): results = artist.search(name='Weezer') weezer = results[0] assert weezer.name == 'Weezer' assert len(weezer.blogs) != 0 for b in weezer.blogs: assert b.get('url')
def _similar_artists(self, callback, artist, threshold): timestamp = now() diff = timestamp - self.get_artist_timestamp(artist) if diff < threshold: self._logger.debug(u"similar_artists[%s]: looked up %d seconds ago" % (artist, diff)) return self.set_artist_timestamp(artist, timestamp) try: self._logger.debug(u"similar_artists[%s]: lookup" % (artist)) self._delay() a = en_artist.search(name=artist) try: i = 100.0 p = a[0].get_similar(results=100) self._logger.info(u"similar_artists[%s]: %d result(s)" % (artist, len(p))) for sim in p: callback(artist, sim.name.lower(), i / 100.0, self._title) i -= 1.0 except IndexError: self._logger.info(u"similar_artists[%s]: no result" % (artist)) return except Exception, e: self._logger.error(e) self._logger.info(u"similar_artists[%s]: no result" % (artist)) return
def get_from_spotify(artist, title): # Getting data from spotify request_url = '{}/search'.format(SPOTIFY_API) query = '{} {}'.format(artist, title) response = requests.get(request_url, params={'q': query, 'type': 'track'}).json() items = response['tracks']['items'] if not items: print "Couldn't find '{} - {}' on Spotify".format(artist, title) return None raw_track_data = items[0] track_data = dict() for attr in ['id', 'name', 'uri', 'preview_url']: track_data[attr] = raw_track_data[attr] track_data['artist_name'] = raw_track_data['artists'][0]['name'] track_data['artist_id'] = raw_track_data['artists'][0]['id'] track_data['album'] = raw_track_data['album']['name'] track_data['image'] = raw_track_data['album']['images'][0]['url'] # EchoNest enrichement songs = echonest_song.search(artist=artist, title=title) if not songs: print "Couldn't find '{} - {}' on EchoNest".format(artist, title) return None song = songs[0] track_data['audio_summary'] = song.audio_summary artist = echonest_artist.search(name=song.artist_name)[0] track_data['genres'] = [t['name'] for t in artist.terms] return Track(**track_data)
def check_if_artist_exists(artist_name): """ Check against echonest to see if an artist exists with for a given artist name """ artists = artist.search(artist_name) return len(artists) > 0
def find_artist_data(artist_name): the_artist = artist.search(artist_name, results=1)[0] print "the artist we found %s" % the_artist if not the_artist: return '' data = {} data['artist'] = the_artist.name pronouns_dict = pronoun_search(the_artist) data.update(pronouns_dict) print "we got the pronoun dict" wiki_dict = wiki_member_search(the_artist) data.update(wiki_dict) print "we got the wiki dict" images = the_artist.images data['image_urls'] = [image['url'] for image in images[0:5]] print "we got the echonest images" data['discogs_release'] = discogs_release_search(the_artist) print "we got the discogs releases" print "in find_artist_data, with a dict of %s" % data return json.dumps(data)
def get_most_familiar_artists(nresults=100): """ Get the most familiar artists according to the Echo Nest """ assert nresults <= 100,'we cant ask for more than 100 artists at the moment' locked = FAMILIARARTISTS_LOCK.acquire() assert locked,'FAMILIARARTISTS_LOCK could not lock?' # get top artists while True: try: artists = artistEN.search(sort='familiarity-desc',results=nresults, buckets=['familiarity','hotttnesss','terms', 'id:musicbrainz','id:7digital','id:playme']) break except KeyboardInterrupt: close_creation() raise except Exception as e: print(type(e),':',e) print('at time',time.ctime(),'in get_most_familiar_artists (we wait',SLEEPTIME,'seconds)') time.sleep(SLEEPTIME) continue # done FAMILIARARTISTS_LOCK.release() return artists
def find_artist(artist_name): """Return a pyechonest artist for the given artist name.""" matches = [] try: matches = search(name=artist_name, results=1) except Exception, e: print "Exception searching for %s: %s" % (artist_name, str(e)) pass
def getArtistByGenre( genre , limit ): result = artist.search( style = genre , results = limit , sort='familiarity-desc' ) listArtist = [] for artist_result in result: listArtist.append( ( artist_result.name , artist_result.id ) ) return listArtist
def ask_echonest(artist_name): # get artist artist = artist.search(name = artist_name)[0] # get song song = pyechonest.song.search(artist = artist, max_duration = 240, buckets = ["id:spotify-WW"])[0] # return song id return song.get_tracks('spotify-WW')[0]
def find_artist(self, artist_name): try: results = artist.search(name=artist_name, results=1, buckets=["id:spotify-WW"], limit=True) if results and len(results) > 0: return results[0].id, results[0].name else: return None, None except util.EchoNestAPIError: return None, None
def queue_by_name(name): results = artist.search( name, buckets=['hotttnesss', 'familiarity', 'id:' + idspace], results=1, limit=True) for r in results: fid = r.get_foreign_id(idspace=idspace) queue.append((r.hotttnesss, r.id, fid, r.name))
def similar_artists(search_artist): results = artist.search(name=search_artist) if results: r = results[0] print 'Artists similar to: %s:' % (r.name,) for similar in r.similar: print ' %s' % (similar.name,) else: print 'Artist not found'
def download_keyword(desc, count=1000): """Similar to download hot, but allows you to specify a description""" artists = search(description=desc, results=count, sort='hotttnesss-desc') print "Getting images for artists: %s" % str(artists) for i, a in enumerate(artists): print "Processing artist %d of %d" % (i, count) get_images(a) for s in a.similar: get_images(s)
def search_artist_echonest(name): ''' Returns array of artists based on search query to Echonest API. ''' # add validation via echonest here results = artist.search(name=name) if results is False: return results else: results = sorted([art.name for art in results]) return results
def search_artist_echonest(name): ''' Returns array of artists based on search query to Echonest API. ''' # add validation via echonest here results = artist.search(name=name) if results is False: return results else: sorted_results = sorted([art.name for art in results]) int_results = [(x, sorted_results[x]) for x in xrange(1, len(sorted_results))] return int_results
def search_echonest_artist_terms(artist_name): artist_results = artist.search(name=artist_name) if not artist_results: LOGGER.info('Artist not found in Echonest') return None if artist_results[0].name.lower() == artist_name.lower(): artist_terms = artist_results[0].terms if artist_terms: return max(artist_terms, key=lambda x: x['weight'] * x['frequency'])['name'] else: return None else: LOGGER.info("Artist name did not match top result: {} vs {}".format(artist_name, artist_results[0].name)) return None
def getSimilarArtists(artist_name): "Get similar artists to display" similar_artists = [] bk_results = artist.search(artist_name) bk = bk_results[0] similar_artists = bk.similar return similar_artists toPrint = '' for similar_artist in similar_artists[:3]: toPrint = toPrint + str(similar_artist) + ', ' print '\t' + toPrint[:-2]
def getEchonestMetadata(track, search_artist=True): artist_id = None possible_artists = [] possible_tracks = [] try: ''' Get all recordings from echonest with the corresponding artist and track-title ''' recordings = echonest_song.search(artist=track[0], title=track[1]) for recording in recordings: ''' check if echonest found the correct title or if it returned just similar written tracks ''' if utils.is_similar(recording.title, track[1], normalize=True) and utils.is_similar( recording.artist_name.lower(), track[0]): if artist_id is None: artist_id = recording.artist_id ''' there may exist multiple entities for one song at echonest, so I collect all the matching songs ''' possible_tracks.append(recording) ''' if we found more than one track, get the mean metadata for all of them ''' if len(possible_tracks) > 0: getEchonestTrackMetadata(possible_tracks) if search_artist: if artist_id is None: ''' if echonest couldn't find a corresponding match for the given artist and track, there are chances it will still find only the artist by it's name ''' artists = echonest_artist.search(name=track[0]) for artist in artists: if utils.is_similar(artist.name, track[0], normalize=True): possible_artists.append(artist) if len(possible_artists) > 1: pass # TODO let user choose elif len(possible_artists) == 1: getEchonestArtistMetadata(possible_artists[0]) else: getEchonestArtistMetadata(echonest_artist.Artist(artist_id)) except socket.timeout: track_md.error = True print colored("| Socket timeout...", 'red')
def echonest_artist(artist_name, key): #Takes a string varable of artist name #queries the echonest api to get closest match. #Uses ID of this to ensure correct artist object''' results = artist.search(artist_name) if len(results) > 0: pos_artist = results[0] echo_id = pos_artist.id mb_id = pos_artist.get_foreign_id() terms = pos_artist.get_terms() time.sleep(10) print artist_name return 1, terms, mb_id, artist_name, echo_id else: return 0,False,False,False,False
def getArtistsByGenre(genre, maxNum=4): """ Given genre in TODO: genreList/enum?, returns list of artists Keyword arguments: genre -- string maxNum -- 10 by default, maxNumber of artists to return (<50 please) """ #TODO: assert genre is a valid genre min_famil = 0.60 artists = artist.search(style=genre, min_familiarity=min_famil) #Gets list in format [<artist - artistName>] artistList = [] #parse artists into list for i in xrange(min(len(artists), maxNum)): artistList.append(artists[i].__str__()) return artistList
def retrieve_inf(file_path): from pyechonest import artist, track, config, song config.ECHO_NEST_API_KEY = "WUODI5WC8Y1QIHJTJ" filename = file_path _ = os.popen("avconv -y -i " + filename + " -f ffmetadata metadata.txt").read() with open("metadata.txt", 'r') as outfile: line=outfile.read().split('\n') Title = [l for l in line if "title" in l][0].split('=')[-1] Artist = [l for l in line if "artist" in l][0].split('=')[-1] _ = os.system("rm metadata.txt") Image = artist.search(name=Artist)[0].get_images()[0]['url'] return Title, Image, Artist
def get_artists_from_description(description,nresults=100): """ Return artists given a string description, for instance a tag. """ assert nresults <= 100,'we cant do more than 100 artists for the moment...' # get the artists for that description while True: try: artists = artistEN.search(description=description,sort='familiarity-desc',results=nresults, buckets=['familiarity','hotttnesss','terms','id:musicbrainz','id:7digital','id:playme']) break except (KeyboardInterrupt,NameError): close_creation() raise except Exception,e: print type(e),':',e print 'at time',time.ctime(),'in get_artistids_from_description (we wait',SLEEPTIME,'seconds)' time.sleep(SLEEPTIME) continue
def main_search(): """ http://developer.echonest.com/docs/v4/artist.html#search http://echonest.github.io/pyechonest/artist.html#pyechonest.artist.search """ results = echo_nest_artist.search( style=ECHO_NEST_GENRE, limit=True, buckets=['id:rdio-US'], sort=ECHO_NEST_GENRE_SORT, start=0, results=ECHO_NEST_GENRE_SIZE, ) artist_keys = [extract_rdio_key(artist) for artist in results] payload = { 'method': 'get', 'keys': ','.join(artist_keys), } r = requests.post(RDIO_API_URL, auth=BearerAuth(RDIO_API_TOKEN), data=payload) result_json = r.json()['result'] artist_list = [] for rdio_key in artist_keys: if rdio_key not in result_json: logging.warn('Rdio response was missing %s', rdio_key) continue artist_json = result_json[rdio_key] artist_list.append({ 'key': artist_json['key'], 'name': artist_json['name'], 'shortUrl': artist_json['shortUrl'], }) with open(GENERE_ARTIST_FILE, 'w') as fd: json.dump(artist_list, fd, indent=2)
def artiststracks3(request): from pyechonest import * if request.method == 'POST': form = NewsForm(request.POST) if form.is_valid(): the_news = [] a = form.cleaned_data['artist_name'] artist_results = artist.search(name=a) b = artist_results[0] artist_blogs = b.blogs for blog in artist_blogs: the_news.append([blog.get('name'), blog.get('date_posted')]) data = {'the_news': the_news} print data return render(request, "postlogin/artiststracks3b.html", data) else: form = NewsForm() data = {'form': form} return render(request, 'postlogin/artiststracks3.html', data)
#Set your api key from pyechonest import config config.ECHO_NEST_API_KEY="YOUR API KEY" #Find artists similar to Guns`N Roses from pyechonest import artist bk = artist.Artist('Guns and roses') print "Artists similar to: %s:" % (bk.name,) for similar_artist in bk.similar: print "\t%s" % (similar_artist.name,) #Search for artists from pyechonest import artist weezer_results = artist.search(name='weezer') weezer = weezer_results[0] weezer_blogs = weezer.blogs print 'Blogs about weezer:', [blog.get('url') for blog in weezer_blogs] #Get an artist by name: from pyechonest import artist a = artist.Artist('lady gaga') print a.id #Get the top hottt artists: from pyechonest import artist
# Uncomment to set the API key explicitly. Otherwise Pyechonest will # look in the ECHO_NEST_API_KEY environment variable for the key. # from pyechonest import config # config.ECHO_NEST_API_KEY='YOUR API KEY' from pyechonest import artist synthpop_results = artist.search(description=["synthpop"], buckets=["id:7digital", "id:musicbrainz"], results=5) for sp_artist in synthpop_results: print "%s (Echonest Nest ID: %s)" % (sp_artist.name, sp_artist.id) temp_artist = artist.Artist(sp_artist.get_foreign_id("7digital")) if temp_artist == sp_artist: print "%s (Echonest Nest ID: %s)" % (temp_artist.name, temp_artist.id) else: print "7digital artist is not the same" print " 7digitial ID: ", sp_artist.get_foreign_id("7digital") print " MusicBrainz ID: ", sp_artist.get_foreign_id("musicbrainz"), "\n"
# Uncomment to set the API key explicitly. Otherwise Pyechonest will # look in the ECHO_NEST_API_KEY environment variable for the key. #from pyechonest import config #config.ECHO_NEST_API_KEY='YOUR API KEY' from pyechonest import artist okg_results = artist.search(name='OK Go') if okg_results: okg = okg_results[0] print '%s (Echo Nest Artist ID: %s)' % (okg.name, okg.id) print 'Hotttnesss: %s, Familiarity: %s\n' % (okg.hotttnesss, okg.familiarity) print 'Terms: ', ', '.join([term.get('name') for term in okg.terms]), '\n' print 'Similar artists: ', ', '.join(similar_artist.name for similar_artist in okg.similar), '\n' print 'Artist URLs:' for url_key, url_val in okg.urls.iteritems(): print '%-16s %s' % ('\'' + url_key + '\'' + ':', url_val) print '\n%-20s %s' % ('News articles found:', okg.news.total) print '%-20s %s' % ('Blog articles found:', okg.blogs.total) print '%-20s %s' % ('Album reviews found:', okg.reviews.total) print '%-20s %s' % ('Songs found:', okg.songs.total) print '%-20s %s' % ('Audio URLs found:', okg.audio.total) print '%-20s %s' % ('Videos found:', okg.video.total) print '%-20s %s' % ('Images found:', okg.images.total) print '%-20s %s' % ('Biographies found:', okg.biographies.total) else: print 'Artist not found.'
# Uncomment to set the API key explicitly. Otherwise Pyechonest will # look in the ECHO_NEST_API_KEY environment variable for the key. #from pyechonest import config #config.ECHO_NEST_API_KEY='YOUR API KEY' from pyechonest import artist buckets_options = [['id:7digital'], ['id:playme'], ['id:musicbrainz'], ['id:7digital', 'id:playme', 'id:musicbrainz']] for bucket_set in buckets_options: te_results = artist.search(name='The Ernies', buckets=bucket_set, limit=True) if te_results: print 'Found %s in %s.' % (te_results[0].name, bucket_set) else: print 'Not found in %s.' % (bucket_set,)
def get_artist_id(artist_name): result = artist.search(name=artist_name) if not result: return False return result[0].id
# Uncomment to set the API key explicitly. Otherwise Pyechonest will # look in the ECHO_NEST_API_KEY environment variable for the key. #from pyechonest import config #config.ECHO_NEST_API_KEY='YOUR API KEY' from pyechonest import artist kc_results = artist.search(name='Kid Cudi') if kc_results: kc = kc_results[0] for a_song in kc.get_songs(results=20, start=30): print '%s (Echo Nest ID: %s) by %s' % (a_song.title, a_song.id, a_song.artist_name) else: print 'Artist not found.'
def add(*args): print args def main(): print "bye" if __name__ == '__main__': main() """ #! usr/bin/env/ python from pyechonest import config config.ECHO_NEST_API_KEY="CFD8LTBTFOEH9E3IG" from pyechonest import artist import webbrowser weezer_results = artist.search(name='lady gaga') weezer = weezer_results[0] weezer_blogs = weezer.blogs print 'Blogs about weezer:', [blog.get('url') for blog in weezer_blogs] from facepy import GraphAPI ACC_TOK='CAACEdEose0cBAGnJGkTWsCWrugi4m4JLDFENesQJznaQyyqzB4zCjWViZAbwDRGimMZCmTHfqnZCAJPsFOxnrZAoQc2gTZCyIZCJIrxG1OBEWIAZBzc6LwXOJYoKuCZALFiZC0kOC5l8ZBEtuOYAnlq9cDZAqWcMLvWrNqnDnfjwnxZBGuakrOuZAHZAteN0cnpiiWT9gWTJv9T2ZBSCAZDZD' gr=GraphAPI(ACC_TOK) gr.post(path=me/feed,message='Forca Barca(finally updates by python :p') """ import web from facepy import GraphAPI from urlparse import parse_qs
from pyechonest import config config.ECHO_NEST_API_KEY = "ZQXJHQWPS4UO54AUV" from pyechonest import artist anu_result = artist.search(name = 'Anu Malik') anu = anu_result[0] anu_blogs = anu.blogs print 'Blogs about anu:', [blog.get('url') for blog in anu_blogs]
def secondIter(artistlist): for i in artistlist: ar = artist.search(name=a) ar = ar[0] returnSongs(ar)