CoolFace
Apppublic

seyia92coding/Popular_Spotify_Albums

sourceHugging Faceupdated 2y agoView on Hugging Face
1likes
app.py186 linesDownload Raw Back to root
1# -*- coding: utf-8 -*-2"""Most Popular Albums Per Artist With Gradio_V16-06-24.ipynb3 4Automatically generated by Colab.5 6Original file is located at7    https://colab.research.google.com/drive/1wx0n0CuWwG6Pn034qj-vQJPklYLab2-Y8 9# Set up Spotify credentials10 11Before getting started you need:12 13* Spotify API permissions & credentials that could apply for [here](https://developer.spotify.com/). Simply log in, go to your “dashboard” and select “create client id” and follow the instructions. Spotify are not too strict on providing permissions so put anything you like when they ask for commercial application.14 15* Python module — spotipy — imported16"""17 18import spotipy19#To access authorised Spotify data - https://developer.spotify.com/20from spotipy.oauth2 import SpotifyClientCredentials21from fuzzywuzzy import fuzz22import pandas as pd23import seaborn as sns24import gradio as gr25#https://gradio.app/docs/#i_slider26import matplotlib.pyplot as plt27import time28import numpy as np29 30#Create Function for identifying your artist31 32def choose_artist(name_input, sp):33  results = sp.search(name_input)34  #result_1 = result['tracks']['items'][0]['artists']35  top_matches = []36  counter = 037  #for each result item (max 10 I think)38  for i in results['tracks']['items']:39    #store current item40    current_item = results['tracks']['items'][counter]['artists']41    counter+=142    #for each item in that search_term43    counter2 = 044    for i in current_item:45      #append artist name to top_matches46      #I will need to append something to identify the correct match, please update once I know47      top_matches.append((current_item[counter2]['name'], current_item[counter2]['uri']))48      counter2+=149 50  #remove duplicates by turning list into a set, then back into a list51  top_matches = list(set(top_matches))52 53  fuzzy_matches = []54  #normal list doesn't need len(range)55  for i in top_matches:56    #put ratio result in variable to avoid errors57    ratio = fuzz.ratio(name_input, i[0])58    #store as tuple but will need to increase to 3 to include uid59    fuzzy_matches.append((i[0], ratio, i[1]))60  #sort fuzzy matches by ratio score61  fuzzy_matches = sorted(fuzzy_matches, key=lambda tup: tup[1], reverse=True)62  #store highest tuple's attributes in chosen variables63  chosen = fuzzy_matches[0][0]64  chosen_id = fuzzy_matches[0][1]65  chosen_uri = fuzzy_matches[0][2]66  print("The results are based on the artist: ", chosen)67  return chosen, chosen_id, chosen_uri68 69#Function to Pull all of your artist's albums70def find_albums(artist_uri, sp):71  sp_albums = sp.artist_albums(artist_uri, album_type='album', limit=50) #There's a 50 album limit72  album_names = []73  album_uris = []74  for i in range(len(sp_albums['items'])):75    #Keep names and uris in same order to keep track of duplicate albums76    album_names.append(sp_albums['items'][i]['name'])77    album_uris.append(sp_albums['items'][i]['uri'])78  return album_uris, album_names79 80#Function to store all album details along with their song details81def albumSongs(album, sp, album_count, album_names, spotify_albums):82    spotify_albums[album] = {} #Creates dictionary for that specific album83    #Create keys-values of empty lists inside nested dictionary for album84    spotify_albums[album]['album_name'] = [] #create empty list85    spotify_albums[album]['track_number'] = []86    spotify_albums[album]['song_id'] = []87    spotify_albums[album]['song_name'] = []88    spotify_albums[album]['song_uri'] = []89 90    tracks = sp.album_tracks(album) #pull data on album tracks91 92    for n in range(len(tracks['items'])): #for each song track93        spotify_albums[album]['album_name'].append(album_names[album_count]) #append album name tracked via album_count94        spotify_albums[album]['track_number'].append(tracks['items'][n]['track_number'])95        spotify_albums[album]['song_id'].append(tracks['items'][n]['id'])96        spotify_albums[album]['song_name'].append(tracks['items'][n]['name'])97        spotify_albums[album]['song_uri'].append(tracks['items'][n]['uri'])98 99#Add popularity category100def popularity(album, sp, spotify_albums):101    #Add new key-values to store audio features102    spotify_albums[album]['popularity'] = []103    #create a track counter104    track_count = 0105    for track in spotify_albums[album]['song_uri']:106        #pull audio features per track107        pop = sp.track(track)108        spotify_albums[album]['popularity'].append(pop['popularity'])109        track_count+=1110 111def gradio_music_graph(client_id, client_secret, artist_name): #total_albums112  #Insert your credentials113  client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)114  sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) #spotify object to access API115  #Choose your artist via input116  chosen_artist, ratio_score, artist_uri = choose_artist(artist_name, sp=sp)117  #Retrieve their album details118  album_uris, album_names = find_albums(artist_uri, sp=sp)119  #Create dictionary to store all the albums120  spotify_albums = {}121  #Album count tracker122  album_count = 0123  for i in album_uris: #for each album124      albumSongs(i, sp=sp, album_count=album_count, album_names=album_names, spotify_albums=spotify_albums)125      print("Songs from " + str(album_names[album_count]) + " have been added to spotify_albums dictionary")126      album_count+=1 #Updates album count once all tracks have been added127 128  #To avoid it timing out129  sleep_min = 2130  sleep_max = 5131  start_time = time.time()132  request_count = 0133  #Update albums with popularity scores134  for album in spotify_albums:135      popularity(album, sp=sp, spotify_albums=spotify_albums)136      request_count+=1137      if request_count % 5 == 0:138          # print(str(request_count) + " playlists completed")139          time.sleep(np.random.uniform(sleep_min, sleep_max))140          # print('Loop #: {}'.format(request_count))141          # print('Elapsed Time: {} seconds'.format(time.time() - start_time))142 143  #Create song dictonary to convert into Dataframe144  dic_df = {}145 146  dic_df['album_name'] = []147  dic_df['track_number'] = []148  dic_df['song_id'] = []149  dic_df['song_name'] = []150  dic_df['song_uri'] = []151  dic_df['popularity'] = []152 153  for album in spotify_albums:154      for feature in spotify_albums[album]:155          dic_df[feature].extend(spotify_albums[album][feature])156  #Convert into dataframe157 158  df = pd.DataFrame.from_dict(dic_df)159  df = df.sort_values(by='popularity')160  df = df.drop_duplicates(subset=['song_id'], keep=False)161 162#Parameters of a Original Plot, unfortunately, no longer works (for now)163  # sns.set_style('ticks')164 165  # fig, ax = plt.subplots()166  # fig.set_size_inches(11, 8)167  # ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")168  # plt.tight_layout()169 170  # sns.boxplot(x=df["album_name"], y=df["popularity"], ax=ax)171  # fig.savefig('artist_popular_albums.png')172  # plt.show()173 174  return df175 176plot = gr.ScatterPlot(x="album_name", y="popularity", width=600, height=350, title="Popular Songs By Album Box Plot Distribution on Spotify")177#Interface will include these buttons based on parameters in the function with a dataframe output178 179#Ignore, old code180#music_plots = gr.Interface(gradio_music_graph, ["text", "text", "text"],181#                           ["dataframe", "plot"], title="Popular Songs By Album Box Plot Distribution on Spotify", description="Using your Spotify API Access from https://developer.spotify.com/ you can see your favourite artist's most popular albums on Spotify")182 183music_plots = gr.Interface(fn=gradio_music_graph, inputs=["text","text","text"], outputs=plot)184 185 186music_plots.launch(debug=True)