def seed_gen(): en = pyen.Pyen(APIKEY) all_songs = Song.objects.all() for song in all_songs: artist = Artist.objects.filter(name=song.artist) if len(artist) == 0: try: print(song.artist) new_artist = Artist(name=song.artist) new_artist.save() response = en.get('artist/profile', name=song.artist, bucket=['genre']) genres = response['artist']['genres'] for genre in genres: existing = Genre.objects.filter(name=genre['name']) if len(existing) == 0: genre_object = Genre(name=genre['name']) genre_object.save() print(genre) else: genre_object = existing[0] new_artist.genres.add(genre_object) new_artist.save() except: continue
def test_bad_api_key(self): en = pyen.Pyen(api_key='BAD_API_KEY') try: response = en.get('artist/profile', name='weezer') self.assertTrue(False, "Should never get here") except pyen.PyenException as e: self.assertTrue(True, "exception raised properly") self.assertTrue(e.code == 1)
def __init__(self): self.cache_path = 'songdata.pkl' self.en = pyen.Pyen() self.load_cache() print 'loaded', len(self.cache), 'items from the cache' atexit.register(self.save_cache) self.original_term_handler = cherrypy.engine.signal_handler.handlers["SIGTERM"] cherrypy.engine.signal_handler.set_handler("SIGTERM", self.on_term)
def test_slow_random_walk(self): en = pyen.Pyen(api_key='YDLX4ITBBQHH3PHU0') # the low rate limit key en.auto_throttle = False artist_name = 'The Beatles' try: for i in range(3): response = en.get('artist/similar', name=artist_name, results=15 ) except pyen.PyenException as e: self.assertTrue(e.http_status == 429)
def en_data(artist): en = pyen.Pyen() try: raw_response = en.get('song/search', artist = artist, bucket=['song_type', 'song_hotttnesss'], #sort=['title-asc'], results=100) except pyen.PyenException, pyen.PyenConfigurationException: data = False msg = "Better off Live couldn't reach the EchoNest database. Please try again later."
def online_music_3d(self, artist_name, track_name, mode="loudness_max"): """ Gets information from The Echo Nest services and creates a 3D model of the input song. Args: artist_name: name of the artist track_name: name of the track mode: musical parameter to be used to create the 3D model options: loudness_max, pitches, timbre """ # Interact with The Echo Nest services self.en = pyen.Pyen(self.EN_API_KEY) print("Searching " + track_name + " by " + artist_name + " on The Echo Nest") audio_segments = self._get_segments(self.en, artist_name, track_name) if audio_segments is not None: audio_features = self._get_features_list(audio_segments, mode) if mode == 'loudness_max': # waveform mode loudness_list = self._process_loudness_list(audio_features) loudness_list = self._rescale_list(loudness_list, 0, self.height_Y) processed_waveform = self.make_waveform_square( loudness_list, self.n_waveform_bars) model_3d = self.make_waveform_3d(processed_waveform, self.height_Z) else: # pitches or timbre new_features = [] for af in audio_features: new_features.append( self._rescale_list(af, self.min_absolute_value, self.height_Z)) new_features = self._increase_model_depth( new_features, self.depth_factor) model_3d = np.array(new_features) # Export 3D model print("Exporting the 3D file") if self.OUTPUT_FOLDER[-1] != '/': self.OUTPUT_FOLDER.append('/') output_filename = self.OUTPUT_FOLDER + artist_name + " - " + track_name + "_" + mode + ".stl" numpy2stl(model_3d, output_filename, scale=self.scale, mask_val=self.mask_val, solid=True)
def __init__(self, api_key = None, cache_dir="~/.remix-cache", trace=False): """ Creates a new remixer Args: api_key: the Echo Nest API key. If not set, look for one in the ECHO_NEST_API_KEY environment variable cache_dir: directory for analysis cache trace: trace salient events """ self._en = pyen.Pyen(api_key) self._trace = trace self._cache_dir = cache_dir self._check_cache_dir() self._trid_cache = self._load_trid_cache()
def seed_genre(artist_name): en = pyen.Pyen(APIKEY) new_artist = Artist(name=artist_name) new_artist.save() try: response = en.get('artist/profile', name=artist_name, bucket=['genre']) genres = response['artist']['genres'] for genre in genres: existing = Genre.objects.filter(name=genre['name']) if len(existing) == 0: genre_object = Genre(name=genre['name']) genre_object.save() print(genre) else: genre_object = existing[0] new_artist.genres.add(genre_object) new_artist.save() except: pass return new_artist
def get_artist_data(cfg, query, n=5): en = pyen.Pyen(api_key=cfg['echonest_api_key']) try: songs = en.get('playlist/static', {'artist': query, 'song_type': 'studio', 'bucket': ['id:rdio-US', 'tracks', 'audio_summary'], 'limit': True, 'results': n})['songs'] except: songs = [] response = [] for s in songs: analysis = get_analysis(s['audio_summary']['analysis_url']) track_id = s['tracks'][0]['foreign_id'].split(':')[-1] value = repetition_score(analysis) response.append( (value, track_id, s['artist_name'], s['title']) ) response = sorted(response) return map(lambda x: {'score': x[0], 'track_id': x[1], 'artist': x[2], 'title': x[3]}, response)
import networkx as nx import matplotlib.pyplot as plt import math ## PyEchonest --------------------------------------------- from pyechonest import config from pyechonest import artist config.ECHO_NEST_API_KEY = "JEXRSXP8AZST5QCNP" ## -------------------------------------------------------- ## PyEn --------------------------------------------------- import pyen en = pyen.Pyen("JEXRSXP8AZST5QCNP") ## -------------------------------------------------------- ## Funciones ---------------------------------------------------## def getArtistByGenre(genre, limit): response = en.get('genre/artists', name=genre, results=limit) listArtist = [] for artist in response['artists']: listArtist.append((artist["name"], artist["id"])) return listArtist def relatedArtist(artist_id):
import pyen import random # this API key has a very low rate limit en = pyen.Pyen(api_key='YDLX4ITBBQHH3PHU0') artist_name = 'The Beatles' for i in xrange(10): response = en.get('artist/similar', name=artist_name) print artist_name for artist in response['artists']: print ' --> ', artist['name'] artist_name = random.choice(response['artists'])['name']
def main(): args = parse_args() log = logging.getLogger('pyladies_api') stream = logging.StreamHandler() log.addHandler(stream) if args.debug: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) # load your config.ini file parent_dir = os.path.dirname(os.path.dirname(__file__)) config_file = os.path.join(parent_dir, "config.ini") config = ConfigParser.ConfigParser() config.read(config_file) # parse out spotify configuration spotify_client_id = config.get('spotify', 'client_id') spotify_client_secret = config.get('spotify', 'client_secret') spotify_token_url = config.get('spotify', 'token_url') # Get an OAuth token from Spotify token = sp.get_spotify_oauth_token(spotify_client_id, spotify_client_secret, spotify_token_url) # get the desired user's list of playlists playlists = sp.get_user_playlists(token, args.username) # parse out the tracks URL for each playlist track_urls = sp.get_playlist_track_urls(playlists, args.username) # request track data from the tracks URLs track_data = sp.get_tracks(track_urls, token) # parse track data into parsed_data and json_data parsed_data, json_data = sp.parse_track_data(track_data) # save the json_data for future use with EchoNest output_file_name = config.get('spotify', 'output_file_name') output_file = os.path.abspath(os.path.realpath(output_file_name)) sp.save_json_data(json_data, output_file) # sort the parsed_data of tracks into their appropriate buckets sorted_data = sp.sort_track_data(parsed_data) # create a bar chart with the sorted_data! sp.create_bar_chart(sorted_data) # EchoNest API # Grab your EchoNest API key from your config echonest_api_key = config.get('echonest', 'api_key') # Grab where you saved the track data from Spotify output_file_name = config.get('echonest', 'output_file_name') json_input = config.get('spotify', 'output_file_name') # instantiate the EchoNest APY en = pyen.Pyen(echonest_api_key) # Open the track data we saved from Spotify playlist_json = json.load(open(json_input, "r")) # Deduplicate the artists unique_artists = ec.deduplicate_artists(playlist_json) # Get our artist information artists = ec.get_artists_information(en, unique_artists) # Create a JSON-like object with our artist information json_output = ec.create_json(artists) # Define where the JSON will be saved based off of our config output_file = os.path.abspath(os.path.realpath(output_file_name)) # Save the data into a JSON file ec.save_json(json_output, output_file) ### # GitHub API ### # Load GitHub configuration github_oauth = config.get('github', 'oauth') # Grab the file that we saved with echonest earlier artist_data_file = config.get('echonest', 'output_file_name') # load this file so we can read it artist_json = json.load(open(artist_data_file, 'r')) # Create a GeoJSON-like object with our artist information geojson_output = gh.create_geojson(artist_json) # Either log into GitHub if you do have a GitHub account if github_oauth: try: gh_auth = gh.login_github(github_oauth) except gh.GithubError: gh_auth = None # Or if no account, then set the auth to None else: gh_auth = None # POST the GeoJSON to GitHub gist_url = gh.post_gist_github(geojson_output, gh_auth, args.gist_desc) # Open the default system browser to the gist URL that we just created webbrowser.open(gist_url)
def open_pyen(): flask.g.pyen = pyen.Pyen()
def setUp(self): self.en = pyen.Pyen()
def initialize(): return pyen.Pyen(secrets.ECHO_NEST_KEY)
def __init__(self, apikey): self.en = pyen.Pyen(apikey)
QHBoxLayout, QSlider, QLabel, QLineEdit, QVBoxLayout, QApplication) from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt from Genres import * ###If not working, change the username! ###We need to ask for username! # Set variables specific to our application. os.environ['SPOTIPY_CLIENT_ID'] = '6abdfbaa139448b2b20bdbc8c85e6316' os.environ['SPOTIPY_CLIENT_SECRET'] = 'dcc60e1288414f9e98dde464eea03d9b' os.environ['SPOTIPY_REDIRECT_URI'] = 'http://google.ca' # Initialize Echonest object. en = pyen.Pyen('0QZ2JW9IHKZQ9BMKI') # Set scope of application, see Spotify docs for info on scopes. scope = 'playlist-modify-public playlist-modify-private user-library-modify user-library-read' #Define out example class, inherits much of itself from QWidget module class Example(QWidget): #Inherits parent class def __init__(self): super().__init__() #Initializes the UI upon instantiation self.initUI() #Method to make the UI much of it created from QTStudio and converted into usable python def initUI(self):
def test_artist_sims_over_ssl(self): en = pyen.Pyen() en.prefix = 'https://developer.echonest.com/api/v4/' response = en.get('artist/similar', name = 'weezer') self.assertTrue("artists" in response) self.assertTrue(len(response['artists']) >= 15)
def _get_en(): global en if en == None: en = pyen.Pyen() en.trace = False return en
def find_track_id(songs, artist, track): return None #make sure there's always two songs in queue #by polling for change of currently playing #song every second. def update_playlist(session_id): sleep(1) for song in playlist_iter(session_id): while songs_in_queue() >= 3: sleep(1) add_song(song) en = pyen.Pyen("TANPJV5OAIXMBC5TR") if raw_input("Genre or artist radio? ").lower() == "artist": session_id = en.get('playlist/dynamic/create', artist=get_seed("artist"), bucket=["id:spotify", "tracks"], type='artist-radio')['session_id'] else: session_id = en.get('playlist/dynamic/create', genre=get_seed("genre"), bucket=["id:spotify", "tracks"], type='genre-radio')['session_id'] clear_queue() #begin with 1 songs in queue. add_song(playlist_get_next(session_id)) set_print_mode()
def main(): args = parse_args() # load your config.ini file parent_dir = os.path.dirname(os.path.dirname(__file__)) config_file = os.path.join(parent_dir, "config.ini") config = ConfigParser.ConfigParser() config.read(config_file) # parse out spotify configuration spotify_client_id = config.get('spotify', 'client_id') spotify_client_secret = config.get('spotify', 'client_secret') spotify_token_url = config.get('spotify', 'token_url') # Get an OAuth token from Spotify token = sp.get_spotify_oauth_token(spotify_client_id, spotify_client_secret, spotify_token_url) # get the desired user's list of playlists playlists = sp.get_user_playlists(token, args.username) # parse out the tracks URL for each playlist track_urls = sp.get_playlist_track_urls(playlists, args.username) # request track data from the tracks URLs track_data = sp.get_tracks(track_urls, token) # parse track data into parsed_data and json_data parsed_data, json_data = sp.parse_track_data(track_data) # save the json_data for future use with EchoNest output_file_name = config.get('spotify', 'output_file_name') output_file = os.path.abspath(os.path.realpath(output_file_name)) sp.save_json_data(json_data, output_file) # sort the parsed_data of tracks into their appropriate buckets sorted_data = sp.sort_track_data(parsed_data) # create a bar chart with the sorted_data! sp.create_bar_chart(sorted_data) # EchoNest API # Grab your EchoNest API key from your config echonest_api_key = config.get('echonest', 'api_key') # Grab where you saved the track data from Spotify output_file_name = config.get('echonest', 'output_file_name') json_input = config.get('spotify', 'output_file_name') # instantiate the EchoNest APY en = pyen.Pyen(echonest_api_key) # Open the track data we saved from Spotify playlist_json = json.load(open(json_input, "r")) # Deduplicate the artists unique_artists = ec.deduplicate_artists(playlist_json) # Get our artist information artists = ec.get_artists_information(en, unique_artists) # Create a JSON-like object with our artist information json_output = ec.create_json(artists) # Define where the JSON will be saved based off of our config output_file = os.path.abspath(os.path.realpath(output_file_name)) # Save the data into a JSON file ec.save_json(json_output, output_file)
import pyen from pyen import PyenException en = pyen.Pyen("KO5QUBGMUVJZA0PFA") k = 0 for fileNum in range(40, 41): with open("../data/chunks/file" + str(fileNum)) as catalogIds: print "../data/chunks/file" + str(fileNum) for line in catalogIds: try: catalogId = line.strip() uCatalog = en.get('tasteprofile/read', format='json', id=line.strip()) uCatalogLength = len(uCatalog['catalog']['items']) print uCatalogLength print "user " + str(k) for i in range(uCatalogLength): print "song " + str(i) songId = uCatalog['catalog']['items'][i]['song_id'] if ( u'song_id' in uCatalog['catalog']['items'][i].keys()) else None songName = uCatalog['catalog']['items'][i]['song_name'] if ( u'song_name' in uCatalog['catalog']['items'][i].keys()) else None artistName = uCatalog['catalog']['items'][i][ 'artist_name'] if (u'artist_name' in uCatalog['catalog']['items'] [i].keys()) else None playCount = uCatalog['catalog']['items'][i][ 'play_count'] if (u'play_count' in uCatalog['catalog']
from __future__ import print_function from alchemyapi import AlchemyAPI import json import pyen __author__ = 'Athithyaa' demo_text = 'Yesterday dumb Bob destroyed my fancy iPhone in beautiful Denver, Colorado. I guess I will have to head over to the Apple Store and buy a new one.' alchemyapi = AlchemyAPI() response = alchemyapi.sentiment('text', demo_text) if response['status'] == 'OK': print('## Response Object ##') print('Score: ', response['docSentiment']['score']) print('Type: ', response['docSentiment']['type']) else: print('Error in entity extraction call: ', response['statusInfo']) en = pyen.Pyen("NLZFOCISYFUJULXXJ") responseEcho = en.get('song/search', mood='happy', results='20', max_liveness='0.7', min_liveness='0.4') print(' ## Response Echo') print(responseEcho)
import pyen import sys import time en = pyen.Pyen() en.trace = False def wait_for_analysis(id): while True: response = en.get('track/profile', id=id, bucket=['audio_summary']) if response['track']['status'] <> 'pending': break time.sleep(1) for k, v in response['track']['audio_summary'].items(): print "%32.32s %s" % (k, str(v)) if len(sys.argv) > 2: mp3 = sys.argv[1] type = sys.argv[2] f = open(mp3, 'rb') response = en.post('track/upload', track=f, filetype=type) trid = response['track']['id'] print 'track id is', trid wait_for_analysis(trid) else: print "usage: python track_upload.py path-audio audio-type"
import sys, soundcloud, pyen #Configuration pyen_key = "8GDKECFTIJHEADTWC" #echonest client_id = "53188e4558d06691aac3cf57ef3a7cd7" #soundcloud en = pyen.Pyen(pyen_key) client = soundcloud.Client(client_id=client_id) def aukfetch(root_track, root_artist=None): related_dict = {} # response = en.get('song/search', artist=root_artist, title=root_track, bucket=['audio_summary'], results=1) # for song in response['songs']: # root_duration = song["audio_summary"]['duration'] # #print root_duration # root_artist = song["artist_name"] # root_track = song["title"] # #handle exceptions for license # print "root %-32.32s %s" % (root_artist, root_track) # print sc_streamurl(root_track, root_artist, root_duration) response = en.get('playlist/static', artist=root_artist, type='artist-radio', results=10) for i, new_song in enumerate(response['songs']): templist = [] response2 = en.get('song/search', artist=new_song['artist_name'],
import pyen import simplejson as json import time total_artists = 30 GETTY_ENABLED_ECHO_NEST_API_KEY = 'XXXX' en = pyen.Pyen(GETTY_ENABLED_ECHO_NEST_API_KEY) response = en.get('artist/top_hottt', results=total_artists) artists = response['artists'] for i, artist in enumerate(artists): print i, len(artists), artist['name'] start = time.time() response = en.get('artist/images', id=artist['id'], license='getty') images = response['images'] artist['images'] = images artist['rank'] = i out = open('images.js', 'w') js = json.dumps(artists) print >> out, js out.close()
import urllib2 import pyen from threading import Thread import json from flask import Flask, jsonify, request from random import sample import time app = Flask(__name__) en = pyen.Pyen("YZZS9XI0IMOLQRKQ6") ARTIST_QUALIFIER = 'terms' # genres N_QUALIFIERS = 5 QUALIFIERS_MAX = 3 PARAMS_RANGE = 0.2 N_THREADS = 32 ARTIST_SAMPLE_SIZE = 15 SIMILAR_ARTIST_RETURN = 7 """ Author: Kristine Romero """ def get_song_frequency(song_list): song_frequency = {} for song in song_list: if song in song_frequency: song_frequency[song] += 1 else: song_frequency[song] = 1
def main(): args = parse_args() if args.debug: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) # Config Shit parent_dir = os.path.dirname(os.path.dirname(__file__)) config_file = os.path.join(parent_dir, "config.ini") config = ConfigParser.ConfigParser() config.read(config_file) echonest_api_key = config.get('echonest', 'api_key') spotify_client_id = config.get('spotify', 'client_id') spotify_client_secret = config.get('spotify', 'client_secret') spotify_token_url = config.get('spotify', 'token_url') github_oauth = config.get('github', 'oauth') artist_data_file = config.get('echonest', 'output_file_name') output_file_name = config.get('echonest', 'output_file_name') json_input = config.get('spotify', 'output_file_name') artist_json = json.load(open(artist_data_file, 'r')) # Spotify API log.debug("Getting a Spotify OAuth Token with your client ID") token = sp.get_spotify_oauth_token(spotify_client_id, spotify_client_secret, spotify_token_url) log.debug("Getting public playlists for {0}".format(args.spotify_user)) playlists = sp.get_user_playlists(token, args.spotify_user) log.debug("Parsing out track URLs from each playlist") track_urls = sp.get_playlist_track_urls(playlists, args.spotify_user) log.debug("Parsed tracks from {0} playlists.".format(len(track_urls))) log.debug("Fetching track data for each track URL.") track_data = sp.get_tracks(track_urls, token) log.debug("Received track data on {0} playlists.".format(len(track_data))) log.debug("Parsing track data, and creating & saving a JSON file.") parsed_data, json_data = sp.parse_track_data(track_data) output_file_name = config.get('spotify', 'output_file_name') output_file = os.path.abspath(os.path.realpath(output_file_name)) sp.save_json_data(json_data, output_file) log.debug("Saved the JSON file at: '{0}'".format(output_file)) log.debug("Sorting parsed track data.") sorted_data = sp.sort_track_data(parsed_data) log.debug("Attempting to create an awesome bar chart...") sp.create_bar_chart(sorted_data) current_dir = os.path.abspath(os.path.dirname(__file__)) log.debug("Chart saved as 'Music Timeline.png' in '{0}'.".format( current_dir)) log.debug("Finished getting playlists from Spotify!") # EchoNest API en = pyen.Pyen(echonest_api_key) playlist_json = json.load(open(json_input, "r")) unique_artists = ec.deduplicate_artists(playlist_json) log.debug("Fetching artist information for {0} artists.".format( len(unique_artists))) log.debug("Perhaps go get some coffee, or a have a bathroom break," "this may take a while depending on how many artists " "there are :D.") artists = ec.get_artists_information(en, unique_artists) log.debug("Creating JSON output of artist information.") json_output = ec.create_json(artists) output_file = os.path.abspath(os.path.realpath(output_file_name)) log.debug("Saving JSON output to {0}.".format(output_file)) ec.save_json(json_output, output_file) # GitHub API log.debug("Creating a GeoJSON file with artist info from {0}".format( artist_data_file)) geojson_file = gh.create_geojson(artist_json) if github_oauth: log.debug("Logging you into GitHub...") try: gh_auth = gh.login_github(github_oauth) log.debug("Successfully logged into GitHub! \n" "Posting the gist to your Account.") except gh.GithubError: gh_auth = None log.info("Could not log you in. Will post your Gist anonymously.") else: gh_auth = None gist_url = gh.post_gist_github(geojson_file, gh_auth, args.gist_desc) log.info("Your gist has been posted! Navigating you to: {0}".format( gist_url)) webbrowser.open(gist_url)
import pyen from spotipy import client, util, oauth2 import numpy import json import sys, random, os nest_key = os.environ['ECHONEST_KEY'] nest = pyen.Pyen(nest_key) steve_spotify_id = '1210159879' PLAYLIST_IDS = { 'fall': '4wm4J4d2cKeTTCJ4Mzz06M', 'winter': '7EUoqdUjR91tMmp41nw7Y4', 'spring': '0rmr2dJ3fuudkrXyIXZgIZ', 'summer': '3mpSb7dwheLtB6QdvIBV2m', 'rainy': '2u7t4X9wA2B493qQgR47aW' } SONG_DATA_FIELDS = { 'danceability', 'energy', 'loudness', 'mode', 'key', 'tempo', 'valence' } use_cache = True """FILE IO""" # Load cached songs def load_cache(): song_cache = {}