File size: 27,312 Bytes
d382306
 
 
 
 
 
 
b883db8
d382306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b883db8
 
 
 
 
 
 
 
 
 
d382306
 
 
 
 
 
52b6e15
d382306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b883db8
d382306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5153ab3
 
d382306
 
 
 
 
 
 
 
 
 
b883db8
 
d382306
 
 
 
 
 
 
 
 
 
 
b883db8
d382306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b883db8
 
 
d382306
 
 
b883db8
d382306
 
 
 
 
 
 
 
b883db8
 
 
 
d382306
 
b883db8
 
 
d382306
b883db8
 
 
 
 
 
 
 
 
 
 
 
d382306
 
 
 
b883db8
 
d382306
 
b883db8
 
 
 
d382306
b883db8
d382306
b883db8
 
 
 
d382306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b883db8
d382306
 
 
 
 
b883db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d382306
 
 
 
b883db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d382306
 
 
 
 
 
52b6e15
d382306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import streamlit as st
from streamlit_option_menu import option_menu
import streamlit.components.v1 as components
import time
from model import *
from Explanations.mistral import MistralExplainer, mistral_2_display
from Explanations.llama2 import Llama2Explainer
import json

if 'model' not in st.session_state:
    st.session_state.model = 'Model 1'
def update_radio2():
    st.session_state.explanation_length=st.session_state.radio2
if 'genre' not in st.session_state:
    st.session_state.genre=3
def update_num_genre():
    st.session_state.genre=st.session_state.num_genre
if 'artist' not in st.session_state:
    st.session_state.artist=1
def update_same_art():
    st.session_state.artist=st.session_state.same_art
if 'model2' not in st.session_state:
    st.session_state.model2= 'Spotify model'
def update_radio1():
    st.session_state.model2 =st.session_state.radio1

if 'Region' not in st.session_state:
    st.session_state.rg="US"
def update_Region():
    st.session_state.rg=st.session_state.Region
if 'radio' not in st.session_state:
    st.session_state.feature="Song"
def update_radio0():
    st.session_state.feature=st.session_state.radio

if 'p_url' not in st.session_state:
    st.session_state.p_url = 'Example: https://open.spotify.com/playlist/37i9dQZF1DX45grRWk2ghU?si=3f2b42b40d59449d'
def update_playlist_url():
    st.session_state.p_url = st.session_state.playlist_url

if 's_url' not in st.session_state:
    st.session_state.s_url = 'Example: https://open.spotify.com/track/7hm4HTk9encxT0LYC0J6oI?si=cc4c8b502e2748c5'
def update_song_url():
    st.session_state.s_url = st.session_state.song_url

if 'a_url' not in st.session_state:
    st.session_state.a_url = 'Example: https://open.spotify.com/artist/3RNrq3jvMZxD9ZyoOZbQOD?si=UNAsX20kRpG89bxOO8o7ew'
def update_artist_url():
    st.session_state.a_url = st.session_state.artist_url
if 'selected_option' not in st.session_state:
    st.session_state.selected_option = None
def update_selectbox():
    st.session_state.selected_option = st.session_state.select_box

if 'button_states' not in st.session_state:
    st.session_state.button_states = {}
    
if 'track_list' not in st.session_state:
    st.session_state.track_list = []
    
if 'radio_choice' not in st.session_state:
    st.session_state.radio_choice = None
if 'explanation_length' not in st.session_state:
    st.session_state.explanation_length = 'Succinct'

