ccolas commited on
Commit
b10c9eb
1 Parent(s): 9666561

Upload app_utils.py

Browse files
Files changed (1) hide show
  1. app_utils.py +155 -0
app_utils.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ dir_path = os.path.dirname(os.path.realpath(__file__))
9
+
10
+ # current mess: https://github.com/plamere/spotipy/issues/632
11
+ def centered_button(func, text, n_columns=7, args=None):
12
+ columns = st.columns(np.ones(n_columns))
13
+ with columns[n_columns//2]:
14
+ return func(text)
15
+
16
+ # get credentials
17
+ def setup_credentials():
18
+ if 'client_id' in os.environ.keys() and 'client_secret' in os.environ.keys():
19
+ client_info = dict(client_id=os.environ['client_id'],
20
+ client_secret=os.environ['client_secret'])
21
+ else:
22
+ with open(dir_path + "/ids.pk", 'rb') as f:
23
+ client_info = pickle.load(f)
24
+
25
+ os.environ['SPOTIPY_CLIENT_ID'] = client_info['client_id']
26
+ os.environ['SPOTIPY_CLIENT_SECRET'] = client_info['client_secret']
27
+ os.environ['SPOTIPY_REDIRECT_URI'] = 'http://localhost:8080/'
28
+ return client_info
29
+
30
+ relevant_audio_features = ["danceability", "energy", "loudness", "mode", "valence", "tempo"]
31
+
32
+
33
+ def get_client():
34
+ scope = "playlist-modify-public"
35
+ token = sp_util.prompt_for_user_token(scope=scope)
36
+ sp = spotipy.Spotify(auth=token)
37
+ user_id = sp.me()['id']
38
+ return sp, user_id
39
+
40
+
41
+ def new_get_client(session):
42
+ scope = "playlist-modify-public"
43
+ print('Here3')
44
+
45
+ cache_handler = StreamlitCacheHandler(session)
46
+ auth_manager = spotipy.oauth2.SpotifyOAuth(scope=scope,
47
+ cache_handler=cache_handler,
48
+ show_dialog=True)
49
+ print('Here4')
50
+
51
+ if not auth_manager.validate_token(cache_handler.get_cached_token()):
52
+ # Step 1. Display sign in link when no token
53
+ auth_url = auth_manager.get_authorize_url()
54
+ # st.markdown(f'[Click here to log in]({auth_url})', unsafe_allow_html=True)
55
+ login = centered_button(st.button, 'Log in', n_columns=5)
56
+ print('Here6')
57
+ if login:
58
+ print('Here7')
59
+ sp = spotipy.Spotify(auth_manager=auth_manager)
60
+ user_id = sp.me()['id']
61
+ else:
62
+ sp, user_id = None, None
63
+ return sp, user_id
64
+
65
+
66
+
67
+ def extract_uris_from_links(links, url_type):
68
+ assert url_type in ['playlist', 'artist', 'user']
69
+ urls = links.split('\n')
70
+ uris = []
71
+ for url in urls:
72
+ if 'playlist' in url:
73
+ uri = url.split(f'{url_type}/')[-1].split('?')[0]
74
+ else:
75
+ uri = url.split('?')[0]
76
+ uris.append(uri)
77
+ return uris
78
+
79
+ def wall_of_checkboxes(labels, max_width=10):
80
+ n_labels = len(labels)
81
+ n_rows = int(np.ceil(n_labels/max_width))
82
+ checkboxes = []
83
+ for i in range(n_rows):
84
+ columns = st.columns(np.ones(max_width))
85
+ row_length = n_labels % max_width if i == n_rows - 1 else max_width
86
+ for j in range(row_length):
87
+ with columns[j]:
88
+ checkboxes.append(st.empty())
89
+ return checkboxes
90
+
91
+ def aggregate_genres(genres, legit_genres, verbose=False):
92
+ genres_output = dict()
93
+ legit_genres_formatted = [lg.replace('-', '').replace(' ', '') for lg in legit_genres]
94
+ for glabel in genres.keys():
95
+ if verbose: print('\n', glabel)
96
+ glabel_formatted = glabel.replace(' ', '').replace('-', '')
97
+ best_match = None
98
+ best_match_score = 0
99
+ for legit_glabel, legit_glabel_formatted in zip(legit_genres, legit_genres_formatted):
100
+ if 'jazz' in glabel_formatted:
101
+ best_match = 'jazz'
102
+ if verbose: print('\t', 'pop')
103
+ break
104
+ if 'ukpop' in glabel_formatted:
105
+ best_match = 'pop'
106
+ if verbose: print('\t', 'pop')
107
+ break
108
+ if legit_glabel_formatted == glabel_formatted:
109
+ if verbose: print('\t', legit_glabel_formatted)
110
+ best_match = legit_glabel
111
+ break
112
+ elif glabel_formatted in legit_glabel_formatted:
113
+ if verbose: print('\t', legit_glabel_formatted)
114
+ if len(glabel_formatted) > best_match_score:
115
+ best_match = legit_glabel
116
+ best_match_score = len(glabel_formatted)
117
+ elif legit_glabel_formatted in glabel_formatted:
118
+ if verbose: print('\t', legit_glabel_formatted)
119
+ if len(legit_glabel_formatted) > best_match_score:
120
+ best_match = legit_glabel
121
+ best_match_score = len(legit_glabel_formatted)
122
+
123
+ if best_match is not None:
124
+ if verbose: print('\t', '-->', best_match)
125
+ if best_match in genres_output.keys():
126
+ genres_output[best_match] += genres[glabel]
127
+ else:
128
+ genres_output[best_match] = genres[glabel]
129
+ return genres_output
130
+
131
+
132
+
133
+ class StreamlitCacheHandler(spotipy.cache_handler.CacheHandler):
134
+ """
135
+ A cache handler that stores the token info in the session framework
136
+ provided by streamlit.
137
+ """
138
+
139
+ def __init__(self, session):
140
+ self.session = session
141
+
142
+ def get_cached_token(self):
143
+ token_info = None
144
+ try:
145
+ token_info = self.session["token_info"]
146
+ except KeyError:
147
+ print("Token not found in the session")
148
+
149
+ return token_info
150
+
151
+ def save_token_to_cache(self, token_info):
152
+ try:
153
+ self.session["token_info"] = token_info
154
+ except Exception as e:
155
+ print("Error saving token to cache: " + str(e))