834188divi Abdelrhman elruby commited on
Commit
4900e48
·
0 Parent(s):

Duplicate from Longliveruby/Spotify-Recommendation-System

Browse files

Co-authored-by: Abdelrhman elruby <Longliveruby@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.csv filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ .cache
2
+ __pycache__
3
+ Spotify/*
4
+ .streamlit/
Data/new_tracks.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f17cb1b33e44eba031f0b3646b6a67c7acd216db988671ab2812d77a975e39b3
3
+ size 24187
Data/sc.sav ADDED
Binary file (1.09 kB). View file
 
Data/streamlit.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:825f2815356f51fc0cf80bc7a3000612fab48daa925a32c0c3fe989555b2000b
3
+ size 186112931
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Abdelrhman Elruby
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Spotify Recommendation System
3
+ emoji: 📊
4
+ colorFrom: red
5
+ colorTo: gray
6
+ sdk: streamlit
7
+ sdk_version: 1.10.0
8
+ app_file: main.py
9
+ pinned: false
10
+ duplicated_from: Longliveruby/Spotify-Recommendation-System
11
+ ---
12
+ Check out the Github repository for more info: [Spotify-Recommendation-System](https://github.com/abdelrhmanelruby/Spotify-Recommendation-System)
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
main.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit_option_menu import option_menu
3
+ import streamlit.components.v1 as components
4
+ import time
5
+ from model import *
6
+
7
+
8
+
9
+ if 'model' not in st.session_state:
10
+ st.session_state.model = 'Model 1'
11
+ def update_radio2():
12
+ st.session_state.model=st.session_state.radio2
13
+ if 'genre' not in st.session_state:
14
+ st.session_state.genre=3
15
+ def update_num_genre():
16
+ st.session_state.genre=st.session_state.num_genre
17
+ if 'artist' not in st.session_state:
18
+ st.session_state.artist=5
19
+ def update_same_art():
20
+ st.session_state.artist=st.session_state.same_art
21
+ if 'model2' not in st.session_state:
22
+ st.session_state.model2= 'Spotify model'
23
+ def update_radio1():
24
+ st.session_state.model2 =st.session_state.radio1
25
+
26
+ if 'Region' not in st.session_state:
27
+ st.session_state.rg="US"
28
+ def update_Region():
29
+ st.session_state.rg=st.session_state.Region
30
+ if 'radio' not in st.session_state:
31
+ st.session_state.feature="Playlist"
32
+ def update_radio0():
33
+ st.session_state.feature=st.session_state.radio
34
+
35
+ if 'p_url' not in st.session_state:
36
+ st.session_state.p_url = 'Example: https://open.spotify.com/playlist/37i9dQZF1DX8FwnYE6PRvL?si=06ff6b38d4124af0'
37
+ def update_playlist_url():
38
+ st.session_state.p_url = st.session_state.playlist_url
39
+
40
+ if 's_url' not in st.session_state:
41
+ st.session_state.s_url = 'Example: https://open.spotify.com/track/5CQ30WqJwcep0pYcV4AMNc?si=ed4b04f153a24531'
42
+ def update_song_url():
43
+ st.session_state.s_url = st.session_state.song_url
44
+
45
+ if 'a_url' not in st.session_state:
46
+ st.session_state.a_url = 'Example: https://open.spotify.com/artist/3RNrq3jvMZxD9ZyoOZbQOD?si=UNAsX20kRpG89bxOO8o7ew'
47
+ def update_artist_url():
48
+ st.session_state.a_url = st.session_state.artist_url
49
+
50
+
51
+ def play_recomm():
52
+ if 'rs' in st.session_state:
53
+ del st.session_state.rs,st.session_state.err
54
+ try:
55
+ if len(pd.read_csv('Data/new_tracks.csv')) >= 200:
56
+ with st.spinner('Updating the dataset...'):
57
+ x=update_dataset()
58
+ st.success('{} New tracks were added to the dataset.'.format(x))
59
+ except:
60
+ st.error("The dataset update failed. ")
61
+ with st.spinner('Getting Recommendations...'):
62
+ res,err = playlist_model(st.session_state.p_url,st.session_state.model,st.session_state.genre,st.session_state.artist)
63
+ st.session_state.rs=res
64
+ st.session_state.err=err
65
+ if len(st.session_state.rs)>=1:
66
+ if st.session_state.model == 'Model 1' or st.session_state.model == 'Model 2':
67
+ st.success('Go to the Result page to view the top {} recommendations'.format(len(st.session_state.rs)))
68
+ else:
69
+ st.success('Go to the Result page to view the Spotify recommendations')
70
+ else:
71
+ st.error('Model failed. Check the log for more information.')
72
+
73
+ def art_recomm():
74
+ if 'rs' in st.session_state:
75
+ del st.session_state.rs,st.session_state.err
76
+ with st.spinner('Getting Recommendations...'):
77
+ res,err = top_tracks(st.session_state.a_url,st.session_state.rg)
78
+ st.session_state.rs=res
79
+ st.session_state.err=err
80
+ if len(st.session_state.rs)>=1:
81
+ st.success("Go to the Result page to view the Artist's top tracks")
82
+ else:
83
+ st.error('Model failed. Check the log for more information.')
84
+
85
+ def song_recomm():
86
+ if 'rs' in st.session_state:
87
+ del st.session_state.rs,st.session_state.err
88
+ with st.spinner('Getting Recommendations...'):
89
+ res,err = song_model(st.session_state.s_url,st.session_state.model,st.session_state.genre,st.session_state.artist)
90
+ st.session_state.rs=res
91
+ st.session_state.err=err
92
+ if len(st.session_state.rs)>=1:
93
+ if st.session_state.model == 'Model 1' or st.session_state.model == 'Model 2':
94
+ st.success('Go to the Result page to view the top {} recommendations'.format(len(st.session_state.rs)))
95
+ else:
96
+ st.success('Go to the Result page to view the Spotify recommendations')
97
+ else:
98
+ st.error('Model failed. Check the log for more information.')
99
+
100
+ def playlist_page():
101
+ st.subheader("User Playlist")
102
+ st.markdown('---')
103
+ playlist_uri = (st.session_state.playlist_url).split('/')[-1].split('?')[0]
104
+ uri_link = 'https://open.spotify.com/embed/playlist/' + playlist_uri
105
+ components.iframe(uri_link, height=300)
106
+ return
107
+
108
+ def song_page():
109
+ st.subheader("User Song")
110
+ st.markdown('---')
111
+ song_uri = (st.session_state.song_url).split('/')[-1].split('?')[0]
112
+ uri_link = 'https://open.spotify.com/embed/track/' + song_uri
113
+ components.iframe(uri_link, height=100)
114
+
115
+ def artist_page():
116
+ st.subheader("User Artist")
117
+ st.markdown('---')
118
+ artist_uri = (st.session_state.artist_url).split('/')[-1].split('?')[0]
119
+ uri_link = 'https://open.spotify.com/embed/artist/' + artist_uri
120
+ components.iframe(uri_link, height=80)
121
+
122
+
123
+ def spr_sidebar():
124
+ menu=option_menu(
125
+ menu_title=None,
126
+ options=['Home','Result','About','Log'],
127
+ icons=['house','book','info-square','terminal'],
128
+ menu_icon='cast',
129
+ default_index=0,
130
+ orientation='horizontal'
131
+ )
132
+ if menu=='Home':
133
+ st.session_state.app_mode = 'Home'
134
+ elif menu=='Result':
135
+ st.session_state.app_mode = 'Result'
136
+ elif menu=='About':
137
+ st.session_state.app_mode = 'About'
138
+ elif menu=='Log':
139
+ st.session_state.app_mode = 'Log'
140
+
141
+ def home_page():
142
+ st.session_state.radio=st.session_state.feature
143
+ st.session_state.radio2=st.session_state.model
144
+ st.session_state.num_genre=st.session_state.genre
145
+ st.session_state.same_art=st.session_state.artist
146
+ st.session_state.Region=st.session_state.rg
147
+
148
+
149
+ st.title('Spotify Recommendation System')
150
+ col,col2,col3=st.columns([2,2,3])
151
+ radio=col.radio("Feature",options=("Playlist","Song","Artist Top Tracks"),key='radio',on_change=update_radio0)
152
+ if radio =="Artist Top Tracks":
153
+ radio1=col2.radio("Model",options=["Spotify model"],key='radio1',on_change=update_radio1)
154
+ Region=col3.selectbox("Please Choose Region",index=58,key='Region',on_change=update_Region,options=('AD', 'AR', 'AU', 'AT', 'BE', 'BO', 'BR', 'BG', 'CA', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DK', 'DO', 'EC', 'SV', 'EE', 'FI', 'FR', 'DE', 'GR', 'GT', 'HN', 'HK', 'HU', 'IS', 'ID', 'IE', 'IT', 'JP', 'LV', 'LI', 'LT', 'LU', 'MY', 'MT', 'MX', 'MC', 'NL', 'NZ', 'NI', 'NO', 'PA', 'PY', 'PE', 'PH', 'PL', 'PT', 'SG', 'ES', 'SK', 'SE', 'CH', 'TW', 'TR', 'GB', 'US', 'UY'))
155
+ elif radio =="Playlist" or radio =="Song" :
156
+ radio2=col2.radio("Model",options=("Model 1","Model 2","Spotify Model"),key='radio2',on_change=update_radio2)
157
+ if st.session_state.radio2=="Model 1" or st.session_state.radio2=="Model 2":
158
+ num_genre=col3.selectbox("choose a number of genres to focus on",options=(1,2,3,4,5,6,7),index=2,key='num_genre',on_change=update_num_genre)
159
+ same_art=col3.selectbox("How many recommendations by the same artist",options=(1,2,3,4,5,7,10,15),index=3,key='same_art',on_change=update_same_art)
160
+
161
+
162
+ st.markdown("<br>", unsafe_allow_html=True)
163
+
164
+ if radio == "Playlist" :
165
+ st.session_state.playlist_url = st.session_state.p_url
166
+ Url = st.text_input(label="Playlist Url",key='playlist_url',on_change=update_playlist_url)
167
+ playlist_page()
168
+ state =st.button('Get Recommendations')
169
+ with st.expander("Here's how to find any Playlist URL in Spotify"):
170
+ st.write("""
171
+ - Search for Playlist on the Spotify app
172
+ - Right Click on the Playlist you like
173
+ - Click "Share"
174
+ - Choose "Copy link to playlist"
175
+ """)
176
+ st.markdown("<br>", unsafe_allow_html=True)
177
+ st.image('spotify_get_playlist_url.png')
178
+ if state:
179
+ play_recomm()
180
+ elif radio == "Song" :
181
+ st.session_state.song_url = st.session_state.s_url
182
+ Url = st.text_input(label="Song Url",key='song_url',on_change=update_song_url)
183
+ song_page()
184
+ state =st.button('Get Recommendations')
185
+ with st.expander("Here's how to find any Song URL in Spotify"):
186
+ st.write("""
187
+ - Search for Song on the Spotify app
188
+ - Right Click on the Song you like
189
+ - Click "Share"
190
+ - Choose "Copy link to Song"
191
+ """)
192
+ st.markdown("<br>", unsafe_allow_html=True)
193
+ st.image('spotify_get_song_url.png')
194
+ if state:
195
+ song_recomm()
196
+ elif radio == "Artist Top Tracks" :
197
+ st.session_state.artist_url = st.session_state.a_url
198
+ Url = st.text_input(label="Artist Url",key='artist_url',on_change=update_artist_url)
199
+ artist_page()
200
+ state =st.button('Get Recommendations')
201
+ with st.expander("Here's how to find any Artist URL in Spotify"):
202
+ st.write("""
203
+ - Search for Artist on the Spotify app
204
+ - Right Click on the Artist you like
205
+ - Click "Share"
206
+ - Choose "Copy link to Artist"
207
+ """)
208
+ st.markdown("<br>", unsafe_allow_html=True)
209
+ st.image('spotify_get_artist_url.png')
210
+ if state:
211
+ art_recomm()
212
+
213
+ def result_page():
214
+ if 'rs' not in st.session_state:
215
+ st.error('Please select a model on the Home page and run Get Recommendations')
216
+ else:
217
+ st.success('Top {} recommendations'.format(len(st.session_state.rs)))
218
+ i=0
219
+ for uri in st.session_state.rs:
220
+ uri_link = "https://open.spotify.com/embed/track/" + uri + "?utm_source=generator&theme=0"
221
+ components.iframe(uri_link, height=80)
222
+ i+=1
223
+ if i%5==0:
224
+ time.sleep(1)
225
+ def Log_page():
226
+ log=st.checkbox('Display Output', True, key='display_output')
227
+ if log == True:
228
+ if 'err' in st.session_state:
229
+ st.write(st.session_state.err)
230
+ with open('Data/streamlit.csv') as f:
231
+ st.download_button('Download Dataset', f,file_name='streamlit.csv')
232
+ def About_page():
233
+ st.header('Development')
234
+ """
235
+ Check out the [repository](https://github.com/abdelrhmanelruby/Spotify-Recommendation-System) for the source code and approaches, and don't hesitate to contact me if you have any questions. I'm excited to read your review.
236
+ [Github](https://github.com/abdelrhmanelruby) [Linkedin](https://www.linkedin.com/in/abdelrhmanelruby/) Email : abdelrhmanelruby@gmail.com
237
+ """
238
+ st.subheader('Spotify Million Playlist Dataset')
239
+ """
240
+ For this project, I'm using the Million Playlist Dataset, which, as its name implies, consists of one million playlists.
241
+ contains a number of songs, and some metadata is included as well, such as the name of the playlist, duration, number of songs, number of artists, etc.
242
+ """
243
+
244
+ """
245
+ It is created by sampling playlists from the billions of playlists that Spotify users have created over the years.
246
+ Playlists that meet the following criteria were selected at random:
247
+ - Created by a user that resides in the United States and is at least 13 years old
248
+ - Was a public playlist at the time the MPD was generated
249
+ - Contains at least 5 tracks
250
+ - Contains no more than 250 tracks
251
+ - Contains at least 3 unique artists
252
+ - Contains at least 2 unique albums
253
+ - Has no local tracks (local tracks are non-Spotify tracks that a user has on their local device
254
+ - Has at least one follower (not including the creator
255
+ - Was created after January 1, 2010 and before December 1, 2017
256
+ - Does not have an offensive title
257
+ - Does not have an adult-oriented title if the playlist was created by a user under 18 years of age
258
+
259
+ Information about the Dataset [here](https://www.aicrowd.com/challenges/spotify-million-playlist-dataset-challenge)
260
+ """
261
+ st.subheader('Audio Features Explanation')
262
+ """
263
+ | Variable | Description |
264
+ | :----: | :---: |
265
+ | Acousticness | A confidence measure from 0.0 to 1.0 of whether the track is acoustic. 1.0 represents high confidence the track is acoustic. |
266
+ | Danceability | Danceability describes how suitable a track is for dancing based on a combination of musical elements including tempo, rhythm stability, beat strength, and overall regularity. A value of 0.0 is least danceable and 1.0 is most danceable. |
267
+ | Energy | Energy is a measure from 0.0 to 1.0 and represents a perceptual measure of intensity and activity. Typically, energetic tracks feel fast, loud, and noisy. For example, death metal has high energy, while a Bach prelude scores low on the scale. Perceptual features contributing to this attribute include dynamic range, perceived loudness, timbre, onset rate, and general entropy. |
268
+ | Instrumentalness | Predicts whether a track contains no vocals. "Ooh" and "aah" sounds are treated as instrumental in this context. Rap or spoken word tracks are clearly "vocal". The closer the instrumentalness value is to 1.0, the greater likelihood the track contains no vocal content. Values above 0.5 are intended to represent instrumental tracks, but confidence is higher as the value approaches 1.0. |
269
+ | Key | The key the track is in. Integers map to pitches using standard Pitch Class notation. E.g. 0 = C, 1 = C♯/D♭, 2 = D, and so on. If no key was detected, the value is -1. |
270
+ | Liveness | Detects the presence of an audience in the recording. Higher liveness values represent an increased probability that the track was performed live. A value above 0.8 provides strong likelihood that the track is live. |
271
+ | Loudness | The overall loudness of a track in decibels (dB). Loudness values are averaged across the entire track and are useful for comparing relative loudness of tracks. Loudness is the quality of a sound that is the primary psychological correlate of physical strength (amplitude). Values typically range between -60 and 0 db. |
272
+ | Mode | Mode indicates the modality (major or minor) of a track, the type of scale from which its melodic content is derived. Major is represented by 1 and minor is 0. |
273
+ | Speechiness | Speechiness detects the presence of spoken words in a track. The more exclusively speech-like the recording (e.g. talk show, audio book, poetry), the closer to 1.0 the attribute value. Values above 0.66 describe tracks that are probably made entirely of spoken words. Values between 0.33 and 0.66 describe tracks that may contain both music and speech, either in sections or layered, including such cases as rap music. Values below 0.33 most likely represent music and other non-speech-like tracks. |
274
+ | Tempo | The overall estimated tempo of a track in beats per minute (BPM). In musical terminology, tempo is the speed or pace of a given piece and derives directly from the average beat duration. |
275
+ | Time Signature | An estimated time signature. The time signature (meter) is a notational convention to specify how many beats are in each bar (or measure). The time signature ranges from 3 to 7 indicating time signatures of "3/4", to "7/4". |
276
+ | Valence | A measure from 0.0 to 1.0 describing the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry). |
277
+
278
+ Information about features: [here](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-audio-features)
279
+ """
280
+
281
+ def main():
282
+ spr_sidebar()
283
+ if st.session_state.app_mode == 'Home':
284
+ home_page()
285
+ if st.session_state.app_mode == 'Result':
286
+ result_page()
287
+ if st.session_state.app_mode == 'About' :
288
+ About_page()
289
+ if st.session_state.app_mode == 'Log':
290
+ Log_page()
291
+ # Run main()
292
+ if __name__ == '__main__':
293
+ main()
model.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import spotipy
3
+ from spotipy.oauth2 import SpotifyOAuth, SpotifyClientCredentials
4
+ import yaml
5
+ import re
6
+ from sklearn.feature_extraction.text import TfidfVectorizer
7
+ from sklearn.metrics.pairwise import cosine_similarity
8
+ from sklearn.preprocessing import MinMaxScaler
9
+ import pickle
10
+ import streamlit as st
11
+ import os
12
+
13
+ def playlist_model(url, model, max_gen=3, same_art=5):
14
+ log = []
15
+ Fresult = []
16
+ try:
17
+ log.append('Start logging')
18
+ uri = url.split('/')[-1].split('?')[0]
19
+ try:
20
+ log.append('spotify local method')
21
+ stream = open("Spotify/Spotify.yaml")
22
+ spotify_details = yaml.safe_load(stream)
23
+ auth_manager = SpotifyClientCredentials(client_id=spotify_details['Client_id'], client_secret=spotify_details['client_secret'])
24
+ except:
25
+ log.append('spotify .streamlit method')
26
+ try:
27
+ Client_id=st.secrets["Client_ID"]
28
+ client_secret=st.secrets["Client_secret"]
29
+ auth_manager = SpotifyClientCredentials(client_id=Client_id, client_secret=client_secret)
30
+ except:
31
+ log.append('spotify hug method')
32
+ Client_id=os.environ['Client_ID']
33
+ client_secret=os.environ['Client_secret']
34
+ auth_manager = SpotifyClientCredentials(client_id=Client_id, client_secret=client_secret)
35
+ sp = spotipy.client.Spotify(auth_manager=auth_manager)
36
+
37
+ if model == 'Spotify Model':
38
+ def get_IDs(user, playlist_id):
39
+ try:
40
+ log.append('start playlist extraction')
41
+ track_ids = []
42
+ playlist = sp.user_playlist(user, playlist_id)
43
+ for item in playlist['tracks']['items']:
44
+ track = item['track']
45
+ track_ids.append(track['id'])
46
+ return track_ids
47
+ except Exception as e:
48
+ log.append('Failed to load the playlist')
49
+ log.append(e)
50
+
51
+ track_ids = get_IDs('Ruby', uri)
52
+ track_ids_uni = list(set(track_ids))
53
+ log.append('Starting Spotify Model')
54
+ Spotifyresult = pd.DataFrame()
55
+ for i in range(len(track_ids_uni)-5):
56
+ if len(Spotifyresult) >= 50:
57
+ break
58
+ try:
59
+ ff = sp.recommendations(seed_tracks=list(track_ids_uni[i:i+5]), limit=5)
60
+ except Exception as e:
61
+ log.append(e)
62
+ continue
63
+ for z in range(5):
64
+ result = pd.DataFrame([z+(5*i)+1])
65
+ result['uri'] = ff['tracks'][z]['id']
66
+ Spotifyresult = pd.concat([Spotifyresult, result], axis=0)
67
+ Spotifyresult.drop_duplicates(subset=['uri'], inplace=True,keep='first')
68
+ Fresult = Spotifyresult.uri[:50]
69
+
70
+ log.append('Model run successfully')
71
+ return Fresult, log
72
+
73
+ lendf=len(pd.read_csv('Data/streamlit.csv',usecols=['track_uri']))
74
+ dtypes = {'track_uri': 'object', 'artist_uri': 'object', 'album_uri': 'object', 'danceability': 'float16', 'energy': 'float16', 'key': 'float16',
75
+ 'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
76
+ 'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
77
+ 'Track_release_date': 'int8', 'Track_pop': 'int8', 'Artist_pop': 'int8', 'Artist_genres': 'object'}
78
+ col_name= ['track_uri', 'artist_uri', 'album_uri', 'danceability', 'energy', 'key',
79
+ 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness',
80
+ 'liveness', 'valence', 'tempo', 'duration_ms', 'time_signature',
81
+ 'Track_release_date', 'Track_pop', 'Artist_pop', 'Artist_genres']
82
+
83
+ try:
84
+ def get_IDs(user, playlist_id):
85
+ log.append('start playlist extraction')
86
+ track_ids = []
87
+ artist_id = []
88
+ playlist = sp.user_playlist(user, playlist_id)
89
+ for item in playlist['tracks']['items']:
90
+ track = item['track']
91
+ track_ids.append(track['id'])
92
+ artist = item['track']['artists']
93
+ artist_id.append(artist[0]['id'])
94
+ return track_ids, artist_id
95
+ except Exception as e:
96
+ log.append('Failed to load the playlist')
97
+ log.append(e)
98
+
99
+ track_ids, artist_id = get_IDs('Ruby', uri)
100
+ log.append("Number of Track : {}".format(len(track_ids)))
101
+
102
+ artist_id_uni = list(set(artist_id))
103
+ track_ids_uni = list(set(track_ids))
104
+ log.append("Number of unique Artists : {}".format(len(artist_id_uni)))
105
+ log.append("Number of unique Tracks : {}".format(len(track_ids_uni)))
106
+
107
+ def extract(track_ids_uni, artist_id_uni):
108
+ err = []
109
+ err.append('Start audio features extraction')
110
+ audio_features = pd.DataFrame()
111
+ for i in range(0, len(track_ids_uni), 25):
112
+ try:
113
+ track_feature = sp.audio_features(track_ids_uni[i:i+25])
114
+ track_df = pd.DataFrame(track_feature)
115
+ audio_features = pd.concat([audio_features, track_df], axis=0)
116
+ except Exception as e:
117
+ err.append(e)
118
+ continue
119
+ err.append('Start track features extraction')
120
+ track_ = pd.DataFrame()
121
+ for i in range(0, len(track_ids_uni), 25):
122
+ try:
123
+ track_features = sp.tracks(track_ids_uni[i:i+25])
124
+ for x in range(25):
125
+ track_pop = pd.DataFrame([track_ids_uni[i+x]], columns=['Track_uri'])
126
+ track_pop['Track_release_date'] = track_features['tracks'][x]['album']['release_date']
127
+ track_pop['Track_pop'] = track_features['tracks'][x]["popularity"]
128
+ track_pop['Artist_uri'] = track_features['tracks'][x]['artists'][0]['id']
129
+ track_pop['Album_uri'] = track_features['tracks'][x]['album']['id']
130
+ track_ = pd.concat([track_, track_pop], axis=0)
131
+ except Exception as e:
132
+ err.append(e)
133
+ continue
134
+ err.append('Start artist features extraction')
135
+ artist_ = pd.DataFrame()
136
+ for i in range(0, len(artist_id_uni), 25):
137
+ try:
138
+ artist_features = sp.artists(artist_id_uni[i:i+25])
139
+ for x in range(25):
140
+ artist_df = pd.DataFrame([artist_id_uni[i+x]], columns=['Artist_uri'])
141
+ artist_pop = artist_features['artists'][x]["popularity"]
142
+ artist_genres = artist_features['artists'][x]["genres"]
143
+ artist_df["Artist_pop"] = artist_pop
144
+ if artist_genres:
145
+ artist_df["genres"] = " ".join([re.sub(' ', '_', i) for i in artist_genres])
146
+ else:
147
+ artist_df["genres"] = "unknown"
148
+ artist_ = pd.concat([artist_, artist_df], axis=0)
149
+ except Exception as e:
150
+ err.append(e)
151
+ continue
152
+ try:
153
+ test = pd.DataFrame(
154
+ track_, columns=['Track_uri', 'Artist_uri', 'Album_uri'])
155
+
156
+ test.rename(columns={'Track_uri': 'track_uri',
157
+ 'Artist_uri': 'artist_uri', 'Album_uri': 'album_uri'}, inplace=True)
158
+
159
+ audio_features.drop(
160
+ columns=['type', 'uri', 'track_href', 'analysis_url'], axis=1, inplace=True)
161
+
162
+ test = pd.merge(test, audio_features,
163
+ left_on="track_uri", right_on="id", how='outer')
164
+ test = pd.merge(test, track_, left_on="track_uri",
165
+ right_on="Track_uri", how='outer')
166
+ test = pd.merge(test, artist_, left_on="artist_uri",
167
+ right_on="Artist_uri", how='outer')
168
+
169
+ test.rename(columns={'genres': 'Artist_genres'}, inplace=True)
170
+
171
+ test.drop(columns=['Track_uri', 'Artist_uri_x',
172
+ 'Artist_uri_y', 'Album_uri', 'id'], axis=1, inplace=True)
173
+
174
+ test.dropna(axis=0, inplace=True)
175
+ test['Track_pop'] = test['Track_pop'].apply(lambda x: int(x/5))
176
+ test['Artist_pop'] = test['Artist_pop'].apply(lambda x: int(x/5))
177
+ test['Track_release_date'] = test['Track_release_date'].apply(lambda x: x.split('-')[0])
178
+ test['Track_release_date'] = test['Track_release_date'].astype('int16')
179
+ test['Track_release_date'] = test['Track_release_date'].apply(lambda x: int(x/50))
180
+
181
+ test[['danceability', 'energy', 'key', 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'time_signature']] = test[[
182
+ 'danceability', 'energy', 'key', 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'time_signature']].astype('float16')
183
+ test[['duration_ms']] = test[['duration_ms']].astype('float32')
184
+ test[['Track_release_date', 'Track_pop', 'Artist_pop']] = test[[
185
+ 'Track_release_date', 'Track_pop', 'Artist_pop']].astype('int8')
186
+ except Exception as e:
187
+ err.append(e)
188
+ err.append('Finish extraction')
189
+ return test, err
190
+ test, err = extract(track_ids_uni, artist_id_uni)
191
+
192
+ for i in err:
193
+ log.append(i)
194
+ del err
195
+ grow = test.copy()
196
+ test['Artist_genres'] = test['Artist_genres'].apply(lambda x: x.split(" "))
197
+ tfidf = TfidfVectorizer(max_features=max_gen)
198
+ tfidf_matrix = tfidf.fit_transform(test['Artist_genres'].apply(lambda x: " ".join(x)))
199
+ genre_df = pd.DataFrame(tfidf_matrix.toarray())
200
+ genre_df.columns = ['genre' + "|" +i for i in tfidf.get_feature_names_out()]
201
+ genre_df = genre_df.astype('float16')
202
+ test.drop(columns=['Artist_genres'], axis=1, inplace=True)
203
+ test = pd.concat([test.reset_index(drop=True),genre_df.reset_index(drop=True)], axis=1)
204
+ Fresult = pd.DataFrame()
205
+ x = 1
206
+ for i in range(int(lendf/2), lendf+1, int(lendf/2)):
207
+ try:
208
+ df = pd.read_csv('Data/streamlit.csv',names= col_name,dtype=dtypes,skiprows=x,nrows=i)
209
+ log.append('reading data frame chunks from {} to {}'.format(x,i))
210
+ except Exception as e:
211
+ log.append('Failed to load grow')
212
+ log.append(e)
213
+ grow = grow[~grow['track_uri'].isin(df['track_uri'].values)]
214
+ df = df[~df['track_uri'].isin(test['track_uri'].values)]
215
+ df['Artist_genres'] = df['Artist_genres'].apply(lambda x: x.split(" "))
216
+ tfidf_matrix = tfidf.transform(df['Artist_genres'].apply(lambda x: " ".join(x)))
217
+ genre_df = pd.DataFrame(tfidf_matrix.toarray())
218
+ genre_df.columns = ['genre' + "|" +i for i in tfidf.get_feature_names_out()]
219
+ genre_df = genre_df.astype('float16')
220
+ df.drop(columns=['Artist_genres'], axis=1, inplace=True)
221
+ df = pd.concat([df.reset_index(drop=True),
222
+ genre_df.reset_index(drop=True)], axis=1)
223
+ del genre_df
224
+ try:
225
+ df.drop(columns=['genre|unknown'], axis=1, inplace=True)
226
+ test.drop(columns=['genre|unknown'], axis=1, inplace=True)
227
+ except:
228
+ log.append('genre|unknown not found')
229
+ log.append('Scaling the data .....')
230
+ if x == 1:
231
+ sc = pickle.load(open('Data/sc.sav','rb'))
232
+ df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
233
+ test.iloc[:, 3:19] = sc.transform(test.iloc[:, 3:19])
234
+ log.append("Creating playlist vector")
235
+ playvec = pd.DataFrame(test.sum(axis=0)).T
236
+ else:
237
+ df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
238
+ x = i
239
+ if model == 'Model 1':
240
+ df['sim']=cosine_similarity(df.drop(['track_uri', 'artist_uri', 'album_uri'], axis = 1),playvec.drop(['track_uri', 'artist_uri', 'album_uri'], axis = 1))
241
+ df['sim2']=cosine_similarity(df.iloc[:,16:-1],playvec.iloc[:,16:])
242
+ df['sim3']=cosine_similarity(df.iloc[:,19:-2],playvec.iloc[:,19:])
243
+ df = df.sort_values(['sim3','sim2','sim'],ascending = False,kind='stable').groupby('artist_uri').head(same_art).head(50)
244
+ Fresult = pd.concat([Fresult, df], axis=0)
245
+ Fresult = Fresult.sort_values(['sim3', 'sim2', 'sim'],ascending=False,kind='stable')
246
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
247
+ Fresult = Fresult.groupby('artist_uri').head(same_art).head(50)
248
+ elif model == 'Model 2':
249
+ df['sim'] = cosine_similarity(df.iloc[:, 3:16], playvec.iloc[:, 3:16])
250
+ df['sim2'] = cosine_similarity(df.loc[:, df.columns.str.startswith('T') | df.columns.str.startswith('A')], playvec.loc[:, playvec.columns.str.startswith('T') | playvec.columns.str.startswith('A')])
251
+ df['sim3'] = cosine_similarity(df.loc[:, df.columns.str.startswith('genre')], playvec.loc[:, playvec.columns.str.startswith('genre')])
252
+ df['sim4'] = (df['sim']+df['sim2']+df['sim3'])/3
253
+ df = df.sort_values(['sim4'], ascending=False,kind='stable').groupby('artist_uri').head(same_art).head(50)
254
+ Fresult = pd.concat([Fresult, df], axis=0)
255
+ Fresult = Fresult.sort_values(['sim4'], ascending=False,kind='stable')
256
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
257
+ Fresult = Fresult.groupby('artist_uri').head(same_art).head(50)
258
+ del test
259
+ try:
260
+ del df
261
+ log.append('Getting Result')
262
+ except:
263
+ log.append('Getting Result')
264
+ if model == 'Model 1':
265
+ Fresult = Fresult.sort_values(['sim3', 'sim2', 'sim'],ascending=False,kind='stable')
266
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
267
+ Fresult = Fresult.groupby('artist_uri').head(same_art).track_uri.head(50)
268
+ elif model == 'Model 2':
269
+ Fresult = Fresult.sort_values(['sim4'], ascending=False,kind='stable')
270
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
271
+ Fresult = Fresult.groupby('artist_uri').head(same_art).track_uri.head(50)
272
+ log.append('{} New Tracks Found'.format(len(grow)))
273
+ if(len(grow)>=1):
274
+ try:
275
+ new=pd.read_csv('Data/new_tracks.csv',dtype=dtypes)
276
+ new=pd.concat([new, grow], axis=0)
277
+ new=new[new.Track_pop >0]
278
+ new.drop_duplicates(subset=['track_uri'], inplace=True,keep='last')
279
+ new.to_csv('Data/new_tracks.csv',index=False)
280
+ except:
281
+ grow.to_csv('Data/new_tracks.csv', index=False)
282
+ log.append('Model run successfully')
283
+ except Exception as e:
284
+ log.append("Model Failed")
285
+ log.append(e)
286
+ return Fresult, log
287
+
288
+
289
+
290
+ def top_tracks(url,region):
291
+ log = []
292
+ Fresult = []
293
+ uri = url.split('/')[-1].split('?')[0]
294
+ try:
295
+ log.append('spotify local method')
296
+ stream = open("Spotify/Spotify.yaml")
297
+ spotify_details = yaml.safe_load(stream)
298
+ auth_manager = SpotifyClientCredentials(client_id=spotify_details['Client_id'], client_secret=spotify_details['client_secret'])
299
+ except:
300
+ log.append('spotify .streamlit method')
301
+ try:
302
+ Client_id=st.secrets["Client_ID"]
303
+ client_secret=st.secrets["Client_secret"]
304
+ auth_manager = SpotifyClientCredentials(client_id=Client_id, client_secret=client_secret)
305
+ except:
306
+ log.append('spotify hug method')
307
+ Client_id=os.environ['Client_ID']
308
+ client_secret=os.environ['Client_secret']
309
+ auth_manager = SpotifyClientCredentials(client_id=Client_id, client_secret=client_secret)
310
+ sp = spotipy.client.Spotify(auth_manager=auth_manager)
311
+ try:
312
+ log.append('Starting Spotify Model')
313
+ top=sp.artist_top_tracks(uri,country=region)
314
+ for i in range(10) :
315
+ Fresult.append(top['tracks'][i]['id'])
316
+ log.append('Model run successfully')
317
+ except Exception as e:
318
+ log.append("Model Failed")
319
+ log.append(e)
320
+ return Fresult,log
321
+
322
+ def song_model(url, model, max_gen=3, same_art=5):
323
+ log = []
324
+ Fresult = []
325
+ try:
326
+ log.append('Start logging')
327
+ uri = url.split('/')[-1].split('?')[0]
328
+ try:
329
+ log.append('spotify local method')
330
+ stream = open("Spotify/Spotify.yaml")
331
+ spotify_details = yaml.safe_load(stream)
332
+ auth_manager = SpotifyClientCredentials(client_id=spotify_details['Client_id'], client_secret=spotify_details['client_secret'])
333
+ except:
334
+ log.append('spotify .streamlit method')
335
+ try:
336
+ Client_id=st.secrets["Client_ID"]
337
+ client_secret=st.secrets["Client_secret"]
338
+ auth_manager = SpotifyClientCredentials(client_id=Client_id, client_secret=client_secret)
339
+ except:
340
+ log.append('spotify hug method')
341
+ Client_id=os.environ['Client_ID']
342
+ client_secret=os.environ['Client_secret']
343
+ auth_manager = SpotifyClientCredentials(client_id=Client_id, client_secret=client_secret)
344
+ sp = spotipy.client.Spotify(auth_manager=auth_manager)
345
+
346
+ if model == 'Spotify Model':
347
+ log.append('Starting Spotify Model')
348
+ aa=sp.recommendations(seed_tracks=[uri], limit=25)
349
+ for i in range(25):
350
+ Fresult.append(aa['tracks'][i]['id'])
351
+ log.append('Model run successfully')
352
+ return Fresult, log
353
+ lendf=len(pd.read_csv('Data/streamlit.csv',usecols=['track_uri']))
354
+ dtypes = {'track_uri': 'object', 'artist_uri': 'object', 'album_uri': 'object', 'danceability': 'float16', 'energy': 'float16', 'key': 'float16',
355
+ 'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
356
+ 'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
357
+ 'Track_release_date': 'int8', 'Track_pop': 'int8', 'Artist_pop': 'int8', 'Artist_genres': 'object'}
358
+ col_name= ['track_uri', 'artist_uri', 'album_uri', 'danceability', 'energy', 'key',
359
+ 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness',
360
+ 'liveness', 'valence', 'tempo', 'duration_ms', 'time_signature',
361
+ 'Track_release_date', 'Track_pop', 'Artist_pop', 'Artist_genres']
362
+ log.append('Start audio features extraction')
363
+ audio_features = pd.DataFrame(sp.audio_features([uri]))
364
+ log.append('Start track features extraction')
365
+ track_ = pd.DataFrame()
366
+ track_features = sp.tracks([uri])
367
+ track_pop = pd.DataFrame([uri], columns=['Track_uri'])
368
+ track_pop['Track_release_date'] = track_features['tracks'][0]['album']['release_date']
369
+ track_pop['Track_pop'] = track_features['tracks'][0]["popularity"]
370
+ track_pop['Artist_uri'] = track_features['tracks'][0]['artists'][0]['id']
371
+ track_pop['Album_uri'] = track_features['tracks'][0]['album']['id']
372
+ track_ = pd.concat([track_, track_pop], axis=0)
373
+ log.append('Start artist features extraction')
374
+ artist_id_uni=list(track_['Artist_uri'])
375
+ artist_ = pd.DataFrame()
376
+ artist_features = sp.artists(artist_id_uni)
377
+ artist_df = pd.DataFrame(artist_id_uni, columns=['Artist_uri'])
378
+ artist_pop = artist_features['artists'][0]["popularity"]
379
+ artist_genres = artist_features['artists'][0]["genres"]
380
+ artist_df["Artist_pop"] = artist_pop
381
+ if artist_genres:
382
+ artist_df["genres"] = " ".join([re.sub(' ', '_', i) for i in artist_genres])
383
+ else:
384
+ artist_df["genres"] = "unknown"
385
+ artist_ = pd.concat([artist_, artist_df], axis=0)
386
+ try:
387
+ test = pd.DataFrame(track_, columns=['Track_uri', 'Artist_uri', 'Album_uri'])
388
+ test.rename(columns={'Track_uri': 'track_uri','Artist_uri': 'artist_uri', 'Album_uri': 'album_uri'}, inplace=True)
389
+ audio_features.drop(columns=['type', 'uri', 'track_href', 'analysis_url'], axis=1, inplace=True)
390
+ test = pd.merge(test, audio_features,left_on="track_uri", right_on="id", how='outer')
391
+ test = pd.merge(test, track_, left_on="track_uri",right_on="Track_uri", how='outer')
392
+ test = pd.merge(test, artist_, left_on="artist_uri",right_on="Artist_uri", how='outer')
393
+ test.rename(columns={'genres': 'Artist_genres'}, inplace=True)
394
+ test.drop(columns=['Track_uri', 'Artist_uri_x','Artist_uri_y', 'Album_uri', 'id'], axis=1, inplace=True)
395
+ test.dropna(axis=0, inplace=True)
396
+ test['Track_pop'] = test['Track_pop'].apply(lambda x: int(x/5))
397
+ test['Artist_pop'] = test['Artist_pop'].apply(lambda x: int(x/5))
398
+ test['Track_release_date'] = test['Track_release_date'].apply(lambda x: x.split('-')[0])
399
+ test['Track_release_date'] = test['Track_release_date'].astype('int16')
400
+ test['Track_release_date'] = test['Track_release_date'].apply(lambda x: int(x/50))
401
+ test[['danceability', 'energy', 'key', 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'time_signature']] = test[['danceability', 'energy', 'key', 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'time_signature']].astype('float16')
402
+ test[['duration_ms']] = test[['duration_ms']].astype('float32')
403
+ test[['Track_release_date', 'Track_pop', 'Artist_pop']] = test[['Track_release_date', 'Track_pop', 'Artist_pop']].astype('int8')
404
+ except Exception as e:
405
+ log.append(e)
406
+ log.append('Finish extraction')
407
+ grow = test.copy()
408
+ test['Artist_genres'] = test['Artist_genres'].apply(lambda x: x.split(" "))
409
+ tfidf = TfidfVectorizer(max_features=max_gen)
410
+ tfidf_matrix = tfidf.fit_transform(test['Artist_genres'].apply(lambda x: " ".join(x)))
411
+ genre_df = pd.DataFrame(tfidf_matrix.toarray())
412
+ genre_df.columns = ['genre' + "|" +i for i in tfidf.get_feature_names_out()]
413
+ genre_df = genre_df.astype('float16')
414
+ test.drop(columns=['Artist_genres'], axis=1, inplace=True)
415
+ test = pd.concat([test.reset_index(drop=True),genre_df.reset_index(drop=True)], axis=1)
416
+ Fresult = pd.DataFrame()
417
+ x = 1
418
+ for i in range(int(lendf/2), lendf+1, int(lendf/2)):
419
+ try:
420
+ df = pd.read_csv('Data/streamlit.csv',names= col_name,dtype=dtypes,skiprows=x,nrows=i)
421
+ log.append('reading data frame chunks from {} to {}'.format(x,i))
422
+ except Exception as e:
423
+ log.append('Failed to load grow')
424
+ log.append(e)
425
+ grow = grow[~grow['track_uri'].isin(df['track_uri'].values)]
426
+ df = df[~df['track_uri'].isin(test['track_uri'].values)]
427
+ df['Artist_genres'] = df['Artist_genres'].apply(lambda x: x.split(" "))
428
+ tfidf_matrix = tfidf.transform(df['Artist_genres'].apply(lambda x: " ".join(x)))
429
+ genre_df = pd.DataFrame(tfidf_matrix.toarray())
430
+ genre_df.columns = ['genre' + "|" +i for i in tfidf.get_feature_names_out()]
431
+ genre_df = genre_df.astype('float16')
432
+ df.drop(columns=['Artist_genres'], axis=1, inplace=True)
433
+ df = pd.concat([df.reset_index(drop=True),
434
+ genre_df.reset_index(drop=True)], axis=1)
435
+ del genre_df
436
+ try:
437
+ df.drop(columns=['genre|unknown'], axis=1, inplace=True)
438
+ test.drop(columns=['genre|unknown'], axis=1, inplace=True)
439
+ except:
440
+ log.append('genre|unknown not found')
441
+ log.append('Scaling the data .....')
442
+ if x == 1:
443
+ sc = pickle.load(open('Data/sc.sav','rb'))
444
+ df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
445
+ test.iloc[:, 3:19] = sc.transform(test.iloc[:, 3:19])
446
+ log.append("Creating playlist vector")
447
+ playvec = pd.DataFrame(test.sum(axis=0)).T
448
+ else:
449
+ df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
450
+ x = i
451
+ if model == 'Model 1':
452
+ df['sim']=cosine_similarity(df.drop(['track_uri', 'artist_uri', 'album_uri'], axis = 1),playvec.drop(['track_uri', 'artist_uri', 'album_uri'], axis = 1))
453
+ df['sim2']=cosine_similarity(df.iloc[:,16:-1],playvec.iloc[:,16:])
454
+ df['sim3']=cosine_similarity(df.iloc[:,19:-2],playvec.iloc[:,19:])
455
+ df = df.sort_values(['sim3','sim2','sim'],ascending = False,kind='stable').groupby('artist_uri').head(same_art).head(50)
456
+ Fresult = pd.concat([Fresult, df], axis=0)
457
+ Fresult = Fresult.sort_values(['sim3', 'sim2', 'sim'],ascending=False,kind='stable')
458
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
459
+ Fresult = Fresult.groupby('artist_uri').head(same_art).head(50)
460
+ elif model == 'Model 2':
461
+ df['sim'] = cosine_similarity(df.iloc[:, 3:16], playvec.iloc[:, 3:16])
462
+ df['sim2'] = cosine_similarity(df.loc[:, df.columns.str.startswith('T') | df.columns.str.startswith('A')], playvec.loc[:, playvec.columns.str.startswith('T') | playvec.columns.str.startswith('A')])
463
+ df['sim3'] = cosine_similarity(df.loc[:, df.columns.str.startswith('genre')], playvec.loc[:, playvec.columns.str.startswith('genre')])
464
+ df['sim4'] = (df['sim']+df['sim2']+df['sim3'])/3
465
+ df = df.sort_values(['sim4'], ascending=False,kind='stable').groupby('artist_uri').head(same_art).head(50)
466
+ Fresult = pd.concat([Fresult, df], axis=0)
467
+ Fresult = Fresult.sort_values(['sim4'], ascending=False,kind='stable')
468
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
469
+ Fresult = Fresult.groupby('artist_uri').head(same_art).head(50)
470
+ del test
471
+ try:
472
+ del df
473
+ log.append('Getting Result')
474
+ except:
475
+ log.append('Getting Result')
476
+ if model == 'Model 1':
477
+ Fresult = Fresult.sort_values(['sim3', 'sim2', 'sim'],ascending=False,kind='stable')
478
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
479
+ Fresult = Fresult.groupby('artist_uri').head(same_art).track_uri.head(50)
480
+ elif model == 'Model 2':
481
+ Fresult = Fresult.sort_values(['sim4'], ascending=False,kind='stable')
482
+ Fresult.drop_duplicates(subset=['track_uri'], inplace=True,keep='first')
483
+ Fresult = Fresult.groupby('artist_uri').head(same_art).track_uri.head(50)
484
+ log.append('{} New Tracks Found'.format(len(grow)))
485
+ if(len(grow)>=1):
486
+ try:
487
+ new=pd.read_csv('Data/new_tracks.csv',dtype=dtypes)
488
+ new=pd.concat([new, grow], axis=0)
489
+ new=new[new.Track_pop >0]
490
+ new.drop_duplicates(subset=['track_uri'], inplace=True,keep='last')
491
+ new.to_csv('Data/new_tracks.csv',index=False)
492
+ except:
493
+ grow.to_csv('Data/new_tracks.csv', index=False)
494
+ log.append('Model run successfully')
495
+ except Exception as e:
496
+ log.append("Model Failed")
497
+ log.append(e)
498
+ return Fresult, log
499
+
500
+ def update_dataset():
501
+ col_name= ['track_uri', 'artist_uri', 'album_uri', 'danceability', 'energy', 'key',
502
+ 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness',
503
+ 'liveness', 'valence', 'tempo', 'duration_ms', 'time_signature',
504
+ 'Track_release_date', 'Track_pop', 'Artist_pop', 'Artist_genres']
505
+ dtypes = {'track_uri': 'object', 'artist_uri': 'object', 'album_uri': 'object', 'danceability': 'float16', 'energy': 'float16', 'key': 'float16',
506
+ 'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
507
+ 'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
508
+ 'Track_release_date': 'int8', 'Track_pop': 'int8', 'Artist_pop': 'int8', 'Artist_genres': 'object'}
509
+ df = pd.read_csv('Data/streamlit.csv',dtype=dtypes)
510
+ grow = pd.read_csv('Data/new_tracks.csv',dtype=dtypes)
511
+ cur = len(df)
512
+ df=pd.concat([df,grow],axis=0)
513
+ grow=pd.DataFrame(columns=col_name)
514
+ grow.to_csv('Data/new_tracks.csv',index=False)
515
+ df=df[df.Track_pop >0]
516
+ df.drop_duplicates(subset=['track_uri'],inplace=True,keep='last')
517
+ df.dropna(axis=0,inplace=True)
518
+ df.to_csv('Data/streamlit.csv',index=False)
519
+ return (len(df)-cur)
520
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ pandas==1.4.4
2
+ PyYAML==6.0
3
+ scikit_learn==1.1.3
4
+ spotipy==2.20.0
5
+ streamlit==1.14.0
6
+ streamlit_option_menu==0.3.2
spotify_get_artist_url.png ADDED
spotify_get_playlist_url.png ADDED
spotify_get_song_url.png ADDED