if 'selected_song_index' not in st.session_state:
    st.session_state.selected_song_index = 0
    
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'}]}, 
                 {"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'}]},
                 {"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'}] },
                 {"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'}]},
                 {"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'}]},
                 {"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'}]},
                 {"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'}] },
                 {"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'}]},
                 {"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'}] },
                 {"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'}]}
                 ]

def play_recomm():
    if 'rs' in st.session_state:
        del st.session_state.rs,st.session_state.err
    try:
        if len(pd.read_csv('data/new_tracks.csv')) >= 200:
            with st.spinner('Updating the dataset...'):
                x=update_dataset()
                st.success('{} New tracks were added to the dataset.'.format(x))
    except:
        st.error("The dataset update failed. ")
    with st.spinner('Getting Recommendations...'):
        res,err = playlist_model(st.session_state.p_url,st.session_state.model,st.session_state.genre,st.session_state.artist)
        st.session_state.rs=res
        st.session_state.err=err
    if len(st.session_state.rs)>=1:
        if st.session_state.model == 'Model 1' or st.session_state.model == 'Model 2':
            st.success('Go to the Recommended page to view the top {} recommendations'.format(len(st.session_state.rs)))
            # print(st.session_state.rs)
        else:
            st.success('Go to the Recommended page to view the Spotify recommendations')
    else:
        st.error('Model failed. Check the log for more information.')   

def art_recomm():
    if 'rs' in st.session_state:
        del st.session_state.rs,st.session_state.err
    with st.spinner('Getting Recommendations...'):
        res,err = top_tracks(st.session_state.a_url,st.session_state.rg)
        st.session_state.rs=res
        st.session_state.err=err
    if len(st.session_state.rs)>=1:
        st.success("Go to the Recommended page to view the Artist's top tracks")
    else:
        st.error('Model failed. Check the log for more information.')

def song_recomm():
    if 'rs' in st.session_state:
        del st.session_state.rs,st.session_state.err
    with st.spinner('Getting Recommendations...'):
        res,err = song_model(st.session_state.s_url,st.session_state.model,st.session_state.genre,st.session_state.artist)
        st.session_state.rs=res
        st.session_state.err=err
    if len(st.session_state.rs)>=1:
        if st.session_state.model == 'Model 1' or st.session_state.model == 'Model 2':
            st.success('Go to the Recommended page to view the top {} recommendations'.format(len(st.session_state.rs)))
        else:
            st.success('Go to the Recommended page to view the  Spotify recommendations')
    else:
        st.error('Model failed. Check the log for more information.')

def playlist_page():
    st.subheader("User Playlist")
    st.markdown('---')
    playlist_uri = (st.session_state.playlist_url).split('/')[-1].split('?')[0]
    uri_link = 'https://open.spotify.com/embed/playlist/' + playlist_uri
    components.iframe(uri_link, height=180)
    return
    ...
def song_page():
    st.subheader("Select your favorite song from the list below:")
    st.markdown('---')
    
    titles = [song['title'] for song in song_list]  # Get a list of song titles

    selected_title = st.selectbox('Select a song', titles)

    # Find the selected song in the song list
    selected_song = next((song for song in song_list if song['title'] == selected_title), None)
    if selected_song:
        st.session_state.selected_song_index = selected_title
        print(st.session_state.selected_song_index)
        song_uri = selected_song['uri']
        st.session_state.s_url = song_uri
    
        uri_link = 'https://open.spotify.com/embed/track/' + song_uri.split('/')[-1].split('?')[0]
        # slot1 = st.empty()
        components.iframe(uri_link, height=100)

def artist_page():
    st.subheader("User Artist")
    st.markdown('---')
    artist_uri = (st.session_state.artist_url).split('/')[-1].split('?')[0]
    uri_link = 'https://open.spotify.com/embed/artist/' + artist_uri
    components.iframe(uri_link, height=80)
    
def spr_sidebar():
    menu=option_menu(
        menu_title=None,
        options=['Home','Recommended','Counter'],
        icons=['house','lightbulb','heart-half'],
        menu_icon='cast',
        default_index=0,
        orientation='horizontal'
    )
    if menu=='Home':
        st.session_state.app_mode = 'Home'
    elif menu=='Recommended':
        st.session_state.app_mode = 'Recommended'
    elif menu=='About':
        st.session_state.app_mode = 'About'
    # elif menu=='Explanation':
    #     st.session_state.app_mode = 'Explanation'
    elif menu=='Log':
        st.session_state.app_mode = 'Log'
    elif menu=='Counter':
        st.session_state.app_mode = 'Counter'
    
def home_page():
    st.session_state.radio=st.session_state.feature
    st.session_state.num_genre=st.session_state.genre
    st.session_state.same_art=st.session_state.artist
    st.session_state.Region=st.session_state.rg

    st.title('CS6966 - Class Project (Spotify Recommendation)')
    col2,col3=st.columns([2,2])
    # radio=col.radio("Feature",options=("Playlist","Song"),key='radio',on_change=update_radio0)
    radio2=col2.radio("Group Assignment",options=("Succinct","Verbose"),key='radio2',on_change=update_radio2)

    st.markdown("<br>", unsafe_allow_html=True)

    # Check if 'df' and 'selected_option' are in the session state
    if 'df' in st.session_state and 'selected_option' in st.session_state:
        df = st.session_state.df
        selected_item = df[df["Name"] == st.session_state.selected_option].iloc[0]
        
        st.write("Selected Name:", selected_item["Name"])
        st.write("Selected Artist:", selected_item["Artist"])
        st.write("Selected URI:", selected_item["URI"])

    st.session_state.radio_choice = "Song"
    st.session_state.song_url = st.session_state.s_url
    # Url = st.text_input(label="Song Url",key='song_url',on_change=update_song_url)
    song_page()
    state =st.button('Generate Recommendations')
    # with st.expander("Here's how to find any Song URL in Spotify"):
    #     st.write(""" 
    #             - Search for Song on the Spotify app
    #             - Right Click on the Song you like
    #             - Click "Share"
    #             - Choose "Copy link to Song"
    #         """)
    #     st.markdown("<br>", unsafe_allow_html=True)
    #     st.image('spotify_get_song_url.png')
    if state:
        song_recomm()
    
def result_page():
    if 'rs' not in st.session_state:
        st.error('Please select a model on the Home page and run "Generate Recommendations"')
    else:
        if not st.session_state.button_states.values():
            st.success('Top {} recommendations'.format(len(st.session_state.rs)))
        i = 0
        tracks = []
        original_tracks = []
        length_of_explanation = 1
        for index, uri in enumerate(st.session_state.rs):
            uri_link = "https://open.spotify.com/embed/track/" + uri + "?utm_source=generator&theme=0"
            components.iframe(uri_link, height=80)
         
            # Create a button for each URI and store its state
            if uri not in st.session_state.button_states:
                st.session_state.button_states[uri] = False
                
            track_name, artist_name = get_track_info(uri)
            full_song_title = '{} by {}'.format(track_name, artist_name)
            original_tracks.append({'full_track_name': full_song_title, 'uri': uri})
            tracks.append({'track_name': track_name, 'artist_name': artist_name, 'uri': uri, 'index': index})
            explanation_button = st.button('Get explanation for {}'.format(track_name))          

            # When button is clicked, call get_track_info
            if explanation_button:
                with st.spinner('Getting explanation...'):
                    time.sleep(0.5)                      
                    if st.session_state.radio_choice == 'Song':
                        song_title, artist = get_track_info(uri)
                        print(song_title, artist)
                        full_song_title = '{} by {}'.format(song_title, artist)
                        found_index = None
                        key = None
                        for track in tracks:
                            if track['track_name'] == song_title:
                                found_index = track['index'] + 1
                                key = str(found_index)
                                break  # Exit the loop once the track is found
                        with open('data/results.json') as f:
                            data = json.load(f)
                        
                        songlist = [{'track_name': track, 'artist_name': artist}]
                        if st.session_state.explanation_length == "Verbose":
                            length_of_explanation = 5
                            song_objects = data["5"]
                            st.session_state.generated_explanation = song_objects[st.session_state.selected_song_index][0][key]
                        else: 
                            length_of_explanation = 1
                            song_objects = data["1"]
                            st.session_state.generated_explanation = song_objects[st.session_state.selected_song_index][0][key]
                              
                        st.success(st.session_state.generated_explanation)
                        st.session_state.explanation_status = True
                        st.session_state.button_states[uri] = True
        
        i += 1
        st.session_state.track_list = tracks
        print(original_tracks[5:])
        if i % 5 == 0:
            time.sleep(1)
            
def Explain_page():
    if 'explanation_status' not in st.session_state:
        st.error('Please select the "Get Explanation" button under one of the recommended tracks.')
    else:
        st.success('Explanation generated below for the selected track.')
        for track_explanation in st.session_state.explanation_status:
            st.text(track_explanation)
            
def Counter_page():
    if 'explanation_status' not in st.session_state:
        st.error('Please select the "Get Explanation" button under one of the recommended tracks.')
    else:
        st.header('Understanding Recommendations')
        st.markdown("<br>", unsafe_allow_html=True)
        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.')
    
        next_five = None
        for song in song_list:
            if song["title"] == st.session_state.selected_song_index:
                next_five = song["next_five"]
                break
            
        titles = [song['full_track_name'] for song in next_five]  # Get a list of song titles
        
        selected_title = st.selectbox('Select a song', titles)
        
        selected_song = next((song for song in next_five if song['full_track_name'] == selected_title), None)
        if selected_song:
            # st.session_state.selected_song_index = selected_title
            print(selected_song)
            song_uri = selected_song['uri']
            # st.session_state.s_url = song_uri
        
            uri_link = 'https://open.spotify.com/embed/track/' + song_uri
            # slot1 = st.empty()
            components.iframe(uri_link, height=100)
        
        counter_fact_button = st.button('Generate Explanation')
        
        if counter_fact_button:
            found_index = None
            key = None
            for index, track in enumerate(next_five):
                if track['full_track_name'] == selected_song['full_track_name']:
                    found_index = index + 1
                    key = str(found_index)
                    break  # Exit the loop once the track is found
            with open('data/results.json') as f:
                data = json.load(f)
                
            if st.session_state.explanation_length == "Verbose":
                length_of_explanation = 5
                song_objects = data["5"]
                st.session_state.generated_counter = song_objects[st.session_state.selected_song_index][1][key]
            else: 
                length_of_explanation = 1
                song_objects = data["1"]
                st.session_state.generated_counter = song_objects[st.session_state.selected_song_index][1][key]
                
            st.success(st.session_state.generated_counter)
        
        

def Log_page():
    log=st.checkbox('Display Output', True, key='display_output')
    if log == True:
     if 'err' in st.session_state:
        st.write(st.session_state.err)
    with open('data/streamlit.csv') as f:
        st.download_button('Download Dataset', f,file_name='streamlit.csv')
def About_page():
    st.header('Development')
    """
    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.
    [Github](https://github.com/abdelrhmanelruby)  [Linkedin](https://www.linkedin.com/in/abdelrhmanelruby/) Email : abdelrhmanelruby@gmail.com
    """
    st.subheader('Spotify Million Playlist Dataset')
    """
    For this project, I'm using the Million Playlist Dataset, which, as its name implies, consists of one million playlists.
    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.
    """

    """
    It is created by sampling playlists from the billions of playlists that Spotify users have created over the years. 
    Playlists that meet the following criteria were selected at random:
    - Created by a user that resides in the United States and is at least 13 years old
    - Was a public playlist at the time the MPD was generated
    - Contains at least 5 tracks
    - Contains no more than 250 tracks
    - Contains at least 3 unique artists
    - Contains at least 2 unique albums
    - Has no local tracks (local tracks are non-Spotify tracks that a user has on their local device
    - Has at least one follower (not including the creator
    - Was created after January 1, 2010 and before December 1, 2017
    - Does not have an offensive title
    - Does not have an adult-oriented title if the playlist was created by a user under 18 years of age

    Information about the Dataset [here](https://www.aicrowd.com/challenges/spotify-million-playlist-dataset-challenge)
    """
    st.subheader('Audio Features Explanation')
    """
    | Variable | Description |
    | :----: | :---: |
    | 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. |
    | 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. |
    | 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. |
    | 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. |
    | 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. |
    | 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. |
    | 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. |
    | 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. |
    | 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. |
    | 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. |
    | 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". |
    | 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). |
    
    Information about features: [here](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-audio-features)
    """
    

def main():
    spr_sidebar()        
    if st.session_state.app_mode == 'Home':
        home_page()
    if st.session_state.app_mode == 'Recommended':
        result_page()
    # if st.session_state.app_mode == 'About':
    #     About_page()
    if st.session_state.app_mode == 'Counter':
        Counter_page()
    if st.session_state.app_mode == 'Explanation':
        Explain_page()
# Run main()
if __name__ == '__main__':
    main()