def create_track_file_from_song_noartist(maindir,song,mbconnect=None): """ After getting the artist, get tracks from a song, choose the first one and calls for its creation. We assume we already have a song. We can have a connection to musicbrainz as an option. This function should create only one file! GOAL: handles some errors. INPUT maindir - MillionSongDataset root directory song - pyechonest song object for that track mbconnect - open musicbrainz pg connection RETURN true if a song file is created, false otherwise """ # CLOSED CREATION? if CREATION_CLOSED: return False # get that artist while True: try: artist = artistEN.Artist(song.artist_id) break except KeyboardInterrupt: close_creation() raise except pyechonest.util.EchoNestAPIError,e: print ('MAJOR ERROR, wrong artist id?') print e # means the ID does not exist return False except Exception,e: print type(e),':',e print ('at time',time.ctime(),'in create_track_files_from_song_noartist, sid=',song.id,'(we wait',SLEEPTIME,'seconds) (pid='+str(os.getpid())+')') time.sleep(SLEEPTIME) continue
def get_key_tempo(filename): h5 = GETTERS.open_h5_file_read(filename) tempo = GETTERS.get_tempo(h5) key = GETTERS.get_key(h5) ar = GETTERS.get_artist_name(h5) title = GETTERS.get_title(h5) st = "" terms = None try: a = artist.Artist(str(ar)) terms = a.get_terms() time.sleep(.12) except EchoNestIOError as e: print "echonestIOerror" except EchoNestAPIError as e: if e.code == 3: time.sleep(1) elif e.code == 5: print "code is 5" else: print "error.." if terms: print terms[0]['name'] with open('points.csv', 'a') as fp: a = csv.writer(fp, delimiter=',') a.writerow([tempo, key, ar, title, terms[0]['name']]) h5.close()
def add_items_to_billboard_df_artist_count(billboard_df_artist_count, items_to_add): billboard_df_temp = pd.DataFrame.copy(billboard_df_artist_count) for item in items_to_add: billboard_df_temp[item] = "" count_access_api = 0 for artist_name in billboard_df_artist_count["Artist(s)"]: count_access_api += 1 if count_access_api >= 120: time.sleep(60) count_access_api = 0 try: current_artist = artist.Artist(artist_name) for i, item in enumerate(items_to_add): count_access_api += 1 if count_access_api >= 120: time.sleep(60) count_access_api = 0 index_artist = billboard_df_artist_count[billboard_df_artist_count["Artist(s)"] == artist_name].index.tolist()[0] billboard_df_temp.loc[index_artist, item] = getattr(current_artist, item) except: print artist_name continue billboard_df_temp.to_csv('CSV_data/billboard_df_artist_count_with_additional_items.csv', sep=',') return billboard_df_temp
def getArtistsByLocation(location, appID="Spoons-Tunes", maxNum=1): """ Given location, returns list of nearby bands playing Keyword arguments: location -- in format "city,state", "city,country", "lat,lon", "ip address" maxNum -- maximum number of artists to return """ #TODO: assert location is a valid location location.replace(" ", "+") import urllib2 response = urllib2.urlopen( "http://api.bandsintown.com/events/search.json?location=%s&app_id=%s" % (location, appID)) html = response.read() ctr = 0 artistList = [] while (html.find("\"name\":\"") != -1) and ctr < maxNum: curIndex = html.find("\"name\":\"") html = html[curIndex + 8:] endIndex = html.find("\"") str = html[:endIndex] try: artist.Artist(str) ctr += 1 artistList.append(str) except: continue return artistList
def getArtistImage(artistString): try: artistObject= artist.Artist(urllib.unquote(artistString).decode('utf8')) images=artistObject.get_images() l=len(images) k=random.randint(0,l-1) return images[k]['url'] except: return 'http://images.wikia.com/theslenderman/images/c/ce/Question-mark-face.jpg'
def __init__( self, name, songsterr_id=None, rdio_id=None, ): self.name = name self.echonest_id = en_artist.Artist(name).id self.songsterr_id = songsterr_id self.rdio_id = rdio_id
def get_artist_song_from_names(artistname, songtitle): """ Get an artist and a song from their artist name and title, return the two: artist,song or None,None if problem """ while True: try: songs = songEN.search(artist=artistname, title=songtitle, results=1, buckets=[ 'artist_familiarity', 'artist_hotttnesss', 'artist_location', 'tracks', 'id:musicbrainz', 'id:7digital', 'id:playme' ]) break except (KeyboardInterrupt, NameError, TypeError): close_creation() raise except (Exception, e): print(type(e), ':', e) print('at time', time.ctime(), 'in get_artist_song_from_names (we wait', SLEEPTIME, 'seconds)') time.sleep(SLEEPTIME) continue # sanity checks if len(songs) == 0: print('no song found for:', artistname, '(', songtitle, ')') return None, None if CREATION_CLOSED: return None, None # get artist song = songs[0] while True: try: artist = artistEN.Artist(song.artist_id) break except KeyboardInterrupt: close_creation() raise except (pyechonest.util.EchoNestAPIError, e): print('MAJOR ERROR, wrong artist id?', song.artist_id) print(e) # means the ID does not exist return None, None except (Exception, e): print(type(e), ':', e) print('at time', time.ctime(), 'in get_artist_song_from_names, aid=', song.artist_id, '(we wait', SLEEPTIME, 'seconds)') time.sleep(SLEEPTIME) continue # done return artist, song
def recursiveGraph(G, tempName, depth): if depth == 0: return bk = artist.Artist(tempName) G.add_node(bk.name) for similar_artist in bk.similar: G.add_node(similar_artist.name) G.add_edge(similar_artist.name, bk.name) recursiveGraph(G, similar_artist.name, depth - 1)
def lookup_seeds(seed_artist_names): seed_ids = [] for artist_name in seed_artist_names: try: seed_ids.append("%s" % (artist.Artist(artist_name).id, )) except Exception: logger.info('artist "%s" not found.' % (artist_name, )) # we could try to do full artist search here # and let them choose the right artist logger.info('seed_ids: %s' % (seed_ids, )) return seed_ids
def getSimilarArtists(artistString): similar_artist_list=[] try: artistObject= artist.Artist(urllib.unquote(artistString).decode('utf8')) for similar_artist in artistObject.similar: similar_artist_list.append(similar_artist.name) jsonOutput=json.dumps(similar_artist_list) return jsonOutput except: similar_artist_list.append('No Similar Artists Found') jsonOutput=json.dumps(similar_artist_list) return jsonOutput
def relatedArtist( artist_id ): listArtist = [] ##try: bk = artist.Artist( artist_id ) ##except WebServiceError as exc: ## print("Something went wrong with the request: %s" % exc) ##else: for similar_artist in bk.similar: listArtist.append( ( similar_artist.name , similar_artist.id , "similar" ) ) return listArtist
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 store_en_info(enmfp, url): u = urlparse(url) s = song.identify(code=enmfp)[0] #TODO deal with more than one match a = artist.Artist(id=s.artist_id) #TODO find out if we can get release info too redis_client.set('en_songs:%s' % s.id, json.dumps(s.__dict__)) redis_client.set('en_artists:%s' % a.id, json.dumps(a.__dict__)) redis_client.set('en_enmfp_by_path:%s' % u.path, enmfp) redis_client.set('en_song_ids_by_enmfp:%s' % enmfp, s.id) # Only lookup/store artist terms if we dont have yet key = 'en_artist_terms:%s' % a.id if not redis_client.get(key): redis_client.set(key, json.dumps(a.terms)) return {'song': s, 'artist': a}
def store_en_info(url): u = urlparse(url) # Calc or fetch enmfp from cache sha = sha256_for_file(u.path) key = 'en_enmfp_by_sha:%s' % sha enmfp = redis_client.get(key) if not enmfp: enmfp = get_enmfp_json_from_mp3(url) enmfp = redis_client.set(key, enmfp) # Do we have this song result in redis? en_song_id = redis_client.get('en_song_ids_by_enmfp:%s' % enmfp) if en_song_id: return {'result': 'exists'} # we've already handled this song, so dont do anyhting for it # Still here? Go to EN API for the song and artist info and store it s_results = song.identify(code=enmfp) if len(s_results) == 0: error = "*** ID FAIL %s with code %s" % (url, enmfp) print error return { 'result': 'error', 'error': error} else: s = s_results[0] print "ID %s" % (url) a = artist.Artist(id=s.artist_id) #TODO get release info somehow (via en track query then rosetta lookup?) # Add artist terms to artist obj for json dump ao = a.__dict__ ao['terms'] = a.terms redis_client.set('en_songs:%s' % s.id, json.dumps(s.__dict__)) redis_client.set('en_artists:%s' % a.id, json.dumps(ao)) redis_client.set('en_enmfp_by_path:%s' % u.path, enmfp) redis_client.set('en_song_ids_by_enmfp:%s' % enmfp, s.id) # Only lookup/store artist terms if we dont have yet key = 'en_artist_terms:%s' % a.id if not redis_client.get(key): redis_client.set(key, json.dumps(a.terms)) return {'result': 'ok', 'song': s, 'artist': a, 'enmfp': enmfp}
def EchonestCrawler(path, queue): threadCrawlerLock.acquire(0) filename = os.path.basename(path) filename = os.path.splitext(filename)[0].lower() keywords = filename.split(' - ')[0] keywords = keywords.split('pres')[0] keywords = keywords.split('feat')[0] keywords = keywords.split('with')[0] keywords = keywords.split('and')[0] keywords = u'%s' % (keywords) echonest_config.ECHO_NEST_API_KEY = '3NUCRNQMMTWBDJCSL' try: bk = echonest_artist.Artist(keywords) except Exception: queue.put(None) return info = Struct() info.artist = bk.name info.similar = list() for v in bk.similar: info.similar.append(v.name) queue.put(info) collected = gc.collect()
def getTrackID(artist_name, track_name): """ sometimes plaintext queries are not accurate; need specifically the trackID, artistID, or md5 hash; improvements can be made here for more accurate queries on particularly obscure artists; otherwise, still performs well """ # search for track and artists with appropriate parameters results = song.search(artist=artist_name, title=track_name, buckets=['id:spotify', 'tracks'], limit=True, results=1) # check that results returned something if (len(results) == 0): return 0 # how to get the proper track id; hackishly track_id = results[0].get_tracks('spotify')[0]['id'] artist_id = results[0].artist_id artist_name = artist.Artist(artist_id) artist_terms = artist_name.terms return (track_id, artist_terms)
def MetaCrawler(path, queue): threadCrawlerLock.acquire(0) info = Struct() info.google = Struct() info.discogs = Struct(idx=None, name=None, aliases=None, namevariations=None, realname=None, members=None, releases=None) info.echonest = Struct(artist=None, similar=None) info.gracenote = Struct() filename = os.path.basename(path) filename = os.path.splitext(filename)[0].lower() keywords = filename.split(' - ')[0] keywords = keywords.split('pres')[0] keywords = keywords.split('feat')[0] keywords = keywords.split('with')[0] keywords = keywords.split('and')[0] keywords = u'%s' % (keywords) echonest_config.ECHO_NEST_API_KEY = '3NUCRNQMMTWBDJCSL' try: bk = echonest_artist.Artist(keywords) info.echonest.artist = bk.name info.echonest.similar = list() for v in bk.similar: info.echonest.similar.append(v.name) except Exception: pass queue.put(info) discogs.user_agent = 'muteklab/1.0 +http://www.muteklab.com' artist = discogs.Artist(keywords) try: keys = artist.data.keys() if u'id' in keys: info.discogs.idx = artist.data[u'id'] if u'name' in keys: info.discogs.name = artist.data[u'name'] if u'aliases' in keys: info.discogs.aliases = artist.data[u'aliases'] if u'namevariations' in keys: info.discogs.namevariations = artist.data[u'namevariations'] if u'realname' in keys: info.discogs.realname = artist.data[u'realname'] if u'members' in keys: info.discogs.members = artist.data[u'members'] except Exception: pass queue.put(info) # info.discogs.images = list() info.discogs.releases = list() try: # random.randrange(0, len(artist.releases)) # randomIdx = random.sample(range(len(artist.releases)), len(artist.releases)) # for i in randomIdx: for i in range(len(artist.releases)): release = artist.releases[i] data = '%s %s' % (release.data['year'], release.data['title']) info.discogs.releases.append(data) # if 'images' in release.data.keys(): # # uri = release.data['images'][0]['uri'] # uri = release.data['images'][0]['uri150'] # artwork = urllib.urlopen(uri).read() # info.discogs.images.append(artwork) queue.put(info) except Exception: pass queue.put(info) gc.collect()
#!/usr/bin/env python from pyechonest import config config.ECHO_NEST_API_KEY = "ODF7R3CSWAICT8V7K" from pyechonest import artist bk = artist.Artist('bikini kill') print "Artists similar to: %s:" % (bk.name, ) for similar_artist in bk.similar: print "\t%s" % (similar_artist.name, )
def getSimilarArtists(name, limit): print "::getSimilarArtists" curArtist = artist.Artist(name) artists = curArtist.get_similar(limit) print artists return artists
print type(e), ':', e print 'at time', time.ctime( ), 'in get_artist_song_from_names (we wait', SLEEPTIME, 'seconds)' time.sleep(SLEEPTIME) continue # sanity checks if len(songs) == 0: print 'no song found for:', artistname, '(', songtitle, ')' return None, None if CREATION_CLOSED: return None, None # get artist song = songs[0] while True: try: artist = artistEN.Artist(song.artist_id) break except KeyboardInterrupt: close_creation() raise except pyechonest.util.EchoNestAPIError, e: print 'MAJOR ERROR, wrong artist id?', song.artist_id print e # means the ID does not exist return None, None except Exception, e: print type(e), ':', e print 'at time', time.ctime( ), 'in get_artist_song_from_names, aid=', song.artist_id, '(we wait', SLEEPTIME, 'seconds)' time.sleep(SLEEPTIME) continue # done
# 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 ra_search_results = artist.search(name='Rise Against') if ra_search_results: ra_by_search = ra_search_results[0] print 'Found "%s" (%s) by artist.search()' % (ra_by_search.name, ra_by_search.id) ra_by_id = artist.Artist('ARZWK2R1187B98F09F') if (ra_by_id == ra_by_search): print 'Found "%s" (%s) by ID initialization' % (ra_by_id.name, ra_by_id.id) ra_by_name = artist.Artist('Rise Against') if (ra_by_name == ra_by_search): print 'Found "%s" (%s) by name initialization' % (ra_by_name.name, ra_by_name.id) else: print 'Artist not found by artist.search()'
def all_artist(artist): art = pyartist.Artist(artist)
def coTags(b, c): """ Find overlap in tags given two Artists Input: two valid artist names Output: list of tags that apply to both ## updated to be a similarity score """ print "Getting tags for", b, "and", c # get the artist tags try: artist1 = a.Artist(b) except: print "Artist", b, "does not exist!" return try: artist2 = a.Artist(c) except: print "Artist", c, "does not exist!" # get the terms for the artist a1_terms = artist1.terms a2_terms = artist2.terms # overlap of the names a1_names = [x['name'] for x in a1_terms] print "\n", b, a1_names a2_names = [x['name'] for x in a2_terms] print "\n", c, a2_names a3_names = intersect(a1_names, a2_names) if not a3_names: print "No coTags!" return print a3_names # pre-process values for algorithm dict1 = {} dict2 = {} # print "\nTerms for", artist1.name for x in a1_terms: if x['name'] in a3_names: dict1[x['name']] = [x['frequency'], x['weight']] print x['name'], ",", x['frequency'], ",", x['weight'] # print "\nTerms for", artist2.name for x in a2_terms: if x['name'] in a3_names: dict2[x['name']] = [x['frequency'], x['weight']] print x['name'], ",", x['frequency'], ",", x['weight'] # Trieur Algorithm freq_ratios = [] weight_ratios = [] for x in a3_names: freq_ratios.append(dict1[x][0] / dict2[x][0]) weight_ratios.append(dict1[x][1] / dict2[x][1]) print freq_ratios print weight_ratios # coefficient weights alpha, beta = 1, 1 num = len(a3_names) print num TG = (sum(freq_ratios) * alpha) / num + (sum(weight_ratios) * beta) / num print TG / 2
def echo_nest_update(): """ Updates the json with all EchoNest data available for this song ('Echo Nest API Error 5: bucket - Invalid parameter: bucket "id" is not one of "audio", "biographies", "blogs", "doc_counts", "familiarity", "familiarity_rank", "genre", "hotttnesss", "hotttnesss_rank", "discovery", "discovery_rank", "images", "artist_location", "news", "reviews", "songs", "terms", "urls", "video", "years_active", "id:7digital-US", "id:7digital-AU", "id:7digital-UK", "id:facebook", "id:fma", "id:emi_bluenote", "id:emi_artists", "id:twitter", "id:spotify-WW", "id:seatwave", "id:lyricfind-US", "id:jambase", "id:musixmatch-WW", "id:rdio-US", "id:rdio-AT", "id:rdio-AU", "id:rdio-BR", "id:rdio-CA", "id:rdio-CH", "id:rdio-DE", "id:rdio-DK", "id:rdio-ES", "id:rdio-FI", "id:rdio-FR", "id:rdio-IE", "id:rdio-IT", "id:rdio-NL", "id:rdio-NO", "id:rdio-NZ", "id:rdio-PT", "id:rdio-SE", "id:emi_electrospective", "id:rdio-EE", "id:rdio-LT", "id:rdio-LV", "id:rdio-IS", "id:rdio-BE", "id:rdio-MX", "id:seatgeek", "id:rdio-GB", "id:rdio-CZ", "id:rdio-CO", "id:rdio-PL", "id:rdio-MY", "id:rdio-HK", "id:rdio-CL", "id:twitter_numeric", "id:7digital-ES", "id:openaura", "id:spotify", "id:spotify-WW", "id:tumblr", or "id:<CATALOG ID>" """ from pyechonest import config config.ECHO_NEST_API_KEY = ECHO_NEST_API_KEY config.CALL_TIMEOUT = 60 while True: json_data = yield if json_data == STOP: break if json_data.get('echo_nest', ''): continue json_data['echo_nest'] = {} track_title = '' artist_name = '' if json_data.get('lastfm', ''): track_title = json_data['lastfm'].get('track', '') artist_name = json_data['lastfm'].get('artist', '') if not track_title: track_title = json_data['id3'].get('title', '') if not artist_name: artist_name = json_data['id3'].get('artist', '') a = None try: if artist_name: a = artist.Artist(artist_name, buckets=[ 'biographies', 'blogs', 'doc_counts', 'familiarity', 'hotttnesss', 'genre', 'artist_location', 'news', 'reviews', 'urls', 'years_active' ]) json_data['echo_nest']['artist_id'] = a.id time.sleep(1) json_data['echo_nest']['artist'] = a.name time.sleep(1) json_data['echo_nest']['bios'] = a.biographies time.sleep(1) json_data['echo_nest']['blogs'] = a.blogs time.sleep(1) json_data['echo_nest']['doc_counts'] = a.doc_counts time.sleep(1) json_data['echo_nest']['a_familiarity'] = a.familiarity time.sleep(1) json_data['echo_nest']['a_hotttnesss'] = a.hotttnesss time.sleep(1) json_data['echo_nest']['news'] = a.news time.sleep(1) json_data['echo_nest']['reviews'] = a.reviews time.sleep(1) json_data['echo_nest']['urls'] = a.urls time.sleep(1) json_data['echo_nest']['years_active'] = a.years_active time.sleep(1) json_data['echo_nest']['similar'] = [ str(sim.name) for sim in a.get_similar() ] time.sleep(1) except EchoNestException as e: print(e) except EchoNestIOError as e: print(e) except socket.timeout: pass time.sleep(1) if a and track_title: try: results = song.search(artist=a.name, title=track_title, buckets=[ 'audio_summary', 'song_hotttnesss', 'song_discovery' ]) time.sleep(1) except EchoNestException as e: print(e) except EchoNestIOError as e: print(e) except socket.timeout: pass time.sleep(1) if results: json_data['echo_nest']['id'] = results[0].id time.sleep(1) json_data['echo_nest']['summary'] =\ results[0].audio_summary time.sleep(1) json_data['echo_nest']['s_hotttnesss'] =\ results[0].song_hotttnesss time.sleep(1) json_data['echo_nest']['s_discovery'] =\ results[0].song_discovery time.sleep(1) time.sleep(1) tr = None if json_data['echo_nest'].get('id', ''): try: tr = track.track_from_id(json_data['echo_nest']['id']) time.sleep(1) except EchoNestException as e: print(e) except EchoNestIOError as e: print(e) except socket.timeout: pass time.sleep(1) if not tr: continue try: tr.get_analysis() time.sleep(1) json_data['echo_nest']['analysis'] = {} json_data['echo_nest']['analysis']['acousticness'] =\ tr.acousticness json_data['echo_nest']['analysis']['analysis_url'] =\ tr.analysis_url json_data['echo_nest']['analysis']['danceability'] =\ tr.danceability json_data['echo_nest']['analysis']['duration'] =\ tr.duration json_data['echo_nest']['analysis']['energy'] = tr.energy json_data['echo_nest']['analysis']['key'] = tr.key json_data['echo_nest']['analysis']['liveness'] =\ tr.liveness json_data['echo_nest']['analysis']['loudness'] =\ tr.loudness json_data['echo_nest']['analysis']['mode'] = tr.mode json_data['echo_nest']['analysis']['speechiness'] =\ tr.speechiness json_data['echo_nest']['analysis']['tempo'] =\ tr.tempo json_data['echo_nest']['analysis']['time_signature'] =\ tr.time_signature json_data['echo_nest']['analysis']['valence'] = tr.valence json_data['echo_nest']['analysis']['analysis_channels'] =\ tr.analysis_channels json_data['echo_nest']['analysis']['bars'] = tr.bars json_data['echo_nest']['analysis']['beats'] = tr.beats json_data['echo_nest']['analysis']['start_of_fade_out'] =\ tr.start_of_fade_out json_data['echo_nest']['analysis']['end_of_fade_in'] =\ tr.end_of_fade_in json_data['echo_nest']['analysis']['key_confidence'] =\ tr.key_confidence json_data['echo_nest']['analysis']['meta'] = tr.meta json_data['echo_nest']['analysis']['mode_confidence'] =\ tr.mode_confidence json_data['echo_nest']['analysis']['num_samples'] =\ tr.num_samples json_data['echo_nest']['analysis']['sections'] =\ tr.sections json_data['echo_nest']['analysis']['segments'] =\ tr.segments json_data['echo_nest']['analysis']['synchstring'] =\ tr.synchstring json_data['echo_nest']['analysis']['tatums'] =\ tr.tatums json_data['echo_nest']['analysis']['tempo_confidence'] =\ tr.tempo_confidence json_data['echo_nest']['analysis']['sign_confidence'] =\ tr.time_signature_confidence except EchoNestException as e: print(e) except EchoNestIOError as e: print(e) except socket.timeout: pass except Exception as e: print(e) time.sleep(1) if a: try: json_data['echo_nest']['basic_song_list'] =\ ['{} - {}'.format(s.artist_name, s.title) for s in playlist.basic(type='song-radio', artist_id=a.id, song_id=tr.id)] time.sleep(1) except EchoNestException as e: print(e) except EchoNestIOError as e: print(e) except socket.timeout: pass time.sleep(1) try: json_data['echo_nest']['basic_artist_list'] =\ ['{} - {}'.format(s.artist_name, s.title) for s in playlist.basic(artist_id=a.id, song_id=tr.id)] time.sleep(1) except EchoNestException as e: print(e) except EchoNestIOError as e: print(e) except socket.timeout: pass time.sleep(1)
#Don`t forget pip install pyechonest & getting your api! #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:
# 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 song from pyechonest import artist short_unloud_songs = song.search(max_duration=90, max_loudness=-10, start=34, results=10) if short_unloud_songs: artist_ids = [a_song.artist_id for a_song in short_unloud_songs] artists = [artist.Artist(id) for id in set(artist_ids)] for an_artist in artists: biographies = an_artist.get_biographies(results=1) if biographies: print '%-30s %s' % (an_artist.name[0:30], biographies[0]['url']) else: print an_artist.name else: print 'No songs found.'
#! usr/bin/env python # from pyechonest import artist # def getInfo(inArtist): # a = artist.Artist(inArtist) # print "id: " + str(a.id) # print "hotness rating" + str(a.hotttnesss) from pyechonest import artist bk = artist.Artist('CHVRCHES') print "Artists similar to: %s:" % (bk.name, ) for similar_artist in bk.similar: print "\t%s" % (similar_artist.name, )
def getArtistBio(artistString): artistObject= artist.Artist(urllib.unquote(artistString).decode('utf8')) bios=artistObject.get_biographies() return bios[0]['text'].encode('ascii','ignore')
wt += 'valence: ' + str(songOne.audio_summary['valence']) + '\n' wt += 'song_hotttnesss: ' + str(songOne.song_hotttnesss) + '\n' wt += 'song_type: ' for i in songOne.song_type: wt += i + ',' wt += '\n' ''' if accessCnt>=20 : print 'sleep for a min\n' time.sleep(sec) accessCnt=0 ''' artist_id = songOne.artist_id artist_terms = artist.Artist(artist_id).terms accessCnt += 1 print 'accessCnt: ' + str(accessCnt) wt += 'artist_terms: ' for i in artist_terms: wt += i['name'] + ',' wt += '\n' wt = uni(wt) result_file.write(wt) song_artist[songOne.title] = songOne.artist_name last_maxpoint = songOne.song_hotttnesss startpoint += 100 print len(song_artist) #under- not valid code
# 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 playlist, artist tsquare = artist.Artist('Thompson Square') jaldean = artist.Artist('Jason Aldean') afire = artist.Artist('Arcade Fire') a_playlist = playlist.static(type='artist-radio', artist_id=[tsquare.id, jaldean.id, afire.id], results=5) other_playlist = playlist.static(type='artist-radio', artist_id=[tsquare.id, jaldean.id, afire.id], results=5) print 'Songs in one playlist for seed artists %s:' % (', '.join(an_artist.name for an_artist in [tsquare, jaldean, afire]),) for a_song in a_playlist: print '"%s" by %s' % (a_song.title, a_song.artist_name) print '' print 'Songs in another playlist for seed artists %s:' % (', '.join(an_artist.name for an_artist in [tsquare, jaldean, afire]),) for a_song in other_playlist: print '"%s" by %s' % (a_song.title, a_song.artist_name)