Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,190 +1,158 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
4 |
|
5 |
-
debug = False
|
6 |
dir_path = os.path.dirname(os.path.realpath(__file__))
|
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 |
-
print('
|
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 |
-
if
|
125 |
-
|
126 |
-
|
127 |
-
st.session_state['checkboxes'] = [False] * len(genres_labels)
|
128 |
-
for i_emc, emc in enumerate(empty_checkboxes):
|
129 |
-
st.session_state['checkboxes'][i_emc] = emc.checkbox(genres_labels[i_emc], value=st.session_state['checkboxes'][i_emc])
|
130 |
-
|
131 |
-
|
132 |
-
# filter songs by genres
|
133 |
-
selected_labels = [genres_labels[i] for i in range(len(genres_labels)) if st.session_state['checkboxes'][i]]
|
134 |
-
genre_selected_indexes = []
|
135 |
-
for label in selected_labels:
|
136 |
-
genre_selected_indexes += genres[label]
|
137 |
-
genre_selected_indexes = np.array(sorted(set(genre_selected_indexes)))
|
138 |
-
if len(genre_selected_indexes) < 10:
|
139 |
-
st.warning('Please select more genres or add more music sources.')
|
140 |
else:
|
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 |
-
if generation_button:
|
170 |
-
description = f'Emotion Playlist for Valence: {valence}, Energy: {energy}, Danceability: {danceability}). ' \
|
171 |
-
f'Playlist generated by the EmotionPlaylist app: https://huggingface.co/spaces/ccolas/EmotionPlaylist.'
|
172 |
-
playlist_info = sp.user_playlist_create(user_id, playlist_name, public=True, collaborative=False, description=description)
|
173 |
-
playlist_uri = playlist_info['uri'].split(':')[-1]
|
174 |
-
sp.playlist_add_items(playlist_uri, selected_tracks_uris)
|
175 |
-
st.write(
|
176 |
-
f"""
|
177 |
-
<html>
|
178 |
-
<body>
|
179 |
-
<center>
|
180 |
-
<iframe style = "border-radius:12px" src="https://open.spotify.com/embed/playlist/{playlist_uri}" allowtransparency="true"
|
181 |
-
allow="encrypted-media" width="80%" height="580" frameborder="0"></iframe></center></body></html>
|
182 |
-
""", unsafe_allow_html=True)
|
183 |
-
|
184 |
-
st.success(f'The playlist has been generated, find it [here](https://open.spotify.com/playlist/{playlist_uri}).')
|
185 |
-
|
186 |
-
|
187 |
-
stop = 1
|
188 |
-
|
189 |
-
if __name__ == '__main__':
|
190 |
-
setup_streamlite()
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import numpy as np
|
3 |
+
import os
|
4 |
+
import pickle
|
5 |
+
import spotipy
|
6 |
+
import spotipy.util as sp_util
|
7 |
+
import requests
|
8 |
|
|
|
9 |
dir_path = os.path.dirname(os.path.realpath(__file__))
|
10 |
+
|
11 |
+
# current mess: https://github.com/plamere/spotipy/issues/632
|
12 |
+
def centered_button(func, text, n_columns=7, args=None):
|
13 |
+
columns = st.columns(np.ones(n_columns))
|
14 |
+
with columns[n_columns//2]:
|
15 |
+
return func(text)
|
16 |
+
|
17 |
+
# get credentials
|
18 |
+
def setup_credentials():
|
19 |
+
if 'client_id' in os.environ.keys() and 'client_secret' in os.environ.keys():
|
20 |
+
client_info = dict(client_id=os.environ['client_id'],
|
21 |
+
client_secret=os.environ['client_secret'])
|
22 |
+
else:
|
23 |
+
with open(dir_path + "/ids.pk", 'rb') as f:
|
24 |
+
client_info = pickle.load(f)
|
25 |
+
|
26 |
+
os.environ['SPOTIPY_CLIENT_ID'] = client_info['client_id']
|
27 |
+
os.environ['SPOTIPY_CLIENT_SECRET'] = client_info['client_secret']
|
28 |
+
os.environ['SPOTIPY_REDIRECT_URI'] = 'http://localhost:8080/'
|
29 |
+
return client_info
|
30 |
+
|
31 |
+
relevant_audio_features = ["danceability", "energy", "loudness", "mode", "valence", "tempo"]
|
32 |
+
|
33 |
+
|
34 |
+
def get_client():
|
35 |
+
scope = "playlist-modify-public"
|
36 |
+
token = sp_util.prompt_for_user_token(scope=scope)
|
37 |
+
sp = spotipy.Spotify(auth=token)
|
38 |
+
user_id = sp.me()['id']
|
39 |
+
return sp, user_id
|
40 |
+
|
41 |
+
|
42 |
+
def new_get_client(session):
|
43 |
+
scope = "playlist-modify-public"
|
44 |
+
print('Here3')
|
45 |
+
|
46 |
+
cache_handler = StreamlitCacheHandler(session)
|
47 |
+
auth_manager = spotipy.oauth2.SpotifyOAuth(scope=scope,
|
48 |
+
cache_handler=cache_handler,
|
49 |
+
show_dialog=True)
|
50 |
+
print('Here4')
|
51 |
+
sp, user_id = None, None
|
52 |
+
|
53 |
+
if requests.get("code"):
|
54 |
+
# Step 2. Being redirected from Spotify auth page
|
55 |
+
auth_manager.get_access_token(requests.get("code"))
|
56 |
+
print('Here7')
|
57 |
+
sp = spotipy.Spotify(auth_manager=auth_manager)
|
58 |
+
user_id = sp.me()['id']
|
59 |
+
|
60 |
+
|
61 |
+
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
62 |
+
print('Here6')
|
63 |
+
# Step 1. Display sign in link when no token
|
64 |
+
auth_url = auth_manager.get_authorize_url()
|
65 |
+
st.markdown(f'[Click here to log in]({auth_url})', unsafe_allow_html=True)
|
66 |
+
return sp, user_id
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
def extract_uris_from_links(links, url_type):
|
71 |
+
assert url_type in ['playlist', 'artist', 'user']
|
72 |
+
urls = links.split('\n')
|
73 |
+
uris = []
|
74 |
+
for url in urls:
|
75 |
+
if 'playlist' in url:
|
76 |
+
uri = url.split(f'{url_type}/')[-1].split('?')[0]
|
77 |
+
else:
|
78 |
+
uri = url.split('?')[0]
|
79 |
+
uris.append(uri)
|
80 |
+
return uris
|
81 |
+
|
82 |
+
def wall_of_checkboxes(labels, max_width=10):
|
83 |
+
n_labels = len(labels)
|
84 |
+
n_rows = int(np.ceil(n_labels/max_width))
|
85 |
+
checkboxes = []
|
86 |
+
for i in range(n_rows):
|
87 |
+
columns = st.columns(np.ones(max_width))
|
88 |
+
row_length = n_labels % max_width if i == n_rows - 1 else max_width
|
89 |
+
for j in range(row_length):
|
90 |
+
with columns[j]:
|
91 |
+
checkboxes.append(st.empty())
|
92 |
+
return checkboxes
|
93 |
+
|
94 |
+
def aggregate_genres(genres, legit_genres, verbose=False):
|
95 |
+
genres_output = dict()
|
96 |
+
legit_genres_formatted = [lg.replace('-', '').replace(' ', '') for lg in legit_genres]
|
97 |
+
for glabel in genres.keys():
|
98 |
+
if verbose: print('\n', glabel)
|
99 |
+
glabel_formatted = glabel.replace(' ', '').replace('-', '')
|
100 |
+
best_match = None
|
101 |
+
best_match_score = 0
|
102 |
+
for legit_glabel, legit_glabel_formatted in zip(legit_genres, legit_genres_formatted):
|
103 |
+
if 'jazz' in glabel_formatted:
|
104 |
+
best_match = 'jazz'
|
105 |
+
if verbose: print('\t', 'pop')
|
106 |
+
break
|
107 |
+
if 'ukpop' in glabel_formatted:
|
108 |
+
best_match = 'pop'
|
109 |
+
if verbose: print('\t', 'pop')
|
110 |
+
break
|
111 |
+
if legit_glabel_formatted == glabel_formatted:
|
112 |
+
if verbose: print('\t', legit_glabel_formatted)
|
113 |
+
best_match = legit_glabel
|
114 |
+
break
|
115 |
+
elif glabel_formatted in legit_glabel_formatted:
|
116 |
+
if verbose: print('\t', legit_glabel_formatted)
|
117 |
+
if len(glabel_formatted) > best_match_score:
|
118 |
+
best_match = legit_glabel
|
119 |
+
best_match_score = len(glabel_formatted)
|
120 |
+
elif legit_glabel_formatted in glabel_formatted:
|
121 |
+
if verbose: print('\t', legit_glabel_formatted)
|
122 |
+
if len(legit_glabel_formatted) > best_match_score:
|
123 |
+
best_match = legit_glabel
|
124 |
+
best_match_score = len(legit_glabel_formatted)
|
125 |
+
|
126 |
+
if best_match is not None:
|
127 |
+
if verbose: print('\t', '-->', best_match)
|
128 |
+
if best_match in genres_output.keys():
|
129 |
+
genres_output[best_match] += genres[glabel]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
else:
|
131 |
+
genres_output[best_match] = genres[glabel]
|
132 |
+
return genres_output
|
133 |
+
|
134 |
+
|
135 |
+
|
136 |
+
class StreamlitCacheHandler(spotipy.cache_handler.CacheHandler):
|
137 |
+
"""
|
138 |
+
A cache handler that stores the token info in the session framework
|
139 |
+
provided by streamlit.
|
140 |
+
"""
|
141 |
+
|
142 |
+
def __init__(self, session):
|
143 |
+
self.session = session
|
144 |
+
|
145 |
+
def get_cached_token(self):
|
146 |
+
token_info = None
|
147 |
+
try:
|
148 |
+
token_info = self.session["token_info"]
|
149 |
+
except KeyError:
|
150 |
+
print("Token not found in the session")
|
151 |
+
|
152 |
+
return token_info
|
153 |
+
|
154 |
+
def save_token_to_cache(self, token_info):
|
155 |
+
try:
|
156 |
+
self.session["token_info"] = token_info
|
157 |
+
except Exception as e:
|
158 |
+
print("Error saving token to cache: " + str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|