Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files
main.py
CHANGED
@@ -5,6 +5,7 @@ import time
|
|
5 |
from model import *
|
6 |
from Explanations.mistral import MistralExplainer, mistral_2_display
|
7 |
from Explanations.llama2 import Llama2Explainer
|
|
|
8 |
|
9 |
if 'model' not in st.session_state:
|
10 |
st.session_state.model = 'Model 1'
|
@@ -65,23 +66,23 @@ if 'explanation_length' not in st.session_state:
|
|
65 |
if 'selected_song_index' not in st.session_state:
|
66 |
st.session_state.selected_song_index = 0
|
67 |
|
68 |
-
song_list = [{"title": "The Strokes
|
69 |
-
{"title": "
|
70 |
-
{"title": "
|
71 |
-
{"title": "Dolly Parton
|
72 |
-
{"title": "
|
73 |
-
{"title": "
|
74 |
-
{"title": "
|
75 |
-
{"title": "
|
76 |
-
{"title": "
|
77 |
-
{"title": "
|
78 |
]
|
79 |
|
80 |
def play_recomm():
|
81 |
if 'rs' in st.session_state:
|
82 |
del st.session_state.rs,st.session_state.err
|
83 |
try:
|
84 |
-
if len(pd.read_csv('data/new_tracks.csv')) >= 200:
|
85 |
with st.spinner('Updating the dataset...'):
|
86 |
x=update_dataset()
|
87 |
st.success('{} New tracks were added to the dataset.'.format(x))
|
@@ -147,7 +148,7 @@ def song_page():
|
|
147 |
selected_song = next((song for song in song_list if song['title'] == selected_title), None)
|
148 |
if selected_song:
|
149 |
st.session_state.selected_song_index = selected_title
|
150 |
-
|
151 |
song_uri = selected_song['uri']
|
152 |
st.session_state.s_url = song_uri
|
153 |
|
@@ -165,8 +166,8 @@ def artist_page():
|
|
165 |
def spr_sidebar():
|
166 |
menu=option_menu(
|
167 |
menu_title=None,
|
168 |
-
options=['Home','Recommended','
|
169 |
-
icons=['house','lightbulb','heart
|
170 |
menu_icon='cast',
|
171 |
default_index=0,
|
172 |
orientation='horizontal'
|
@@ -177,8 +178,8 @@ def spr_sidebar():
|
|
177 |
st.session_state.app_mode = 'Recommended'
|
178 |
elif menu=='About':
|
179 |
st.session_state.app_mode = 'About'
|
180 |
-
elif menu=='Explanation':
|
181 |
-
|
182 |
elif menu=='Log':
|
183 |
st.session_state.app_mode = 'Log'
|
184 |
elif menu=='Counter':
|
@@ -190,7 +191,7 @@ def home_page():
|
|
190 |
st.session_state.same_art=st.session_state.artist
|
191 |
st.session_state.Region=st.session_state.rg
|
192 |
|
193 |
-
st.title('Spotify Recommendation
|
194 |
col2,col3=st.columns([2,2])
|
195 |
# radio=col.radio("Feature",options=("Playlist","Song"),key='radio',on_change=update_radio0)
|
196 |
radio2=col2.radio("Group Assignment",options=("Succinct","Verbose"),key='radio2',on_change=update_radio2)
|
@@ -227,12 +228,13 @@ def result_page():
|
|
227 |
if 'rs' not in st.session_state:
|
228 |
st.error('Please select a model on the Home page and run "Generate Recommendations"')
|
229 |
else:
|
230 |
-
|
231 |
-
|
|
|
232 |
tracks = []
|
233 |
original_tracks = []
|
234 |
length_of_explanation = 1
|
235 |
-
for uri in st.session_state.rs:
|
236 |
uri_link = "https://open.spotify.com/embed/track/" + uri + "?utm_source=generator&theme=0"
|
237 |
components.iframe(uri_link, height=80)
|
238 |
|
@@ -241,55 +243,47 @@ def result_page():
|
|
241 |
st.session_state.button_states[uri] = False
|
242 |
|
243 |
track_name, artist_name = get_track_info(uri)
|
244 |
-
|
245 |
-
|
246 |
-
|
|
|
247 |
|
248 |
# When button is clicked, call get_track_info
|
249 |
-
if
|
250 |
-
with st.spinner('Getting explanation...'):
|
|
|
251 |
if st.session_state.radio_choice == 'Song':
|
252 |
-
|
253 |
-
print(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
254 |
|
255 |
songlist = [{'track_name': track, 'artist_name': artist}]
|
256 |
if st.session_state.explanation_length == "Verbose":
|
257 |
length_of_explanation = 5
|
|
|
|
|
258 |
else:
|
259 |
length_of_explanation = 1
|
260 |
-
|
|
|
|
|
|
|
261 |
st.session_state.explanation_status = True
|
262 |
-
|
263 |
-
# explanation = mistral_2_display(mistral.get_positive_explanations())
|
264 |
-
# print(explanation)
|
265 |
-
|
266 |
-
# track_name, artist_name = get_track_info(uri)
|
267 |
-
# st.write('Track Name:', track_name)
|
268 |
-
# st.write('Artist Name:', artist_name)
|
269 |
|
270 |
-
i+=1
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
# formatted_string += '{} by {}, '.format(item['track_name'], item['artist_name'])
|
275 |
-
# songs = formatted_string.rstrip(', ')
|
276 |
-
|
277 |
-
# # Split the string into a list of songs
|
278 |
-
# song_list = songs.split(", ")
|
279 |
-
|
280 |
-
# # Calculate the midpoint index
|
281 |
-
# midpoint = len(song_list) // 2
|
282 |
-
|
283 |
-
# # Get the top and bottom halves of the list
|
284 |
-
# top_half = song_list[:midpoint]
|
285 |
-
# bottom_half = song_list[midpoint:]
|
286 |
-
|
287 |
-
# # Print the top and bottom halves
|
288 |
-
# print("Top half:")
|
289 |
-
# print(top_half)
|
290 |
-
# print("Bottom half:")
|
291 |
-
# print(bottom_half)
|
292 |
-
if i%5==0:
|
293 |
time.sleep(1)
|
294 |
|
295 |
def Explain_page():
|
@@ -307,27 +301,60 @@ def Counter_page():
|
|
307 |
st.header('Understanding Recommendations')
|
308 |
st.markdown("<br>", unsafe_allow_html=True)
|
309 |
st.subheader('Please select a song from the list below that you believe should have been recommended in the top 5 songs for your original selection.')
|
310 |
-
|
311 |
next_five = None
|
312 |
for song in song_list:
|
313 |
if song["title"] == st.session_state.selected_song_index:
|
314 |
next_five = song["next_five"]
|
315 |
break
|
316 |
-
|
317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
318 |
|
319 |
counter_fact_button = st.button('Generate Explanation')
|
320 |
|
321 |
if counter_fact_button:
|
322 |
-
None
|
323 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
324 |
|
325 |
def Log_page():
|
326 |
log=st.checkbox('Display Output', True, key='display_output')
|
327 |
if log == True:
|
328 |
if 'err' in st.session_state:
|
329 |
st.write(st.session_state.err)
|
330 |
-
with open('data/streamlit.csv') as f:
|
331 |
st.download_button('Download Dataset', f,file_name='streamlit.csv')
|
332 |
def About_page():
|
333 |
st.header('Development')
|
@@ -379,45 +406,6 @@ def About_page():
|
|
379 |
"""
|
380 |
|
381 |
|
382 |
-
# def dialog_close_button_clicked():
|
383 |
-
# st.write("### Dialog close callback results:")
|
384 |
-
# st.write("#### No preferences saved!")
|
385 |
-
# dialog.close()
|
386 |
-
|
387 |
-
|
388 |
-
# dialog = st.dialog(
|
389 |
-
# "first_dialog_with_help", title="Group Assignment",
|
390 |
-
# on_close_button_clicked=dialog_close_button_clicked, can_be_closed=True)
|
391 |
-
|
392 |
-
|
393 |
-
# def dialog_form_submit_button_clicked():
|
394 |
-
# st.write("### Dialog form submit button clicked results:")
|
395 |
-
# st.write(f"#### Hey {st.session_state.first_name} {st.session_state.last_name}!")
|
396 |
-
# st.write(f"#### Your preferences are saved")
|
397 |
-
# dialog.close()
|
398 |
-
|
399 |
-
|
400 |
-
# with dialog:
|
401 |
-
# st.radio("Explanation Length",options=("Succinct","Verbose"),key='radio2',on_change=update_radio2)
|
402 |
-
# st.text_input("First name", key="first_name")
|
403 |
-
# st.text_input("Last name", key="last_name")
|
404 |
-
# st.form_submit_button("OK", on_click=dialog_form_submit_button_clicked)
|
405 |
-
|
406 |
-
|
407 |
-
# if st.button("Open dialog", key="first_dialog_button"):
|
408 |
-
# dialog.open()
|
409 |
-
|
410 |
-
# modal = Modal("Demo Modal", key="example")
|
411 |
-
# open_modal = st.button("Open")
|
412 |
-
# if open_modal:
|
413 |
-
# modal.open()
|
414 |
-
|
415 |
-
# if modal.is_open():
|
416 |
-
# with modal.container():
|
417 |
-
# st.write("Text goes here")
|
418 |
-
# st.radio("Explanation Length",options=("Succinct","Verbose"),key='radio3',on_change=update_radio2)
|
419 |
-
# st.write("Some fancy text")
|
420 |
-
|
421 |
def main():
|
422 |
spr_sidebar()
|
423 |
if st.session_state.app_mode == 'Home':
|
|
|
5 |
from model import *
|
6 |
from Explanations.mistral import MistralExplainer, mistral_2_display
|
7 |
from Explanations.llama2 import Llama2Explainer
|
8 |
+
import json
|
9 |
|
10 |
if 'model' not in st.session_state:
|
11 |
st.session_state.model = 'Model 1'
|
|
|
66 |
if 'selected_song_index' not in st.session_state:
|
67 |
st.session_state.selected_song_index = 0
|
68 |
|
69 |
+
song_list = [{"title": "Someday by The Strokes", "uri" : "https://open.spotify.com/track/7hm4HTk9encxT0LYC0J6oI?si=9d23a7470dfb4330", "next_five": [{'full_track_name': 'Figure It Out by Royal Blood', 'uri': '3MjrueDQKVr6xDDseZwhEd'}, {'full_track_name': 'Joker And The Thief by Wolfmother', 'uri': '7ISL3LO8AWP3fKIXunvqTa'}, {'full_track_name': 'Heads Will Roll - A-Trak Remix Radio Edit by Yeah Yeah Yeahs', 'uri': '5qGIfWDRdyO67LCTqA2sEn'}, {'full_track_name': 'Hate To Say I Told You So by The Hives', 'uri': '20j7B6mL9gnNvG3ic6Vwh5'}, {'full_track_name': 'Get Free by The Vines', 'uri': '1JcGNoiwifg0MdJMVgJQYx'}]},
|
70 |
+
{"title": "Paint the Town Red by Doja Cat", "uri" : "https://open.spotify.com/track/4dHRp03oxqJQfjGU8ECo7v?si=75a8b6b9ae304963", "next_five":[{'full_track_name': 'Locked out of Heaven by Bruno Mars', 'uri': '3w3y8KPTfNeOKPiqUTakBh'}, {'full_track_name': '...Baby One More Time by Britney Spears', 'uri': '3MjUtNVVq3C8Fn0MP3zhXa'}, {'full_track_name': 'I Wanna Dance with Somebody (Who Loves Me) by Whitney Houston', 'uri': '2tUBqZG2AbRi7Q0BIrVrEj'}, {'full_track_name': 'Disturbia by Rihanna', 'uri': '2VOomzT6VavJOGBeySqaMc'}, {'full_track_name': 'Too Good At Goodbyes by Sam Smith', 'uri': '1mXVgsBdtIVeCLJnSnmtdV'}]},
|
71 |
+
{"title": "Single Ladies by Beyonce","uri":"https://open.spotify.com/track/5R9a4t5t5O0IsznsrKPVro?si=d7f7f6b342b446c8", "next_five":[{'full_track_name': "I'm Good (Blue) by David Guetta", 'uri': '4uUG5RXrOk84mYEfFvj3cK'}, {'full_track_name': 'Dance The Night - From Barbie The Album by Dua Lipa', 'uri': '1vYXt7VSjH9JIM5oRRo7vA'}, {'full_track_name': 'Super Shy by NewJeans', 'uri': '5sdQOyqq2IDhvmx2lHOpwd'}, {'full_track_name': 'Snooze by SZA', 'uri': '4iZ4pt7kvcaH6Yo8UoZ4s2'}, {'full_track_name': 'Watermelon Sugar by Harry Styles', 'uri': '6UelLqGlWMcVH1E5c4H7lY'}] },
|
72 |
+
{"title": "Jolene by Dolly Parton","uri":"https://open.spotify.com/track/2SpEHTbUuebeLkgs9QB7Ue?si=ab915579c1244a5f", "next_five":[{'full_track_name': 'Wide Open Spaces by The Chicks', 'uri': '6cjwec9ii5uLK7CDfPBYt1'}, {'full_track_name': 'Blue Eyes Crying In the Rain by Willie Nelson', 'uri': '2uRVPeQbsEpRQD0DKr1WTo'}, {'full_track_name': 'Need You Now by Lady A', 'uri': '11EX5yhxr9Ihl3IN1asrfK'}, {'full_track_name': "Mama's Broken Heart by Miranda Lambert", 'uri': '2mXsZsJBThTaJXbNcg5QD4'}, {'full_track_name': "She's In Love With The Boy - Single Version by Trisha Yearwood", 'uri': '2ulBBx6YQ3qY3ci34RadtN'}]},
|
73 |
+
{"title": "Lavender Haze by Taylor Swift","uri":"https://open.spotify.com/track/5jQI2r1RdgtuT8S3iG8zFC?si=5922d57584b84382", "next_five":[{'full_track_name': 'Dance The Night - From Barbie The Album by Dua Lipa', 'uri': '1vYXt7VSjH9JIM5oRRo7vA'}, {'full_track_name': "I'm Good (Blue) by David Guetta", 'uri': '4uUG5RXrOk84mYEfFvj3cK'}, {'full_track_name': 'Perfect by Ed Sheeran', 'uri': '0tgVpDi06FyKpA1z0VMD4v'}, {'full_track_name': "Doin' Time by Lana Del Rey", 'uri': '0Oqc0kKFsQ6MhFOLBNZIGX'}, {'full_track_name': 'Sweater Weather by The Neighbourhood', 'uri': '2QjOHCTQ1Jl3zawyYOpxh6'}]},
|
74 |
+
{"title": "What I've Done by Lincoln Park","uri":"https://open.spotify.com/track/2nLtzopw4rPReszdYBJU6h?si=1b48d972e12d43e7", "next_five":[{'full_track_name': 'Higher by Creed', 'uri': '1ZozJfi8u9cO2Ob8KwiwNT'}, {'full_track_name': 'Drive by Incubus', 'uri': '7nnWIPM5hwE3DaUBkvOIpy'}, {'full_track_name': 'I Hate Everything About You by Three Days Grace', 'uri': '0M955bMOoilikPXwKLYpoi'}, {'full_track_name': 'The Reason by Hoobastank', 'uri': '77loZpT5Y5PRP1S451P9Yz'}, {'full_track_name': 'Butterfly by Crazy Town', 'uri': '4BggEwLhGfrbrl7JBhC8EC'}]},
|
75 |
+
{"title": "Hey Brother by Avicii","uri":"https://open.spotify.com/track/4lhqb6JvbHId48OUJGwymk?si=d148732daa8e4897", "next_five":[{'full_track_name': 'Silence by Marshmello', 'uri': '7vGuf3Y35N4wmASOKLUVVU'}, {'full_track_name': 'Sugar (feat. Francesco Yates) by Robin Schulz', 'uri': '5tf1VVWniHgryyumXyJM7w'}, {'full_track_name': 'Where Did You Go? (feat. MNEK) by Jax Jones', 'uri': '3sa06xVNmLLYIxdNNmVQN8'}, {'full_track_name': 'Rockabye (feat. Sean Paul & Anne-Marie) by Clean Bandit', 'uri': '5knuzwU65gJK7IF5yJsuaW'}, {'full_track_name': 'Lush Life by Zara Larsson', 'uri': '1rIKgCH4H52lrvDcz50hS8'}] },
|
76 |
+
{"title": "Sound of Silence by Simon & Garfunkel","uri":"https://open.spotify.com/track/3YfS47QufnLDFA71FUsgCM?si=5bff00bb3b2e4a67", "next_five": [{'full_track_name': 'American Pie by Don McLean', 'uri': '1fDsrQ23eTAVFElUMaf38X'}, {'full_track_name': 'The Weight - Remastered 2000 by The Band', 'uri': '0P7DoyGrr4Wp9w5TotEtUC'}, {'full_track_name': "You're So Vain by Carly Simon", 'uri': '2DnJjbjNTV9Nd5NOa1KGba'}, {'full_track_name': "Do You Believe in Magic? by The Lovin' Spoonful", 'uri': '1udKn1oNKYQSQ9OmiIWCMu'}, {'full_track_name': "You've Got a Friend by Carole King", 'uri': '1qhp5owrFGeZ5Jgin28nwR'}]},
|
77 |
+
{"title": "Bohemian Rhapsody by Queen","uri":"https://open.spotify.com/track/6l8GvAyoUZwWDgF1e4822w?si=9639498e177d46e6", "next_five":[{'full_track_name': 'You Really Got Me by The Kinks', 'uri': '29SyMC0plk6qw8NMF7lfRL'}, {'full_track_name': 'Walk On the Wild Side by Lou Reed', 'uri': '5p3JunprHCxClJjOmcLV8G'}, {'full_track_name': 'In The Army Now by Status Quo', 'uri': '6QLspHLCLftSGPa6vNzKuo'}, {'full_track_name': 'Surrender by Cheap Trick', 'uri': '2ccUQnjjNWT0rsNnsBpsCA'}, {'full_track_name': 'More Than This by Roxy Music', 'uri': '6N7gPTru90HYLRUIVDQ185'}] },
|
78 |
+
{"title": "Nocturnes Op. 9 N. 2 by Fr\u00e9d\u00e9ric Chopin","uri":"https://open.spotify.com/track/61YM5SkqqeUjIBL7It56cs?si=01a05e921c61409b", "next_five":[{'full_track_name': 'Paganini: 24 Caprices, Op. 1: No. 24 in A Minor by Niccolò Paganini', 'uri': '6cC6h5E351deEGFd7Kh9uy'}, {'full_track_name': 'I puritani / Act I: A te, o cara by Vincenzo Bellini', 'uri': '48fH1Mv10Nl8Hisna5y2Rf'}, {'full_track_name': 'Strauss I: Radetzky March, Op. 228 by Johann Strauss I', 'uri': '53Z3s7DPc7WbkYt9L9ZdlJ'}, {'full_track_name': 'Clarinet Concerto No. 1 in F Minor, Op. 73: III. Rondo: Allegretto by Carl Maria von Weber', 'uri': '21Ct04i87NtSa6pKvM0bAF'}, {'full_track_name': 'Scherzo-tarantelle in G Minor, Op.16 - 1987 Remastered Version by Henryk Wieniawski', 'uri': '0yQMA3UgzGgmL7Py3lPFCx'}]}
|
79 |
]
|
80 |
|
81 |
def play_recomm():
|
82 |
if 'rs' in st.session_state:
|
83 |
del st.session_state.rs,st.session_state.err
|
84 |
try:
|
85 |
+
if len(pd.read_csv('../data/new_tracks.csv')) >= 200:
|
86 |
with st.spinner('Updating the dataset...'):
|
87 |
x=update_dataset()
|
88 |
st.success('{} New tracks were added to the dataset.'.format(x))
|
|
|
148 |
selected_song = next((song for song in song_list if song['title'] == selected_title), None)
|
149 |
if selected_song:
|
150 |
st.session_state.selected_song_index = selected_title
|
151 |
+
print(st.session_state.selected_song_index)
|
152 |
song_uri = selected_song['uri']
|
153 |
st.session_state.s_url = song_uri
|
154 |
|
|
|
166 |
def spr_sidebar():
|
167 |
menu=option_menu(
|
168 |
menu_title=None,
|
169 |
+
options=['Home','Recommended','Counter'],
|
170 |
+
icons=['house','lightbulb','heart-half'],
|
171 |
menu_icon='cast',
|
172 |
default_index=0,
|
173 |
orientation='horizontal'
|
|
|
178 |
st.session_state.app_mode = 'Recommended'
|
179 |
elif menu=='About':
|
180 |
st.session_state.app_mode = 'About'
|
181 |
+
# elif menu=='Explanation':
|
182 |
+
# st.session_state.app_mode = 'Explanation'
|
183 |
elif menu=='Log':
|
184 |
st.session_state.app_mode = 'Log'
|
185 |
elif menu=='Counter':
|
|
|
191 |
st.session_state.same_art=st.session_state.artist
|
192 |
st.session_state.Region=st.session_state.rg
|
193 |
|
194 |
+
st.title('CS6966 - Class Project (Spotify Recommendation)')
|
195 |
col2,col3=st.columns([2,2])
|
196 |
# radio=col.radio("Feature",options=("Playlist","Song"),key='radio',on_change=update_radio0)
|
197 |
radio2=col2.radio("Group Assignment",options=("Succinct","Verbose"),key='radio2',on_change=update_radio2)
|
|
|
228 |
if 'rs' not in st.session_state:
|
229 |
st.error('Please select a model on the Home page and run "Generate Recommendations"')
|
230 |
else:
|
231 |
+
if not st.session_state.button_states.values():
|
232 |
+
st.success('Top {} recommendations'.format(len(st.session_state.rs)))
|
233 |
+
i = 0
|
234 |
tracks = []
|
235 |
original_tracks = []
|
236 |
length_of_explanation = 1
|
237 |
+
for index, uri in enumerate(st.session_state.rs):
|
238 |
uri_link = "https://open.spotify.com/embed/track/" + uri + "?utm_source=generator&theme=0"
|
239 |
components.iframe(uri_link, height=80)
|
240 |
|
|
|
243 |
st.session_state.button_states[uri] = False
|
244 |
|
245 |
track_name, artist_name = get_track_info(uri)
|
246 |
+
full_song_title = '{} by {}'.format(track_name, artist_name)
|
247 |
+
original_tracks.append({'full_track_name': full_song_title, 'uri': uri})
|
248 |
+
tracks.append({'track_name': track_name, 'artist_name': artist_name, 'uri': uri, 'index': index})
|
249 |
+
explanation_button = st.button('Get explanation for {}'.format(track_name))
|
250 |
|
251 |
# When button is clicked, call get_track_info
|
252 |
+
if explanation_button:
|
253 |
+
with st.spinner('Getting explanation...'):
|
254 |
+
time.sleep(0.5)
|
255 |
if st.session_state.radio_choice == 'Song':
|
256 |
+
song_title, artist = get_track_info(uri)
|
257 |
+
print(song_title, artist)
|
258 |
+
full_song_title = '{} by {}'.format(song_title, artist)
|
259 |
+
found_index = None
|
260 |
+
key = None
|
261 |
+
for track in tracks:
|
262 |
+
if track['track_name'] == song_title:
|
263 |
+
found_index = track['index'] + 1
|
264 |
+
key = str(found_index)
|
265 |
+
break # Exit the loop once the track is found
|
266 |
+
with open('data/results.json') as f:
|
267 |
+
data = json.load(f)
|
268 |
|
269 |
songlist = [{'track_name': track, 'artist_name': artist}]
|
270 |
if st.session_state.explanation_length == "Verbose":
|
271 |
length_of_explanation = 5
|
272 |
+
song_objects = data["5"]
|
273 |
+
st.session_state.generated_explanation = song_objects[st.session_state.selected_song_index][0][key]
|
274 |
else:
|
275 |
length_of_explanation = 1
|
276 |
+
song_objects = data["1"]
|
277 |
+
st.session_state.generated_explanation = song_objects[st.session_state.selected_song_index][0][key]
|
278 |
+
|
279 |
+
st.success(st.session_state.generated_explanation)
|
280 |
st.session_state.explanation_status = True
|
281 |
+
st.session_state.button_states[uri] = True
|
|
|
|
|
|
|
|
|
|
|
|
|
282 |
|
283 |
+
i += 1
|
284 |
+
st.session_state.track_list = tracks
|
285 |
+
print(original_tracks[5:])
|
286 |
+
if i % 5 == 0:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
287 |
time.sleep(1)
|
288 |
|
289 |
def Explain_page():
|
|
|
301 |
st.header('Understanding Recommendations')
|
302 |
st.markdown("<br>", unsafe_allow_html=True)
|
303 |
st.subheader('Please select a song from the list below that you believe should have been recommended in the top 5 songs for your original selection.')
|
304 |
+
|
305 |
next_five = None
|
306 |
for song in song_list:
|
307 |
if song["title"] == st.session_state.selected_song_index:
|
308 |
next_five = song["next_five"]
|
309 |
break
|
310 |
+
|
311 |
+
titles = [song['full_track_name'] for song in next_five] # Get a list of song titles
|
312 |
+
|
313 |
+
selected_title = st.selectbox('Select a song', titles)
|
314 |
+
|
315 |
+
selected_song = next((song for song in next_five if song['full_track_name'] == selected_title), None)
|
316 |
+
if selected_song:
|
317 |
+
# st.session_state.selected_song_index = selected_title
|
318 |
+
print(selected_song)
|
319 |
+
song_uri = selected_song['uri']
|
320 |
+
# st.session_state.s_url = song_uri
|
321 |
+
|
322 |
+
uri_link = 'https://open.spotify.com/embed/track/' + song_uri
|
323 |
+
# slot1 = st.empty()
|
324 |
+
components.iframe(uri_link, height=100)
|
325 |
|
326 |
counter_fact_button = st.button('Generate Explanation')
|
327 |
|
328 |
if counter_fact_button:
|
329 |
+
found_index = None
|
330 |
+
key = None
|
331 |
+
for index, track in enumerate(next_five):
|
332 |
+
if track['full_track_name'] == selected_song['full_track_name']:
|
333 |
+
found_index = index + 1
|
334 |
+
key = str(found_index)
|
335 |
+
break # Exit the loop once the track is found
|
336 |
+
with open('data/results.json') as f:
|
337 |
+
data = json.load(f)
|
338 |
+
|
339 |
+
if st.session_state.explanation_length == "Verbose":
|
340 |
+
length_of_explanation = 5
|
341 |
+
song_objects = data["5"]
|
342 |
+
st.session_state.generated_counter = song_objects[st.session_state.selected_song_index][1][key]
|
343 |
+
else:
|
344 |
+
length_of_explanation = 1
|
345 |
+
song_objects = data["1"]
|
346 |
+
st.session_state.generated_counter = song_objects[st.session_state.selected_song_index][1][key]
|
347 |
+
|
348 |
+
st.success(st.session_state.generated_counter)
|
349 |
+
|
350 |
+
|
351 |
|
352 |
def Log_page():
|
353 |
log=st.checkbox('Display Output', True, key='display_output')
|
354 |
if log == True:
|
355 |
if 'err' in st.session_state:
|
356 |
st.write(st.session_state.err)
|
357 |
+
with open('../data/streamlit.csv') as f:
|
358 |
st.download_button('Download Dataset', f,file_name='streamlit.csv')
|
359 |
def About_page():
|
360 |
st.header('Development')
|
|
|
406 |
"""
|
407 |
|
408 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
409 |
def main():
|
410 |
spr_sidebar()
|
411 |
if st.session_state.app_mode == 'Home':
|
model.py
CHANGED
@@ -157,7 +157,7 @@ def playlist_model(url, model, max_gen=3, same_art=5):
|
|
157 |
log.append('Model run successfully')
|
158 |
return Fresult, log
|
159 |
|
160 |
-
lendf=len(pd.read_csv('data/streamlit.csv',usecols=['track_uri']))
|
161 |
dtypes = {'track_uri': 'object', 'artist_uri': 'object', 'album_uri': 'object', 'danceability': 'float16', 'energy': 'float16', 'key': 'float16',
|
162 |
'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
|
163 |
'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
|
@@ -292,7 +292,7 @@ def playlist_model(url, model, max_gen=3, same_art=5):
|
|
292 |
x = 1
|
293 |
for i in range(int(lendf/2), lendf+1, int(lendf/2)):
|
294 |
try:
|
295 |
-
df = pd.read_csv('data/streamlit.csv',names= col_name,dtype=dtypes,skiprows=x,nrows=i)
|
296 |
log.append('reading data frame chunks from {} to {}'.format(x,i))
|
297 |
except Exception as e:
|
298 |
log.append('Failed to load grow')
|
@@ -315,7 +315,7 @@ def playlist_model(url, model, max_gen=3, same_art=5):
|
|
315 |
log.append('genre|unknown not found')
|
316 |
log.append('Scaling the data .....')
|
317 |
if x == 1:
|
318 |
-
sc = pickle.load(open('data/sc.sav','rb'))
|
319 |
df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
|
320 |
test.iloc[:, 3:19] = sc.transform(test.iloc[:, 3:19])
|
321 |
log.append("Creating playlist vector")
|
@@ -359,13 +359,13 @@ def playlist_model(url, model, max_gen=3, same_art=5):
|
|
359 |
log.append('{} New Tracks Found'.format(len(grow)))
|
360 |
if(len(grow)>=1):
|
361 |
try:
|
362 |
-
new=pd.read_csv('data/new_tracks.csv',dtype=dtypes)
|
363 |
new=pd.concat([new, grow], axis=0)
|
364 |
new=new[new.Track_pop >0]
|
365 |
new.drop_duplicates(subset=['track_uri'], inplace=True,keep='last')
|
366 |
-
new.to_csv('data/new_tracks.csv',index=False)
|
367 |
except:
|
368 |
-
grow.to_csv('data/new_tracks.csv', index=False)
|
369 |
log.append('Model run successfully')
|
370 |
except Exception as e:
|
371 |
log.append("Model Failed")
|
@@ -437,7 +437,7 @@ def song_model(url, model, max_gen=3, same_art=5):
|
|
437 |
Fresult.append(aa['tracks'][i]['id'])
|
438 |
log.append('Model run successfully')
|
439 |
return Fresult, log
|
440 |
-
lendf=len(pd.read_csv('data/streamlit.csv',usecols=['track_uri']))
|
441 |
dtypes = {'track_uri': 'object', 'artist_uri': 'object', 'album_uri': 'object', 'danceability': 'float16', 'energy': 'float16', 'key': 'float16',
|
442 |
'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
|
443 |
'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
|
@@ -504,7 +504,7 @@ def song_model(url, model, max_gen=3, same_art=5):
|
|
504 |
x = 1
|
505 |
for i in range(int(lendf/2), lendf+1, int(lendf/2)):
|
506 |
try:
|
507 |
-
df = pd.read_csv('data/streamlit.csv',names= col_name,dtype=dtypes,skiprows=x,nrows=i)
|
508 |
log.append('reading data frame chunks from {} to {}'.format(x,i))
|
509 |
except Exception as e:
|
510 |
log.append('Failed to load grow')
|
@@ -527,7 +527,7 @@ def song_model(url, model, max_gen=3, same_art=5):
|
|
527 |
log.append('genre|unknown not found')
|
528 |
log.append('Scaling the data .....')
|
529 |
if x == 1:
|
530 |
-
sc = pickle.load(open('data/sc.sav','rb'))
|
531 |
df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
|
532 |
test.iloc[:, 3:19] = sc.transform(test.iloc[:, 3:19])
|
533 |
log.append("Creating playlist vector")
|
@@ -571,13 +571,13 @@ def song_model(url, model, max_gen=3, same_art=5):
|
|
571 |
log.append('{} New Tracks Found'.format(len(grow)))
|
572 |
if(len(grow)>=1):
|
573 |
try:
|
574 |
-
new=pd.read_csv('data/new_tracks.csv',dtype=dtypes)
|
575 |
new=pd.concat([new, grow], axis=0)
|
576 |
new=new[new.Track_pop >0]
|
577 |
new.drop_duplicates(subset=['track_uri'], inplace=True,keep='last')
|
578 |
-
new.to_csv('data/new_tracks.csv',index=False)
|
579 |
except:
|
580 |
-
grow.to_csv('data/new_tracks.csv', index=False)
|
581 |
log.append('Model run successfully')
|
582 |
except Exception as e:
|
583 |
log.append("Model Failed")
|
@@ -593,14 +593,14 @@ def update_dataset():
|
|
593 |
'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
|
594 |
'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
|
595 |
'Track_release_date': 'int8', 'Track_pop': 'int8', 'Artist_pop': 'int8', 'Artist_genres': 'object'}
|
596 |
-
df = pd.read_csv('data/streamlit.csv',dtype=dtypes)
|
597 |
-
grow = pd.read_csv('data/new_tracks.csv',dtype=dtypes)
|
598 |
cur = len(df)
|
599 |
df=pd.concat([df,grow],axis=0)
|
600 |
grow=pd.DataFrame(columns=col_name)
|
601 |
-
grow.to_csv('data/new_tracks.csv',index=False)
|
602 |
df=df[df.Track_pop >0]
|
603 |
df.drop_duplicates(subset=['track_uri'],inplace=True,keep='last')
|
604 |
df.dropna(axis=0,inplace=True)
|
605 |
-
df.to_csv('data/streamlit.csv',index=False)
|
606 |
return (len(df)-cur)
|
|
|
157 |
log.append('Model run successfully')
|
158 |
return Fresult, log
|
159 |
|
160 |
+
lendf=len(pd.read_csv('../data/streamlit.csv',usecols=['track_uri']))
|
161 |
dtypes = {'track_uri': 'object', 'artist_uri': 'object', 'album_uri': 'object', 'danceability': 'float16', 'energy': 'float16', 'key': 'float16',
|
162 |
'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
|
163 |
'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
|
|
|
292 |
x = 1
|
293 |
for i in range(int(lendf/2), lendf+1, int(lendf/2)):
|
294 |
try:
|
295 |
+
df = pd.read_csv('../data/streamlit.csv',names= col_name,dtype=dtypes,skiprows=x,nrows=i)
|
296 |
log.append('reading data frame chunks from {} to {}'.format(x,i))
|
297 |
except Exception as e:
|
298 |
log.append('Failed to load grow')
|
|
|
315 |
log.append('genre|unknown not found')
|
316 |
log.append('Scaling the data .....')
|
317 |
if x == 1:
|
318 |
+
sc = pickle.load(open('../data/sc.sav','rb'))
|
319 |
df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
|
320 |
test.iloc[:, 3:19] = sc.transform(test.iloc[:, 3:19])
|
321 |
log.append("Creating playlist vector")
|
|
|
359 |
log.append('{} New Tracks Found'.format(len(grow)))
|
360 |
if(len(grow)>=1):
|
361 |
try:
|
362 |
+
new=pd.read_csv('../data/new_tracks.csv',dtype=dtypes)
|
363 |
new=pd.concat([new, grow], axis=0)
|
364 |
new=new[new.Track_pop >0]
|
365 |
new.drop_duplicates(subset=['track_uri'], inplace=True,keep='last')
|
366 |
+
new.to_csv('../data/new_tracks.csv',index=False)
|
367 |
except:
|
368 |
+
grow.to_csv('../data/new_tracks.csv', index=False)
|
369 |
log.append('Model run successfully')
|
370 |
except Exception as e:
|
371 |
log.append("Model Failed")
|
|
|
437 |
Fresult.append(aa['tracks'][i]['id'])
|
438 |
log.append('Model run successfully')
|
439 |
return Fresult, log
|
440 |
+
lendf=len(pd.read_csv('../data/streamlit.csv',usecols=['track_uri']))
|
441 |
dtypes = {'track_uri': 'object', 'artist_uri': 'object', 'album_uri': 'object', 'danceability': 'float16', 'energy': 'float16', 'key': 'float16',
|
442 |
'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
|
443 |
'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
|
|
|
504 |
x = 1
|
505 |
for i in range(int(lendf/2), lendf+1, int(lendf/2)):
|
506 |
try:
|
507 |
+
df = pd.read_csv('../data/streamlit.csv',names= col_name,dtype=dtypes,skiprows=x,nrows=i)
|
508 |
log.append('reading data frame chunks from {} to {}'.format(x,i))
|
509 |
except Exception as e:
|
510 |
log.append('Failed to load grow')
|
|
|
527 |
log.append('genre|unknown not found')
|
528 |
log.append('Scaling the data .....')
|
529 |
if x == 1:
|
530 |
+
sc = pickle.load(open('../data/sc.sav','rb'))
|
531 |
df.iloc[:, 3:19] = sc.transform(df.iloc[:, 3:19])
|
532 |
test.iloc[:, 3:19] = sc.transform(test.iloc[:, 3:19])
|
533 |
log.append("Creating playlist vector")
|
|
|
571 |
log.append('{} New Tracks Found'.format(len(grow)))
|
572 |
if(len(grow)>=1):
|
573 |
try:
|
574 |
+
new=pd.read_csv('../data/new_tracks.csv',dtype=dtypes)
|
575 |
new=pd.concat([new, grow], axis=0)
|
576 |
new=new[new.Track_pop >0]
|
577 |
new.drop_duplicates(subset=['track_uri'], inplace=True,keep='last')
|
578 |
+
new.to_csv('../data/new_tracks.csv',index=False)
|
579 |
except:
|
580 |
+
grow.to_csv('../data/new_tracks.csv', index=False)
|
581 |
log.append('Model run successfully')
|
582 |
except Exception as e:
|
583 |
log.append("Model Failed")
|
|
|
593 |
'loudness': 'float16', 'mode': 'float16', 'speechiness': 'float16', 'acousticness': 'float16', 'instrumentalness': 'float16',
|
594 |
'liveness': 'float16', 'valence': 'float16', 'tempo': 'float16', 'duration_ms': 'float32', 'time_signature': 'float16',
|
595 |
'Track_release_date': 'int8', 'Track_pop': 'int8', 'Artist_pop': 'int8', 'Artist_genres': 'object'}
|
596 |
+
df = pd.read_csv('../data/streamlit.csv',dtype=dtypes)
|
597 |
+
grow = pd.read_csv('../data/new_tracks.csv',dtype=dtypes)
|
598 |
cur = len(df)
|
599 |
df=pd.concat([df,grow],axis=0)
|
600 |
grow=pd.DataFrame(columns=col_name)
|
601 |
+
grow.to_csv('../data/new_tracks.csv',index=False)
|
602 |
df=df[df.Track_pop >0]
|
603 |
df.drop_duplicates(subset=['track_uri'],inplace=True,keep='last')
|
604 |
df.dropna(axis=0,inplace=True)
|
605 |
+
df.to_csv('../data/streamlit.csv',index=False)
|
606 |
return (len(df)-cur)
|