def recommend_artists(request, artist_name = ""):
    songs = []
    track = []
    if request.method == "POST":
        artist_name=request.POST.get('name')
        token = oauth2.SpotifyClientCredentials(client_id=client_id,client_secret=client_secret)
        access_token = token.get_access_token()
        get_artist_details_url = "https://api.spotify.com/v1/search?q={}&type=artist&access_token={}"
        artist_response = requests.get(get_artist_details_url.format(artist_name,access_token)).json()
        artist_id = artist_response['artists']['items'][0]['id']
        get_recommend_url = "https://api.spotify.com/v1/recommendations?seed_artists={}&access_token={}"
        artist_response = requests.get(get_recommend_url.format(artist_id,access_token)).json()
        for song in artist_response['tracks']:
            songs.append(song['name'])
            songs.append(song['popularity'])
            songs.append("https://open.spotify.com/artist/" + artist_id,)
            songs.append(song['artists'][0]['name'])
            songs.append(song['album']['name'])
            songs.append(song['album']['images'][0]['url'])
            track.append(songs)
            songs = []
        context = {
            'tracks':track,
        }
        return render(request,'song/recommend_results.html', context=context)
    else:
        if artist_name == '':
            value = randint(0, 10)
            lyrics = random_lyrics[value]
            context = {
                'lyrics':lyrics,
            }
            return render(request,'artists/recommended_search.html', context=context)
        else:
            token = oauth2.SpotifyClientCredentials(client_id=client_id,client_secret=client_secret)
            access_token = token.get_access_token()
            get_artist_details_url = "https://api.spotify.com/v1/search?q={}&type=artist&access_token={}"
            artist_response = requests.get(get_artist_details_url.format(artist_name,access_token)).json()
            artist_id = artist_response['artists']['items'][0]['id']
            get_recommend_url = "https://api.spotify.com/v1/recommendations?seed_artists={}&access_token={}"
            artist_response = requests.get(get_recommend_url.format(artist_id,access_token)).json()
            for song in artist_response['tracks']:
                songs.append(song['name'])
                songs.append(song['popularity'])
                songs.append("https://open.spotify.com/artist/" + artist_id,)
                songs.append(song['artists'][0]['name'])
                songs.append(song['album']['name'])
                songs.append(song['album']['images'][0]['url'])
                track.append(songs)
                songs = []
            context = {
                'tracks':track,
            }
            return render(request,'song/recommend_results.html', context=context)
def generate_token():
    """ Generate the token. Please respect these credentials :) """
    credentials = oauth2.SpotifyClientCredentials(
        client_id = "5a50ec388e014dda8c475275e7a39631",
        client_secret = "58ce595bfef64775aea3a7a32bd83116")
    token = credentials.get_access_token()
    return token
class SpotifyApi(object):

    client_id = os.environ['SPOTIPY_CLIENT_ID']
    client_secret = os.environ['SPOTIPY_CLIENT_SECRET']
    redirect_uri = os.environ['SPOTIPY_REDIRECT_URI']
    _id = oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri)
    client = oauth2.SpotifyClientCredentials()

    def generate_token(self, user_code):
        url = "https://accounts.spotify.com/api/token"
        data = {
            # 'grant_type': 'client_credentials',
            'grant_type': 'authorization_code',
            'code': user_code,
            'redirect_uri': "http://localhost:8080/login",
        }
        response = requests.post(url,
                                 data=data,
                                 auth=(self.client_id, self.client_secret))

        return response.json()

    def get_spotify_toolbox(self, requesting):
        if 'code' in requesting.args:
            code = requesting.args.get('code')

        elif 'error' in request.args:
            code = requesting.args.get('error')
            raise code
        else:
            code = "This was unexpected, where my queries at?"
        spotify_toolbox = spotipy.Spotify(
            client_credentials_manager=self.client)
        return spotify_toolbox
