# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import requests#Connect to endpoints
import time #time script
import sys
import csv
import pandas as pd
import spotipy#authentication
import spotipy.util as util#authentication
from spotipy.oauth2 import SpotifyClientCredentials#authentication

#Credentials
cid = '049ade7215e54c63a2b628f3784dc407'
secret = '<KEY>'
redirect_uri = 'http://google.com/'
username = 'xxx'

# +
#Authentication
scope = 'user-library-read'
token = util.prompt_for_user_token(username, scope, client_id=cid, client_secret=secret, redirect_uri=redirect_uri)

if token:
    sp = spotipy.Spotify(auth=token)
else:
    print("Can't get token for", username)


# -

def get_albums(nexturl,artist_uri):
    all_albums = []
    try:
        resp = requests.get(url=nexturl,
                            headers={'Authorization': 'Bearer ' + token})
        resp.raise_for_status()
    except requests.exceptions.HTTPError as err:
        print(err)
        
        
    response = resp.json()
    
    album_limit = (response['limit'])-1
    print(album_limit)
    
    for x in range(album_limit):
        try:
            album_uri = response['items'][x]['uri'].split(':')
            all_albums.append(album_uri[2])
        except IndexError as error:
            continue #Natural part of the process. The length of response is sometimes less than limit
    try:
        if (nexturl is not None):
            get_albums(response['next'])
        else:
            return
    except:
        return all_albums
    

# +
i = 0
album_list=[]

start = time.time()
with open('Data/artist_uri.csv') as csvfile:
    file = csv.reader(csvfile, delimiter='|')
    next(file)
    head = [next(file) for x in range(1)] #for limiting amount of rows read
    for row in head:
        artist_uri = row[0]
        artist_name = row[1]
        print(i,artist_uri,artist_name)
        
        #output album_uri
        albums = get_albums('https://api.spotify.com/v1/artists/{id}/albums?limit=20'.format(id=artist_uri),artist_uri)#list of album uris
        
        #There are a number of albums per artist so need to create a record of each
        for album in albums:
            album_list.append({'Artist URI':artist_uri,'Artist Name':artist_name,'Album URI':album})
        i+=1
stop = time.time()
duration = (stop - start)/60
# -

#Duration of script
str(duration)+' minutes'

df = pd.DataFrame(album_list)
df
#no_duplicates = df.drop_duplicates(['Album URI'])
#no_duplicates.to_csv('Data/artist_album_uri.csv',sep='|',index=False)
#no_duplicates



StarcoderdataJupyterScriptsDedupFiltered