seyia92coding commited on
Commit
a716291
1 Parent(s): fc87c98

Upload Most_Popular_Albums_Per_Artist_With_Gradio.ipynb

Browse files
Most_Popular_Albums_Per_Artist_With_Gradio.ipynb ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "source": [
6
+ "# Set up Spotify credentials\n",
7
+ "\n",
8
+ "Before getting started you need:\n",
9
+ "\n",
10
+ "* 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.\n",
11
+ "\n",
12
+ "* Python module — spotipy — imported"
13
+ ],
14
+ "metadata": {
15
+ "id": "XnUzjGil6shK"
16
+ }
17
+ },
18
+ {
19
+ "cell_type": "code",
20
+ "source": [
21
+ "!pip install gradio"
22
+ ],
23
+ "metadata": {
24
+ "id": "oQ6x5yuCAzUn"
25
+ },
26
+ "execution_count": null,
27
+ "outputs": []
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "execution_count": null,
32
+ "metadata": {
33
+ "id": "yCTm2lqN1kuh"
34
+ },
35
+ "outputs": [],
36
+ "source": [
37
+ "!pip install spotipy\n",
38
+ "import spotipy\n",
39
+ "#To access authorised Spotify data - https://developer.spotify.com/\n",
40
+ "from spotipy.oauth2 import SpotifyClientCredentials\n",
41
+ "!pip install fuzzywuzzy\n",
42
+ "from fuzzywuzzy import fuzz\n",
43
+ "import pandas as pd\n",
44
+ "import seaborn as sns\n",
45
+ "!pip install gradio\n",
46
+ "import gradio as gr\n",
47
+ "#https://gradio.app/docs/#i_slider\n",
48
+ "import matplotlib.pyplot as plt\n",
49
+ "import time\n",
50
+ "import numpy as np"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "source": [
56
+ "#Create Function for identifying your artist\n",
57
+ "\n",
58
+ "def choose_artist(name_input, sp):\n",
59
+ " results = sp.search(name_input)\n",
60
+ " #result_1 = result['tracks']['items'][0]['artists']\n",
61
+ " top_matches = []\n",
62
+ " counter = 0\n",
63
+ " #for each result item (max 10 I think)\n",
64
+ " for i in results['tracks']['items']:\n",
65
+ " #store current item\n",
66
+ " current_item = results['tracks']['items'][counter]['artists']\n",
67
+ " counter+=1\n",
68
+ " #for each item in that search_term\n",
69
+ " counter2 = 0\n",
70
+ " for i in current_item:\n",
71
+ " #append artist name to top_matches\n",
72
+ " #I will need to append something to identify the correct match, please update once I know\n",
73
+ " top_matches.append((current_item[counter2]['name'], current_item[counter2]['uri']))\n",
74
+ " counter2+=1\n",
75
+ "\n",
76
+ " #remove duplicates by turning list into a set, then back into a list\n",
77
+ " top_matches = list(set(top_matches))\n",
78
+ "\n",
79
+ " fuzzy_matches = []\n",
80
+ " #normal list doesn't need len(range)\n",
81
+ " for i in top_matches:\n",
82
+ " #put ratio result in variable to avoid errors\n",
83
+ " ratio = fuzz.ratio(name_input, i[0])\n",
84
+ " #store as tuple but will need to increase to 3 to include uid\n",
85
+ " fuzzy_matches.append((i[0], ratio, i[1]))\n",
86
+ " #sort fuzzy matches by ratio score\n",
87
+ " fuzzy_matches = sorted(fuzzy_matches, key=lambda tup: tup[1], reverse=True)\n",
88
+ " #store highest tuple's attributes in chosen variables\n",
89
+ " chosen = fuzzy_matches[0][0]\n",
90
+ " chosen_id = fuzzy_matches[0][1]\n",
91
+ " chosen_uri = fuzzy_matches[0][2]\n",
92
+ " print(\"The results are based on the artist: \", chosen)\n",
93
+ " return chosen, chosen_id, chosen_uri"
94
+ ],
95
+ "metadata": {
96
+ "colab": {
97
+ "base_uri": "https://localhost:8080/"
98
+ },
99
+ "id": "Hpbj6dLF8LmI",
100
+ "outputId": "cfc62ba7-1aab-460c-fdee-bac810e0ea52"
101
+ },
102
+ "execution_count": 24,
103
+ "outputs": [
104
+ {
105
+ "output_type": "stream",
106
+ "name": "stdout",
107
+ "text": [
108
+ "The results are based on the artist: Unknown T\n"
109
+ ]
110
+ }
111
+ ]
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "execution_count": 30,
116
+ "metadata": {
117
+ "id": "NsjpVGCP1kul"
118
+ },
119
+ "outputs": [],
120
+ "source": [
121
+ "#Function to Pull all of your artist's albums\n",
122
+ "def find_albums(artist_uri, sp):\n",
123
+ " sp_albums = sp.artist_albums(artist_uri, album_type='album', limit=50) #There's a 50 album limit\n",
124
+ " album_names = []\n",
125
+ " album_uris = []\n",
126
+ " for i in range(len(sp_albums['items'])):\n",
127
+ " #Keep names and uris in same order to keep track of duplicate albums\n",
128
+ " album_names.append(sp_albums['items'][i]['name'])\n",
129
+ " album_uris.append(sp_albums['items'][i]['uri'])\n",
130
+ " return album_uris, album_names"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "source": [
136
+ "#Function to store all album details along with their song details\n",
137
+ "def albumSongs(album, sp, album_count, album_names, spotify_albums):\n",
138
+ " spotify_albums[album] = {} #Creates dictionary for that specific album\n",
139
+ " #Create keys-values of empty lists inside nested dictionary for album\n",
140
+ " spotify_albums[album]['album_name'] = [] #create empty list\n",
141
+ " spotify_albums[album]['track_number'] = []\n",
142
+ " spotify_albums[album]['song_id'] = []\n",
143
+ " spotify_albums[album]['song_name'] = []\n",
144
+ " spotify_albums[album]['song_uri'] = []\n",
145
+ "\n",
146
+ " tracks = sp.album_tracks(album) #pull data on album tracks\n",
147
+ "\n",
148
+ " for n in range(len(tracks['items'])): #for each song track\n",
149
+ " spotify_albums[album]['album_name'].append(album_names[album_count]) #append album name tracked via album_count\n",
150
+ " spotify_albums[album]['track_number'].append(tracks['items'][n]['track_number'])\n",
151
+ " spotify_albums[album]['song_id'].append(tracks['items'][n]['id'])\n",
152
+ " spotify_albums[album]['song_name'].append(tracks['items'][n]['name'])\n",
153
+ " spotify_albums[album]['song_uri'].append(tracks['items'][n]['uri'])"
154
+ ],
155
+ "metadata": {
156
+ "id": "mgR4WN77iYG0"
157
+ },
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "source": [
164
+ "#Add popularity category\n",
165
+ "def popularity(album, sp, spotify_albums):\n",
166
+ " #Add new key-values to store audio features\n",
167
+ " spotify_albums[album]['popularity'] = []\n",
168
+ " #create a track counter\n",
169
+ " track_count = 0\n",
170
+ " for track in spotify_albums[album]['song_uri']:\n",
171
+ " #pull audio features per track\n",
172
+ " pop = sp.track(track)\n",
173
+ " spotify_albums[album]['popularity'].append(pop['popularity'])\n",
174
+ " track_count+=1"
175
+ ],
176
+ "metadata": {
177
+ "id": "4bgHVdBnpawL"
178
+ },
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "source": [
185
+ "def gradio_music_graph(client_id, client_secret, artist_name): #total_albums\n",
186
+ " #Insert your credentials\n",
187
+ " client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)\n",
188
+ " sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) #spotify object to access API\n",
189
+ " #Choose your artist via input\n",
190
+ " chosen_artist, ratio_score, artist_uri = choose_artist(artist_name, sp=sp)\n",
191
+ " #Retrieve their album details\n",
192
+ " album_uris, album_names = find_albums(artist_uri, sp=sp)\n",
193
+ " #Create dictionary to store all the albums\n",
194
+ " spotify_albums = {}\n",
195
+ " #Album count tracker\n",
196
+ " album_count = 0\n",
197
+ " for i in album_uris: #for each album\n",
198
+ " albumSongs(i, sp=sp, album_count=album_count, album_names=album_names, spotify_albums=spotify_albums)\n",
199
+ " print(\"Songs from \" + str(album_names[album_count]) + \" have been added to spotify_albums dictionary\")\n",
200
+ " album_count+=1 #Updates album count once all tracks have been added\n",
201
+ " \n",
202
+ " #To avoid it timing out\n",
203
+ " sleep_min = 2\n",
204
+ " sleep_max = 5\n",
205
+ " start_time = time.time()\n",
206
+ " request_count = 0\n",
207
+ " #Update albums with popularity scores\n",
208
+ " for album in spotify_albums:\n",
209
+ " popularity(album, sp=sp, spotify_albums=spotify_albums)\n",
210
+ " request_count+=1\n",
211
+ " if request_count % 5 == 0:\n",
212
+ " # print(str(request_count) + \" playlists completed\")\n",
213
+ " time.sleep(np.random.uniform(sleep_min, sleep_max))\n",
214
+ " # print('Loop #: {}'.format(request_count))\n",
215
+ " # print('Elapsed Time: {} seconds'.format(time.time() - start_time))\n",
216
+ "\n",
217
+ " #Create song dictonary to convert into Dataframe \n",
218
+ " dic_df = {} \n",
219
+ "\n",
220
+ " dic_df['album_name'] = []\n",
221
+ " dic_df['track_number'] = []\n",
222
+ " dic_df['song_id'] = []\n",
223
+ " dic_df['song_name'] = []\n",
224
+ " dic_df['song_uri'] = []\n",
225
+ " dic_df['popularity'] = []\n",
226
+ "\n",
227
+ " for album in spotify_albums: \n",
228
+ " for feature in spotify_albums[album]:\n",
229
+ " dic_df[feature].extend(spotify_albums[album][feature])\n",
230
+ " #Convert into dataframe\n",
231
+ "\n",
232
+ " df = pd.DataFrame.from_dict(dic_df)\n",
233
+ " df = df.sort_values(by='popularity')\n",
234
+ " df = df.drop_duplicates(subset=['song_id'], keep=False)\n",
235
+ "\n",
236
+ " sns.set_style('ticks')\n",
237
+ "\n",
238
+ " fig, ax = plt.subplots()\n",
239
+ " fig.set_size_inches(11, 8)\n",
240
+ " ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\n",
241
+ " plt.tight_layout()\n",
242
+ "\n",
243
+ " sns.boxplot(x=df[\"album_name\"], y=df[\"popularity\"], ax=ax)\n",
244
+ " fig.savefig('artist_popular_albums.png')\n",
245
+ " plt.show()\n",
246
+ " # plt.plot(projected_values.T)\n",
247
+ " # plt.legend(employee_data[\"Name\"])\n",
248
+ " # return employee_data, plt.gcf(), regression_values\n",
249
+ " return df\n",
250
+ "#Interface will include these buttons based on parameters in the function with a dataframe output\n",
251
+ "music_plots = gr.Interface(gradio_music_graph, [\"text\", \"text\", \"text\"], \n",
252
+ " [\"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\")\n",
253
+ "\n",
254
+ "music_plots.launch(debug=True)"
255
+ ],
256
+ "metadata": {
257
+ "id": "bUr9kLB-7CBj"
258
+ },
259
+ "execution_count": null,
260
+ "outputs": []
261
+ }
262
+ ],
263
+ "metadata": {
264
+ "kernelspec": {
265
+ "display_name": "Python 3",
266
+ "language": "python",
267
+ "name": "python3"
268
+ },
269
+ "language_info": {
270
+ "codemirror_mode": {
271
+ "name": "ipython",
272
+ "version": 3
273
+ },
274
+ "file_extension": ".py",
275
+ "mimetype": "text/x-python",
276
+ "name": "python",
277
+ "nbconvert_exporter": "python",
278
+ "pygments_lexer": "ipython3",
279
+ "version": "3.6.4"
280
+ },
281
+ "colab": {
282
+ "name": "Most Popular Albums Per Artist With Gradio.ipynb",
283
+ "provenance": [],
284
+ "collapsed_sections": []
285
+ }
286
+ },
287
+ "nbformat": 4,
288
+ "nbformat_minor": 0
289
+ }