Exemple #4
0
def musical(scrapdf):
    print('Hola nos estamos conectando a la API de Spotify')
    print('Espero no tardar con la obtencion de canciones de la lista que me has mandado, asi que no desesperes')
    CLIENT_ID = "2b7f57a2e7d74e43b0a0771a99fbb470"
    CLIENT_SECRET = "219cfd4ed31349d5b3175e3526de4921"

    credentials = oauth2.SpotifyClientCredentials(
            client_id=CLIENT_ID,
            client_secret=CLIENT_SECRET)

    token = credentials.get_access_token()
    spotify = spotipy.Spotify(auth=token)

    apiDF = pd.DataFrame({'href':[], 'items':[], 'limit':[], 'next':[], 'offset':[], 'previous':[], 'total':[]})
    dataframes = []
    for row in scrapdf.itertuples():
        canciones = spotify.user_playlist_tracks(row.Id_usr, str(row.Id_playlist).replace('/playlist/', ''))
        dataframes.append(pd.DataFrame(canciones))
    print('He terminado con obtención de canciones')
    apiDF = pd.concat(dataframes)
    apiDF.reset_index(inplace = True)
    candionero2 = json_normalize(apiDF['items'])
    dfinal = candionero2[['track.name', 'track.external_urls.spotify', 'track.href', 'track.id'  ,'track.popularity']]
    dfinal.drop_duplicates(inplace = True)
    dfinal.dropna(inplace = True)
    dfinal.to_csv("./SpotifyApi.csv", index = False)
    return dfinal
Exemple #5
0
def generate_credentials():
    """Generate the token. Please respect these credentials :)"""
    credentials = oauth2.SpotifyClientCredentials(
        client_id="6451e12933bb49ed8543d41e3296a88d",
        client_secret="40ef54678fe441bd9acd66f5d5c34e69",
    )
    return credentials
Exemple #6
0
 def connectSpotify(self):
     spot_client_id = "371af5b9ee7146b6b2c038195a54e06a"
     spot_client_key = "352f23c6be3148de82b19e7ccc711d61"
     credentials = oauth2.SpotifyClientCredentials(
         client_id=spot_client_id, client_secret=spot_client_key)
     token = credentials.get_access_token()
     return spotipy.Spotify(auth=token)
def index():
    """ Displays the index page accessible at '/'
    """
    auth.SpotifyClientCredentials(client_id, client_secret)
    send_url_request(ACCESS.get_authorize_url())

    return flask.render_template('index.html')
def generate_spotify_token():
    credentials = oauth2.SpotifyClientCredentials(
        client_id='4fe3fecfe5334023a1472516cc99d805',
        client_secret='0f02b7c483c04257984695007a4a8d5c')
    token = credentials.get_access_token()

    return token
    def get(self, name):
        credentials = oauth2.SpotifyClientCredentials(
            client_id="", client_secret="e5e7f45c6898dcb8bb34a4ee0")

        token = credentials.get_access_token()

        url = "https://api.spotify.com/v1/search"

        params = {"query": name, "type": "artist", "limit": 1}

        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": "Bearer " + token,
        }
        req = requests.get(url, headers=headers, params=params)

        sData = req.json()
        artist = {}
        if "artists" in sData:
            artists = sData["artists"]["items"]
            if len(artists) != 0:
                data = artists[0]
                img1 = ""
                spotifyURL = ""
                if len(data["images"]) != 0:
                    img1 = data["images"][0]
                if "spotify" in data["external_urls"]:
                    spotifyURL = data["external_urls"]["spotify"]
                artist = {
                    "spotifyURL": spotifyURL,
                    "spotifyPopularity": str(data["popularity"]),
                    "spotifyImage": img1,
                }
        return (artist)
Exemple #10
0
def generate_token(SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET):
    """ Generate the token. Please respect these credentials :) """
    """https://www.programcreek.com/python/example/107939/spotipy.oauth2.SpotifyClientCredentials"""
    credentials = oauth2.SpotifyClientCredentials(
        client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET)
    token = credentials.get_access_token()
    return token
Exemple #11
0
def generateSpotifyObject():
    clientID = "1bb4ca2adbe14ec299ae000ec92fd78e"
    clientSecret = "51f6ca11380a425e95ae29b704ed5069"
    credentials = oauth2.SpotifyClientCredentials(client_id=clientID,
                                                  client_secret=clientSecret)
    token = credentials.get_access_token()
    return spotipy.Spotify(auth=token)
