File size: 7,267 Bytes
401a647
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fadd779
401a647
fadd779
8fc4f28
401a647
 
fadd779
401a647
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# -*- coding: utf-8 -*-
"""Most Popular Albums Per Artist With Gradio.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1wMpev3zhNcOdO_amUdfeE6HCflOB8KIL

# Set up Spotify credentials

Before getting started you need:

* 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.

* Python module — spotipy — imported
"""

import spotipy
#To access authorised Spotify data - https://developer.spotify.com/
from spotipy.oauth2 import SpotifyClientCredentials
from fuzzywuzzy import fuzz
import pandas as pd
import seaborn as sns
import gradio as gr
#https://gradio.app/docs/#i_slider
import matplotlib.pyplot as plt
import time
import numpy as np

#Create Function for identifying your artist

def choose_artist(name_input, sp):
  results = sp.search(name_input)
  #result_1 = result['tracks']['items'][0]['artists']
  top_matches = []
  counter = 0
  #for each result item (max 10 I think)
  for i in results['tracks']['items']:
    #store current item
    current_item = results['tracks']['items'][counter]['artists']
    counter+=1
    #for each item in that search_term
    counter2 = 0
    for i in current_item:
      #append artist name to top_matches
      #I will need to append something to identify the correct match, please update once I know
      top_matches.append((current_item[counter2]['name'], current_item[counter2]['uri']))
      counter2+=1

  #remove duplicates by turning list into a set, then back into a list
  top_matches = list(set(top_matches))

  fuzzy_matches = []
  #normal list doesn't need len(range)
  for i in top_matches:
    #put ratio result in variable to avoid errors
    ratio = fuzz.ratio(name_input, i[0])
    #store as tuple but will need to increase to 3 to include uid
    fuzzy_matches.append((i[0], ratio, i[1]))
  #sort fuzzy matches by ratio score
  fuzzy_matches = sorted(fuzzy_matches, key=lambda tup: tup[1], reverse=True)
  #store highest tuple's attributes in chosen variables
  chosen = fuzzy_matches[0][0]
  chosen_id = fuzzy_matches[0][1]
  chosen_uri = fuzzy_matches[0][2]
  print("The results are based on the artist: ", chosen)
  return chosen, chosen_id, chosen_uri

#Function to Pull all of your artist's albums
def find_albums(artist_uri, sp):
  sp_albums = sp.artist_albums(artist_uri, album_type='album', limit=50) #There's a 50 album limit
  album_names = []
  album_uris = []
  for i in range(len(sp_albums['items'])):
    #Keep names and uris in same order to keep track of duplicate albums
    album_names.append(sp_albums['items'][i]['name'])
    album_uris.append(sp_albums['items'][i]['uri'])
  return album_uris, album_names

#Function to store all album details along with their song details
def albumSongs(album, sp, album_count, album_names, spotify_albums):
    spotify_albums[album] = {} #Creates dictionary for that specific album
    #Create keys-values of empty lists inside nested dictionary for album
    spotify_albums[album]['album_name'] = [] #create empty list
    spotify_albums[album]['track_number'] = []
    spotify_albums[album]['song_id'] = []
    spotify_albums[album]['song_name'] = []
    spotify_albums[album]['song_uri'] = []

    tracks = sp.album_tracks(album) #pull data on album tracks

    for n in range(len(tracks['items'])): #for each song track
        spotify_albums[album]['album_name'].append(album_names[album_count]) #append album name tracked via album_count
        spotify_albums[album]['track_number'].append(tracks['items'][n]['track_number'])
        spotify_albums[album]['song_id'].append(tracks['items'][n]['id'])
        spotify_albums[album]['song_name'].append(tracks['items'][n]['name'])
        spotify_albums[album]['song_uri'].append(tracks['items'][n]['uri'])

#Add popularity category
def popularity(album, sp, spotify_albums):
    #Add new key-values to store audio features
    spotify_albums[album]['popularity'] = []
    #create a track counter
    track_count = 0
    for track in spotify_albums[album]['song_uri']:
        #pull audio features per track
        pop = sp.track(track)
        spotify_albums[album]['popularity'].append(pop['popularity'])
        track_count+=1

def gradio_music_graph(client_id, client_secret, artist_name): #total_albums
  #Insert your credentials
  client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
  sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) #spotify object to access API
  #Choose your artist via input
  chosen_artist, ratio_score, artist_uri = choose_artist(artist_name, sp=sp)
  #Retrieve their album details
  album_uris, album_names = find_albums(artist_uri, sp=sp)
  #Create dictionary to store all the albums
  spotify_albums = {}
  #Album count tracker
  album_count = 0
  for i in album_uris: #for each album
      albumSongs(i, sp=sp, album_count=album_count, album_names=album_names, spotify_albums=spotify_albums)
      print("Songs from " + str(album_names[album_count]) + " have been added to spotify_albums dictionary")
      album_count+=1 #Updates album count once all tracks have been added
  
  #To avoid it timing out
  sleep_min = 2
  sleep_max = 5
  start_time = time.time()
  request_count = 0
  #Update albums with popularity scores
  for album in spotify_albums:
      popularity(album, sp=sp, spotify_albums=spotify_albums)
      request_count+=1
      if request_count % 5 == 0:
          # print(str(request_count) + " playlists completed")
          time.sleep(np.random.uniform(sleep_min, sleep_max))
          # print('Loop #: {}'.format(request_count))
          # print('Elapsed Time: {} seconds'.format(time.time() - start_time))

  #Create song dictonary to convert into Dataframe    
  dic_df = {}    

  dic_df['album_name'] = []
  dic_df['track_number'] = []
  dic_df['song_id'] = []
  dic_df['song_name'] = []
  dic_df['song_uri'] = []
  dic_df['popularity'] = []

  for album in spotify_albums: 
      for feature in spotify_albums[album]:
          dic_df[feature].extend(spotify_albums[album][feature])
  #Convert into dataframe

  df = pd.DataFrame.from_dict(dic_df)
  df = df.sort_values(by='popularity')
  df = df.drop_duplicates(subset=['song_id'], keep=False)

  sns.set_style('ticks')

  fig, ax = plt.subplots()
  fig.set_size_inches(11, 8)
  ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
  plt.tight_layout()

  sns.boxplot(x=df["album_name"], y=df["popularity"], ax=ax)
  #fig.savefig('artist_popular_albums.png')
  plt.show()
  
  return df
#Interface will include these buttons based on parameters in the function with a dataframe output
music_plots = gr.Interface(gradio_music_graph, ["text", "text", "text"], 
                           ["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")

music_plots.launch(debug=True)