-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
745 lines (605 loc) · 36 KB
/
app.py
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
import streamlit as st
from sklearn.preprocessing import LabelEncoder, StandardScaler
from xgboost import XGBClassifier
import pandas as pd
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import joblib
import pickle
import re
import time
#streamlit run app.py
# Load the fitted objects and model
le_song_title = joblib.load('label_encoder_song_title.pkl')
le_artist = joblib.load('label_encoder_artist.pkl')
scaler = joblib.load('standard_scaler.pkl')
xgb = joblib.load('xgb_Model.pkl')
known_song_titles = joblib.load('known_song_titles.pkl')
known_artists = joblib.load('known_artists.pkl')
# Load the RandomForest model
rf_model = joblib.load('rf_model.pkl')
# Load the model
stacked_classifier = joblib.load('stacked_classifier.pkl')
gnb_model = joblib.load('gnb_model.pkl')
# Spotify API setup
client_id = '6291dd76ffb744299366b81b9cddfe5c'
client_secret = '14e1d9b1399a4d8e8ea34e09717b4815'
client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# Display the image from a URL
image_url = "https://storage.googleapis.com/pr-newsroom-wp/1/2018/11/Spotify_Logo_RGB_Green.png"
# Display the image
st.image(image_url, caption="Spotify Logo",use_column_width=True)
st.title("Spotify Track Predictor")
# Introduction and Instructions
st.markdown(
"""
## Welcome ! 🎶
### About This Project
This web app is designed to predict the musical preferences of its creator based on a dataset of songs the creator has listened to and labeled.
It utilizes a machine learning model trained on various song features to make these predictions.
Curious to see how the model generalized with your songs? Give it a try!
### How to Use
1. **Predict a Single Song**: To find out whether the model thinks the creator would like a specific song, simply input the Spotify URL of that song in the text box and hit "Enter"
2. **Analyze a Playlist**: If you have a playlist you'd like the model to analyze, paste the Spotify Playlist URL in the designated text box.
The model will then predict whether the creator would like each song in the playlist.
### Example URLs for Testing
Drag Link to Text Box / Copy URL
- **Song (Like)**: [FEEL LIKE - Josh Fudge](https://open.spotify.com/track/6MFtTpEpk8Q2hZKKfid7SE?si=21c8f420a3a64abe)
- **Song (Dislike)**: [Mia & Sebastian Theme - Justin Hurwitz](https://open.spotify.com/track/1Vk4yRsz0iBzDiZEoFMQyv?si=2bb3c40c02ef47a8)
- **Example Playlist**: [Spotify Playlist](https://open.spotify.com/playlist/1PkLqSEP0rFaw6pw94DZbP?si=873990a54baf4e07)
### Let's Get Started!
Scroll down to input your song or playlist URL and discover what the model predicts. Have fun!
"""
)
####################################################### SINGLE TRACK PREDICTION START ###########################################################
st.header("Predict Individual Tracks 🎶")
spotify_url = st.text_input("Enter Spotify Track URL:")
model_choice = st.selectbox(
'Choose the model for prediction:',
('Extreme Gradient Boosting', 'Random Forest', "Stacking Classifier", "Gaussian Naive Bayes")
)
if st.button("Predict Track"):
if model_choice == 'Extreme Gradient Boosting':
if spotify_url:
# Extract track ID from Spotify URL
track_id = spotify_url.split('/')[-1].split('?')[0]
# Get track features and info
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
# Create DataFrame from track features
df = pd.DataFrame([{
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}])
# Feature selection (Skipping this as your code already has the required features)
# df.drop(['acousticness', 'loudness', 'valence'], axis=1, inplace=True, errors='ignore')
# Handle unknown labels
df['song_title'] = df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
df['artist'] = df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
# Label encoding
df['song_title'] = le_song_title.transform(df['song_title'])
df['artist'] = le_artist.transform(df['artist'])
# Scaling
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
df[columns_to_standardize] = scaler.transform(df[columns_to_standardize])
# Make prediction
prediction = xgb.predict(df)
# Display the features
st.write("## Extracted Features")
st.dataframe(df)
# Display the prediction and track info
st.write(f"**Title:** {track_info['name']}")
st.write(f"**Artist:** {track_info['artists'][0]['name']}")
st.write(f"**Predicted Result:** {prediction[0]}")
# Display visuals based on prediction
if prediction[0] == 1:
st.success('I would probably like this song! 🎶👍')
st.image('https://www.kapwing.com/resources/content/images/2020/04/final_5e94ef5edc305d00159b08e7_769177.gif', use_column_width=True)
else:
st.warning('I might not enjoy this song. 😢👎')
st.image('https://media.tenor.com/qgIjYKSCYfAAAAAC/gordon-ramsey-i-dont.gif', use_column_width=True)
elif model_choice == 'Random Forest':
if spotify_url:
# Extract track ID from Spotify URL
track_id = spotify_url.split('/')[-1].split('?')[0]
# Get track features and info
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
# Create DataFrame from track features
df = pd.DataFrame([{
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}])
# Feature selection (Skipping this as your code already has the required features)
# df.drop(['acousticness', 'loudness', 'valence'], axis=1, inplace=True, errors='ignore')
# Handle unknown labels
df['song_title'] = df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
df['artist'] = df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
# Label encoding
df['song_title'] = le_song_title.transform(df['song_title'])
df['artist'] = le_artist.transform(df['artist'])
# Scaling
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
df[columns_to_standardize] = scaler.transform(df[columns_to_standardize])
# Make prediction with RandomForest model
prediction_rf = rf_model.predict(df)
# Display the features
st.write("## Extracted Features for RandomForest")
st.dataframe(df)
# Display the prediction and track info
st.write(f"**Title:** {track_info['name']}")
st.write(f"**Artist:** {track_info['artists'][0]['name']}")
st.write(f"**Predicted Result by RandomForest:** {prediction_rf[0]}")
# Display visuals based on prediction
if prediction_rf[0] == 1:
st.success('I would probably like this song! 🎶👍')
st.image('https://www.kapwing.com/resources/content/images/2020/04/final_5e94ef5edc305d00159b08e7_769177.gif', use_column_width=True)
else:
st.warning('I might not enjoy this song. 😢👎')
st.image('https://media.tenor.com/qgIjYKSCYfAAAAAC/gordon-ramsey-i-dont.gif', use_column_width=True)
elif model_choice == 'Stacking Classifier':
if spotify_url:
# Extract track ID from Spotify URL
track_id = spotify_url.split('/')[-1].split('?')[0]
# Get track features and info
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
# Create DataFrame from track features
df = pd.DataFrame([{
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}])
# Feature selection (Skipping this as your code already has the required features)
# df.drop(['acousticness', 'loudness', 'valence'], axis=1, inplace=True, errors='ignore')
# Handle unknown labels
df['song_title'] = df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
df['artist'] = df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
# Label encoding
df['song_title'] = le_song_title.transform(df['song_title'])
df['artist'] = le_artist.transform(df['artist'])
# Scaling
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
df[columns_to_standardize] = scaler.transform(df[columns_to_standardize])
# Make prediction with Stacking Classifier
prediction_stacked = stacked_classifier.predict(df)
# Display the features
st.write("## Extracted Features for RandomForest")
st.dataframe(df)
# Display the prediction and track info
st.write(f"**Title:** {track_info['name']}")
st.write(f"**Artist:** {track_info['artists'][0]['name']}")
st.write(f"**Predicted Result by RandomForest:** {prediction_stacked[0]}")
# Display visuals based on prediction
if prediction_stacked[0] == 1:
st.success('I would probably like this song! 🎶👍')
st.image('https://www.kapwing.com/resources/content/images/2020/04/final_5e94ef5edc305d00159b08e7_769177.gif', use_column_width=True)
else:
st.warning('I might not enjoy this song. 😢👎')
st.image('https://media.tenor.com/qgIjYKSCYfAAAAAC/gordon-ramsey-i-dont.gif', use_column_width=True)
elif model_choice == 'Gaussian Naive Bayes':
if spotify_url:
# Extract track ID from Spotify URL
track_id = spotify_url.split('/')[-1].split('?')[0]
# Get track features and info
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
# Create DataFrame from track features
df = pd.DataFrame([{
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}])
# Feature selection (Skipping this as your code already has the required features)
# df.drop(['acousticness', 'loudness', 'valence'], axis=1, inplace=True, errors='ignore')
# Handle unknown labels
df['song_title'] = df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
df['artist'] = df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
# Label encoding
df['song_title'] = le_song_title.transform(df['song_title'])
df['artist'] = le_artist.transform(df['artist'])
# Scaling
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
df[columns_to_standardize] = scaler.transform(df[columns_to_standardize])
# Make prediction with Stacking Classifier
prediction_gaussian = gnb_model.predict(df)
# Display the features
st.write("## Extracted Features for RandomForest")
st.dataframe(df)
# Display the prediction and track info
st.write(f"**Title:** {track_info['name']}")
st.write(f"**Artist:** {track_info['artists'][0]['name']}")
st.write(f"**Predicted Result by RandomForest:** {prediction_gaussian[0]}")
# Display visuals based on prediction
if prediction_gaussian[0] == 1:
st.success('I would probably like this song! 🎶👍')
st.image('https://www.kapwing.com/resources/content/images/2020/04/final_5e94ef5edc305d00159b08e7_769177.gif', use_column_width=True)
else:
st.warning('I might not enjoy this song. 😢👎')
st.image('https://media.tenor.com/qgIjYKSCYfAAAAAC/gordon-ramsey-i-dont.gif', use_column_width=True)
####################################################### SINGLE TRACK PREDICTION END ###########################################################
####################################################### Playlist TRACK PREDICTION Start ###########################################################
# Spotify API setup
client_id = '6291dd76ffb744299366b81b9cddfe5c'
client_secret = '14e1d9b1399a4d8e8ea34e09717b4815'
client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
st.header("Predict Playlist 📖")
# Text box for Playlist URL
playlist_url = st.text_input("Enter Spotify Playlist URL:")
# Initialize an empty list to store track IDs and an empty dataframe for features
track_ids = []
tracks_df = pd.DataFrame()
playListmodel_choice = st.selectbox(
'Choose the model for prediction:',
('XGB', 'RF','Stacking','GNB')
)
if st.button("Predict Playlist"):
if playListmodel_choice == 'XGB':
# Step 1: Extract Playlist ID from URL
if playlist_url:
pattern = r'https://open\.spotify\.com/playlist/(\w+)'
match = re.search(pattern, playlist_url)
if match:
playlist_id = match.group(1)
# Step 2: Fetch Track IDs from Playlist
results = sp.playlist_tracks(playlist_id)
tracks = results['items']
for track in tracks:
track_ids.append(track['track']['id'])
# Step 3: Retrieve Features for Each Track
for track_id in track_ids:
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
track_data = {
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}
tracks_df = pd.concat([tracks_df, pd.DataFrame([track_data])], ignore_index=True)
# Step 4: Preprocess the Features
tracks_df['song_title'] = tracks_df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
tracks_df['artist'] = tracks_df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
tracks_df['song_title'] = le_song_title.transform(tracks_df['song_title'])
tracks_df['artist'] = le_artist.transform(tracks_df['artist'])
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
tracks_df[columns_to_standardize] = scaler.transform(tracks_df[columns_to_standardize])
# Step 5: Make Predictions
predictions = xgb.predict(tracks_df)
# Display the total counts
count_liked = sum(predictions == 1)
count_disliked = sum(predictions == 0)
# Create columns for text and image
col1, col2 = st.columns([1, 1])
# First column: Total number of Liked songs and an image
with col1:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: green;'><h2>👍 Liked Songs: {count_liked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col1_1, col1_2, col1_3 = st.columns([1, 1, 1])
with col1_2:
st.image("https://www.trustedreviews.com/wp-content/uploads/sites/54/2021/02/Rickrolling-in-4K.jpg", width=150)
# Second column: Total number of Disliked songs and an image
with col2:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: red;'><h2>👎 Disliked Songs: {count_disliked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col2_1, col2_2, col2_3 = st.columns([1, 1, 1])
with col2_2:
st.image("https://i.guim.co.uk/img/media/cf19bda612430e6ff33122df8cec403700a38403/794_471_907_544/500.jpg?quality=85&auto=format&fit=max&s=9f3a32b8c2fd3cad2231cc164080ee5a", width=150)
# Step 6: Display Predictions
# Create a subheader for the predictions section
st.subheader("Song Predictions")
# Initialize an empty string to store the Markdown content
markdown_text = "| Title | Artist | Prediction |\n| --- | --- | --- |\n"
# Loop through each prediction and append to the Markdown content
for i, pred in enumerate(predictions):
song_title = tracks[i]['track']['name']
artist = tracks[i]['track']['artists'][0]['name']
like_status = '<span style="color: green;">Like</span>' if pred == 1 else '<span style="color: red;">Dislike</span>'
markdown_text += f"| {song_title} | {artist} | {like_status} |\n"
# Display the Markdown content as a table
st.markdown(markdown_text, unsafe_allow_html=True)
elif playListmodel_choice == 'RF':
# Step 1: Extract Playlist ID from URL
if playlist_url:
pattern = r'https://open\.spotify\.com/playlist/(\w+)'
match = re.search(pattern, playlist_url)
if match:
playlist_id = match.group(1)
# Step 2: Fetch Track IDs from Playlist
results = sp.playlist_tracks(playlist_id)
tracks = results['items']
for track in tracks:
track_ids.append(track['track']['id'])
# Step 3: Retrieve Features for Each Track
for track_id in track_ids:
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
track_data = {
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}
tracks_df = pd.concat([tracks_df, pd.DataFrame([track_data])], ignore_index=True)
# Step 4: Preprocess the Features
tracks_df['song_title'] = tracks_df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
tracks_df['artist'] = tracks_df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
tracks_df['song_title'] = le_song_title.transform(tracks_df['song_title'])
tracks_df['artist'] = le_artist.transform(tracks_df['artist'])
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
tracks_df[columns_to_standardize] = scaler.transform(tracks_df[columns_to_standardize])
# Step 5: Make Predictions using Random Forest
predictions = rf_model.predict(tracks_df)
# Display the total counts
count_liked = sum(predictions == 1)
count_disliked = sum(predictions == 0)
# Create columns for text and image
col1, col2 = st.columns([1, 1])
# First column: Total number of Liked songs and an image
with col1:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: green;'><h2>👍 Liked Songs: {count_liked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col1_1, col1_2, col1_3 = st.columns([1, 1, 1])
with col1_2:
st.image("https://www.trustedreviews.com/wp-content/uploads/sites/54/2021/02/Rickrolling-in-4K.jpg", width=150)
# Second column: Total number of Disliked songs and an image
with col2:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: red;'><h2>👎 Disliked Songs: {count_disliked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col2_1, col2_2, col2_3 = st.columns([1, 1, 1])
with col2_2:
st.image("https://i.guim.co.uk/img/media/cf19bda612430e6ff33122df8cec403700a38403/794_471_907_544/500.jpg?quality=85&auto=format&fit=max&s=9f3a32b8c2fd3cad2231cc164080ee5a", width=150)
# Step 6: Display Predictions
# Create a subheader for the predictions section
st.subheader("Song Predictions")
# Initialize an empty string to store the Markdown content
markdown_text = "| Title | Artist | Prediction |\n| --- | --- | --- |\n"
# Loop through each prediction and append to the Markdown content
for i, pred in enumerate(predictions):
song_title = tracks[i]['track']['name']
artist = tracks[i]['track']['artists'][0]['name']
like_status = '<span style="color: green;">Like</span>' if pred == 1 else '<span style="color: red;">Dislike</span>'
markdown_text += f"| {song_title} | {artist} | {like_status} |\n"
# Display the Markdown content as a table
st.markdown(markdown_text, unsafe_allow_html=True)
elif playListmodel_choice == 'Stacking':
# Step 1: Extract Playlist ID from URL
if playlist_url:
pattern = r'https://open\.spotify\.com/playlist/(\w+)'
match = re.search(pattern, playlist_url)
if match:
playlist_id = match.group(1)
# Step 2: Fetch Track IDs from Playlist
results = sp.playlist_tracks(playlist_id)
tracks = results['items']
for track in tracks:
track_ids.append(track['track']['id'])
# Step 3: Retrieve Features for Each Track
for track_id in track_ids:
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
track_data = {
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}
tracks_df = pd.concat([tracks_df, pd.DataFrame([track_data])], ignore_index=True)
# Step 4: Preprocess the Features
tracks_df['song_title'] = tracks_df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
tracks_df['artist'] = tracks_df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
tracks_df['song_title'] = le_song_title.transform(tracks_df['song_title'])
tracks_df['artist'] = le_artist.transform(tracks_df['artist'])
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
tracks_df[columns_to_standardize] = scaler.transform(tracks_df[columns_to_standardize])
# Step 5: Make Predictions using Random Forest
predictions = stacked_classifier.predict(tracks_df)
# Display the total counts
count_liked = sum(predictions == 1)
count_disliked = sum(predictions == 0)
# Create columns for text and image
col1, col2 = st.columns([1, 1])
# First column: Total number of Liked songs and an image
with col1:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: green;'><h2>👍 Liked Songs: {count_liked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col1_1, col1_2, col1_3 = st.columns([1, 1, 1])
with col1_2:
st.image("https://www.trustedreviews.com/wp-content/uploads/sites/54/2021/02/Rickrolling-in-4K.jpg", width=150)
# Second column: Total number of Disliked songs and an image
with col2:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: red;'><h2>👎 Disliked Songs: {count_disliked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col2_1, col2_2, col2_3 = st.columns([1, 1, 1])
with col2_2:
st.image("https://i.guim.co.uk/img/media/cf19bda612430e6ff33122df8cec403700a38403/794_471_907_544/500.jpg?quality=85&auto=format&fit=max&s=9f3a32b8c2fd3cad2231cc164080ee5a", width=150)
# Step 6: Display Predictions
# Create a subheader for the predictions section
st.subheader("Song Predictions")
# Initialize an empty string to store the Markdown content
markdown_text = "| Title | Artist | Prediction |\n| --- | --- | --- |\n"
# Loop through each prediction and append to the Markdown content
for i, pred in enumerate(predictions):
song_title = tracks[i]['track']['name']
artist = tracks[i]['track']['artists'][0]['name']
like_status = '<span style="color: green;">Like</span>' if pred == 1 else '<span style="color: red;">Dislike</span>'
markdown_text += f"| {song_title} | {artist} | {like_status} |\n"
# Display the Markdown content as a table
st.markdown(markdown_text, unsafe_allow_html=True)
elif playListmodel_choice == 'GNB':
# Step 1: Extract Playlist ID from URL
if playlist_url:
pattern = r'https://open\.spotify\.com/playlist/(\w+)'
match = re.search(pattern, playlist_url)
if match:
playlist_id = match.group(1)
# Step 2: Fetch Track IDs from Playlist
results = sp.playlist_tracks(playlist_id)
tracks = results['items']
for track in tracks:
track_ids.append(track['track']['id'])
# Step 3: Retrieve Features for Each Track
for track_id in track_ids:
track = sp.audio_features(track_id)[0]
track_info = sp.track(track_id)
track_data = {
'danceability': track['danceability'],
'duration_ms': track['duration_ms'],
'energy': track['energy'],
'instrumentalness': track['instrumentalness'],
'key': track['key'],
'liveness': track['liveness'],
'mode': track['mode'],
'speechiness': track['speechiness'],
'tempo': track['tempo'],
'time_signature': track['time_signature'],
'song_title': track_info['name'],
'artist': track_info['artists'][0]['name']
}
tracks_df = pd.concat([tracks_df, pd.DataFrame([track_data])], ignore_index=True)
# Step 4: Preprocess the Features
tracks_df['song_title'] = tracks_df['song_title'].apply(lambda x: x if x in known_song_titles else 'Unknown')
tracks_df['artist'] = tracks_df['artist'].apply(lambda x: x if x in known_artists else 'Unknown')
tracks_df['song_title'] = le_song_title.transform(tracks_df['song_title'])
tracks_df['artist'] = le_artist.transform(tracks_df['artist'])
columns_to_standardize = ['instrumentalness', 'danceability', 'duration_ms', 'energy', 'speechiness', 'liveness', 'tempo']
tracks_df[columns_to_standardize] = scaler.transform(tracks_df[columns_to_standardize])
# Step 5: Make Predictions using Random Forest
predictions = gnb_model.predict(tracks_df)
# Display the total counts
count_liked = sum(predictions == 1)
count_disliked = sum(predictions == 0)
# Create columns for text and image
col1, col2 = st.columns([1, 1])
# First column: Total number of Liked songs and an image
with col1:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: green;'><h2>👍 Liked Songs: {count_liked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col1_1, col1_2, col1_3 = st.columns([1, 1, 1])
with col1_2:
st.image("https://www.trustedreviews.com/wp-content/uploads/sites/54/2021/02/Rickrolling-in-4K.jpg", width=150)
# Second column: Total number of Disliked songs and an image
with col2:
# Using Markdown to center-align the text, add color, and an emoji
st.markdown(
f"<div style='text-align: center; color: red;'><h2>👎 Disliked Songs: {count_disliked}</h2></div>",
unsafe_allow_html=True,
)
# Display an image
# Center-aligning by using column layout
col2_1, col2_2, col2_3 = st.columns([1, 1, 1])
with col2_2:
st.image("https://i.guim.co.uk/img/media/cf19bda612430e6ff33122df8cec403700a38403/794_471_907_544/500.jpg?quality=85&auto=format&fit=max&s=9f3a32b8c2fd3cad2231cc164080ee5a", width=150)
# Step 6: Display Predictions
# Create a subheader for the predictions section
st.subheader("Song Predictions")
# Initialize an empty string to store the Markdown content
markdown_text = "| Title | Artist | Prediction |\n| --- | --- | --- |\n"
# Loop through each prediction and append to the Markdown content
for i, pred in enumerate(predictions):
song_title = tracks[i]['track']['name']
artist = tracks[i]['track']['artists'][0]['name']
like_status = '<span style="color: green;">Like</span>' if pred == 1 else '<span style="color: red;">Dislike</span>'
markdown_text += f"| {song_title} | {artist} | {like_status} |\n"
# Display the Markdown content as a table
st.markdown(markdown_text, unsafe_allow_html=True)
####################################################### Playlist TRACK PREDICTION End ###########################################################