Exemple #12
0
def get_data(filename):
    """
    Creates the data and labels for all valid songs in the dataset

    param: the root file name with all song data
    returns: data: [num_valid_songs, 1024, 12] matrix of MFCC content,
        labels: [num_valid_songs] array of danceability label
    """
    credentials = oauth2.SpotifyClientCredentials(
        client_id='b8aaedbcc185427d96c4f92151d23951',
        client_secret='8be53030941e409cb0e7c6196ad979fd')
    token = credentials.get_access_token()
    sp = spotipy.Spotify(auth=token)
    songs = get_all_files(filename, '.h5')
    # labels, broken_labels = create_labels(songs, sp)
    # with open("labels.txt", "wb") as f1:
    #     np.savetxt(f1, labels.astype(int), fmt='%i', delimiter=",")
    # with open("broken_labels.txt", "wb") as f2:
    #     np.savetxt(f2, broken_labels.astype(int), fmt='%i', delimiter=",")
    with open("labels.txt", "r") as f:
        labels = np.loadtxt(f,dtype=np.int32)
    with open("broken_labels.txt", "r") as f:
        broken_labels = np.loadtxt(f,dtype=np.int32)
    data = create_data(songs, labels, broken_labels)
    print("SIZE OF DATA = ", data.shape)
    print("SIZE OF LABELS = ", labels.shape)
    return data, labels
Exemple #13
0
 def set_sp(self):
     """Gets the spotipy handler"""
     credentials = oauth2.SpotifyClientCredentials(
         client_id=os.getenv("SPOTIPY_CLIENT_ID"),
         client_secret=os.getenv("SPOTIPY_CLIENT_SECRET"))
     token = credentials.get_access_token()
     self.sp = spotipy.Spotify(auth=token)
Exemple #14
0
def generate_token():
    """ Generate the token. Please respect these credentials :) """
    credentials = oauth2.SpotifyClientCredentials(
        client_id=os.getenv('SPOTDL_CLIENT_ID'),
        client_secret=os.getenv('SPOTDL_CLIENT_SECRET'),
    )
    return credentials.get_access_token(as_dict=False)
Exemple #15
0
 def _generate_token(self, client_id, client_secret):
     """ Generate the token. """
     credentials = oauth2.SpotifyClientCredentials(
         client_secret=client_secret,
     )
     token = credentials.get_access_token()
     return token
Exemple #16
0
 def __init__(self):
     self.client_id = "18b12f99b644451f88d0460db3e35c74"
     self.client_secret = "94a01ec88f53412e83e62c4cd134486c"
     self.credentials = oauth2.SpotifyClientCredentials(
         client_id=self.client_id, client_secret=self.client_secret)
     token = self.credentials.get_access_token()
     self.sp = spotipy.Spotify(auth=token)
Exemple #17
0
def meat(artist): 
    credentials = oauth2.SpotifyClientCredentials(
        client_id='c6bbc479081f433d9dd08ba3734b6077',
        client_secret='c1bc5f13ac9a421eb1ecae345ceb959c')

    token = credentials.get_access_token()
    spotify = spotipy.Spotify(auth=token)

    artist_input = artist
    results = spotify.search(q='artist:' + artist_input, type='artist')
    artist_uri = results['artists']['items'][0]['uri'].split(":")[2]

    results = spotify.artist_top_tracks(artist_uri)

    songs = []

    for track in results['tracks'][:5]:
        preview_url = track['preview_url'].replace("https://", "http://", 1) + ".mp3"
        r = requests.get(preview_url, allow_redirects=True)
        open(track['name'] + '.mp3', 'wb').write(r.content)
        songMp3 = AudioSegment.from_mp3(track['name'] + '.mp3').set_channels(1)
        os.remove(track['name'] + '.mp3')
        songMp3.export(track['name'] + '.wav', format="wav")
        import_rate, import_data = wav.read(track['name'] + '.wav')
        os.remove(track['name'] + '.wav')
        avg_freq = average_frequency(import_rate * 1.0, import_data)
        print(avg_freq)
        songs.append(avg_freq)
    # context = {'songs': songs}
    return songs
Exemple #18
0
def client_credential_flow():
    client_credentials_manager = oauth.SpotifyClientCredentials()
    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    search_str = 'Rollling Stones Street Love'
    result = sp.search(search_str)
    pprint.pprint(result)
    return result
Exemple #19
0
def generate_token():
    """ Generate the token. Please respect these credentials :) """
    credentials = oauth2.SpotifyClientCredentials(
        client_id='4fe3fecfe5334023a1472516cc99d805',
        client_secret='0f02b7c483c04257984695007a4a8d5c')
    token = credentials.get_access_token()
    return token
Exemple #20
0
    def __init__(self, client_id=None, client_secret=None):
        global masterclient
        # `spotipy.Spotify` makes use of `self._session` and would
        # result in an error. The below line is a workaround.
        self._session = None

        credentials_provided = client_id is not None \
                           and client_secret is not None
        valid_input = credentials_provided or masterclient is not None

        if not valid_input:
            raise SpotifyAuthorizationError(
                "You must pass in client_id and client_secret to this method "
                "when authenticating for the first time.")

        if masterclient:
            logger.debug("Reading cached master Spotify credentials.")
            # Use cached client instead of authorizing again
            # and thus wasting time.
            self.__dict__.update(masterclient.__dict__)
        else:
            logger.debug("Setting master Spotify credentials.")
            credential_manager = oauth2.SpotifyClientCredentials(
                client_id=client_id, client_secret=client_secret)
            super().__init__(client_credentials_manager=credential_manager)
            # Cache current client
            masterclient = self
Exemple #21
0
def main():
     total_start = time.time()
     warnings.simplefilter('ignore')
     ccm = oauth2.SpotifyClientCredentials(client_id=CLIENT_ID,
                                                   client_secret=CLIENT_SECRET)

     spotify = spotipy.Spotify(client_credentials_manager=ccm)

     artists_dict = dict()
     artist_names = ['Taylor Swift','Rihanna', 'Selena Gomez',
                     'Ed Sheeran', 'The Weeknd', 'Drake',
                     'Coldplay', 'Maroon 5', 'Imagine Dragons']

     for name in artist_names:
          artists_dict = get_artist_from_name(spotify, name, artists_dict)
     
     artists_sql = create_artist_sql(artists_dict)
     insert_sql(artists_sql)

     genre_sql = create_art_genre_sql(artists_dict)
     insert_sql(genre_sql)

     for artist_id in artists_dict:
          print "Getting albums for artist: "+artists_dict[artist_id]['name']
          get_artist_albums(spotify, artist_id)

     clean_database(spotify)
     total_end = time.time()
     print "Total time elapsed: "+str(total_end - total_start)
Exemple #22
0
def generate_token():
    """ Generate the token. Please respect these credentials :) """
    credentials = oauth2.SpotifyClientCredentials(
        client_id='37373b59fc3442f88b4880d7bcaff6ea',
        client_secret='2edca93ea10e41c8b7601d693acad192')
    token = credentials.get_access_token()
    return token
Exemple #23
0
def generate_token():
    """Generate the token. Please respect these credentials :)"""
    credentials = oauth2.SpotifyClientCredentials(
        client_id='05a27dfaa107438eb78215d18ce0aedc',
        client_secret='16a88c04b61941b39a1aa3f3f2190e9e')
    token = credentials.get_access_token()
    return token
Exemple #24
0
def generate_token():
    """ Generate the token. Please respect these credentials :) """
    credentials = oauth2.SpotifyClientCredentials(
        client_id="client_id",  #make these system variables
        client_secret="client_secret")
    token = credentials.get_access_token()
    return token
Exemple #25
0
def getSpotifyBPM():
    global sliderValue
    global beginBPM
    global bpm
    global idName
    global qSpotify
    qSpotify = getShazamSong()
    credentials = oauth2.SpotifyClientCredentials(
        client_id=os.environ['SPOTIPY_CLIENT_ID'],
        client_secret=os.environ['SPOTIPY_CLIENT_SECRET'])
    #token = credentials.get_access_token()
    #sp = spotipy.Spotify(auth=token)#if not t['name']: #auth_manager
    sp = spotipy.Spotify(auth_manager=credentials)  #if not t['name']:
    results = sp.search(q=qSpotify, limit=1)
    for i, t in enumerate(results['tracks']['items']):
        idTrack = t['id']
        idName = (t['name']) + (t['artists'][0]['name'])
        features = sp.audio_features([idTrack])

    #https://pythonrepo.com/repo/plamere-spotipy-python-third-party-apis-wrappers
    #https://dev.to/arvindmehairjan/how-to-play-spotify-songs-and-show-the-album-art-using-spotipy-library-and-python-5eki
    #devices = sp.devices()
    #print(json.dumps(devices, sort_keys=True, indent=4))
    #deviceID = devices['devices'][0]['id']
    #sp.start_playback(deviceID, None, trackSelectionList)
    try:
        print("BPM spotify: ", features[0]['tempo'])
        print("beginBPMSlidder", beginBPMSlidder)
    except:
        print("features not get from spotify?")
    try:
        return (features[0]['tempo'])  #(features['tempo'] not dict, 10th place
    except:
        return (bpm)  #standart bpm
Exemple #26
0
    def login_spotipy(client_id, client_secret):
        credentials = oauth2.SpotifyClientCredentials(
            client_id=client_id, client_secret=client_secret)

        token = credentials.get_access_token()
        sp = spotipy.Spotify(auth=token)
        return sp
    def __init__(self, spotify_client_id, spotify_client_secret,
                 spotify_username):
        '''Spotify Processor Class that maanges the account user details & playlists.'''

        # Spotify Account User Details
        self.spotify_client_id = spotify_client_id
        self.spotify_client_secret = spotify_client_secret
        self.spotify_username = spotify_username

        # Storage variables that help manage which song / playlist to download
        self.playlists_table = {}
        self.playlists_names = []
        self.selected_playlist_index = 1
        self.selected_playlist = ''
        self.selected_songs = []
        self.current_song = ''

        # Spotify oauth2 object
        self.credentials = oauth2.SpotifyClientCredentials(
            client_id=self.spotify_client_id,
            client_secret=self.spotify_client_secret)

        # More spotify account details
        self.token = self.credentials.get_access_token(as_dict=False)
        self.spotify = spotipy.Spotify(auth=self.token)

        # All public playlists under the Spotify username's account
        self.playlists = self.spotify.user_playlists(self.spotify_username)
def song_search(request):
    songs = []
    track = []
    if request.method == "POST":
        token =oauth2.SpotifyClientCredentials(client_id=client_id,client_secret=client_secret)
        access_token = token.get_access_token()    
        song_name = request.POST.get('name')
        get_song_details_url = "https://api.spotify.com/v1/search?q={}&type=track&access_token={}"
        tracks = requests.get(get_song_details_url.format(song_name,access_token)).json()
        for song in tracks['tracks']['items']:
            songs.append(song['name'])
            songs.append(song['popularity'])
            songs.append(song['href'])
            songs.append(song['artists'][0]['name'])
            songs.append(song['album']['name'])
            songs.append(song['album']['images'][0]['url'])
            songs.append(song['name'] + ' ' + song['artists'][0]['name'])
            track.append(songs)
            songs = []
        context = {
            'tracks':track,
        }
        return render(request,'song/song_results.html', context=context)
    else:
        value = randint(0, 10)
        lyrics = random_lyrics[value]
        context = {
            'lyrics':lyrics,
        }
        return render(request,'song/song_search.html', context=context)
    def _spotipy_connector(self):
        """Establishes a connection to the spotify API and returning an object that can make queries."""

        credentials = oauth2.SpotifyClientCredentials(
            client_id=config.spotify_id,
            client_secret=config.spotify_secret)
        self.token = credentials.get_access_token()
        self.conn = spotipy.Spotify(auth=self.token)
def generate_token():
    """ Generate the token. """
    credentials = oauth2.SpotifyClientCredentials(
        client_id=const.args.spotify_client_id,
        client_secret=const.args.spotify_client_secret,
    )
    token = credentials.get_access_token()
    return token