File size: 8,816 Bytes
b10c9eb
 
 
 
 
 
 
 
 
 
c2d257f
b10c9eb
 
c2d257f
 
 
 
b10c9eb
 
 
 
 
 
 
 
 
 
 
 
d99b97e
b10c9eb
 
 
 
 
 
 
 
 
 
 
 
c2d257f
 
 
b7996a5
c2d257f
 
 
 
 
 
 
b10c9eb
 
 
 
 
 
 
 
eb07038
 
b10c9eb
 
 
c2d257f
 
b10c9eb
c2d257f
 
 
 
 
 
 
e91a84d
b10c9eb
 
 
 
 
 
 
 
 
b7996a5
 
b10c9eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9be7350
b10c9eb
9be7350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b10c9eb
9be7350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b10c9eb
c2d257f
 
 
 
b7996a5
c2d257f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b10c9eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import numpy as np
import os
import pickle
import spotipy
import spotipy.util as sp_util

dir_path = os.path.dirname(os.path.realpath(__file__))

# current mess: https://github.com/plamere/spotipy/issues/632
def centered_button(func, text, n_columns=7, disabled=False, args=None):
    columns = st.columns(np.ones(n_columns))
    with columns[n_columns//2]:
        if 'button' in str(func):
            return func(text, disabled=disabled)
        else:
            return func(text)

# get credentials
def setup_credentials():
    if 'client_id' in os.environ.keys() and 'client_secret' in os.environ.keys():
        client_info = dict(client_id=os.environ['client_id'],
                           client_secret=os.environ['client_secret'])
    else:
        with open(dir_path + "/ids.pk", 'rb') as f:
            client_info = pickle.load(f)

    os.environ['SPOTIPY_CLIENT_ID'] = client_info['client_id']
    os.environ['SPOTIPY_CLIENT_SECRET'] = client_info['client_secret']
    os.environ['SPOTIPY_REDIRECT_URI'] = 'https://huggingface.co/spaces/ccolas/EmotionPlaylist/'
    return client_info

relevant_audio_features = ["danceability", "energy", "loudness", "mode", "valence", "tempo"]


def get_client():
    scope = "playlist-modify-public"
    token = sp_util.prompt_for_user_token(scope=scope)
    sp = spotipy.Spotify(auth=token)
    user_id = sp.me()['id']
    return sp, user_id

def add_button(url, text):
    st.write(f'''
        <center>
        <a style='color:black;' href="{url}">
            <button class='css-1cpxqw2'>
                {text}
            </button>
        </a></center>
        ''',
             unsafe_allow_html=True
             )

def new_get_client(session):
    scope = "playlist-modify-public"

    cache_handler = StreamlitCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(scope=scope,
                                               cache_handler=cache_handler,
                                               show_dialog=True)
    sp, user_id = None, None

    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        # Step 1. Display sign in link when no token
        auth_url = auth_manager.get_authorize_url()
        if 'code' not in st.experimental_get_query_params():
            add_button(auth_url, 'Log in')

        # st.markdown(f'<a href="{auth_url}" target="_self">Click here to log in</a>', unsafe_allow_html=True)
        # Step 2. Being redirected from Spotify auth page
        if 'code' in st.experimental_get_query_params():
            auth_manager.get_access_token(st.experimental_get_query_params()['code'])
            sp = spotipy.Spotify(auth_manager=auth_manager)
            user_id = sp.me()['id']

    return sp, user_id, auth_manager


def extract_uris_from_links(links, url_type):
    assert url_type in ['playlist', 'artist', 'user']
    urls = links.split('\n')
    uris = []
    for url in urls:
        if 'playlist' in url:
            uri = url.split(f'{url_type}/')[-1].split('?')[0]
        elif 'user' in url:
            uri = url.split(f'{url_type}/')[-1].split('?')[0]
        else:
            uri = url.split('?')[0]
        uris.append(uri)
    return uris

def wall_of_checkboxes(labels, max_width=10):
    n_labels = len(labels)
    n_rows = int(np.ceil(n_labels/max_width))
    checkboxes = []
    for i in range(n_rows):
        columns = st.columns(np.ones(max_width))
        row_length = n_labels % max_width if i == n_rows - 1 else max_width
        for j in range(row_length):
            with columns[j]:
                checkboxes.append(st.empty())
    return checkboxes

def find_legit_genre(glabel, legit_genres, verbose=False):
    legit_genres_formatted = [lg.replace('-', '').replace(' ', '') for lg in legit_genres]
    glabel_formatted = glabel.replace(' ', '').replace('-', '')
    if verbose: print('\n', glabel)
    best_match = None
    best_match_score = 0
    for legit_glabel, legit_glabel_formatted in zip(legit_genres, legit_genres_formatted):
        if 'jazz' in glabel_formatted:
            best_match = 'jazz'
            if verbose: print('\t', 'pop')
            break
        if 'ukpop' in glabel_formatted:
            best_match = 'pop'
            if verbose: print('\t', 'pop')
            break
        if legit_glabel_formatted == glabel_formatted:
            if verbose: print('\t', legit_glabel_formatted)
            best_match = legit_glabel
            break
        elif glabel_formatted in legit_glabel_formatted:
            if verbose: print('\t', legit_glabel_formatted)
            if len(glabel_formatted) > best_match_score:
                best_match = legit_glabel
                best_match_score = len(glabel_formatted)
        elif legit_glabel_formatted in glabel_formatted:
            if verbose: print('\t', legit_glabel_formatted)
            if len(legit_glabel_formatted) > best_match_score:
                best_match = legit_glabel
                best_match_score = len(legit_glabel_formatted)

    if best_match is None:
        return "unknown"
    else:
        return best_match


# def aggregate_genres(genres, legit_genres, verbose=False):
#     genres_output = dict()
#     legit_genres_formatted = [lg.replace('-', '').replace(' ', '') for lg in legit_genres]
#     for glabel in genres.keys():
#         if verbose: print('\n', glabel)
#         glabel_formatted = glabel.replace(' ', '').replace('-', '')
#         best_match = None
#         best_match_score = 0
#         for legit_glabel, legit_glabel_formatted in zip(legit_genres, legit_genres_formatted):
#             if 'jazz' in glabel_formatted:
#                 best_match = 'jazz'
#                 if verbose: print('\t', 'pop')
#                 break
#             if 'ukpop' in glabel_formatted:
#                 best_match = 'pop'
#                 if verbose: print('\t', 'pop')
#                 break
#             if legit_glabel_formatted == glabel_formatted:
#                 if verbose: print('\t', legit_glabel_formatted)
#                 best_match = legit_glabel
#                 break
#             elif glabel_formatted in legit_glabel_formatted:
#                 if verbose: print('\t', legit_glabel_formatted)
#                 if len(glabel_formatted) > best_match_score:
#                     best_match = legit_glabel
#                     best_match_score = len(glabel_formatted)
#             elif legit_glabel_formatted in glabel_formatted:
#                 if verbose: print('\t', legit_glabel_formatted)
#                 if len(legit_glabel_formatted) > best_match_score:
#                     best_match = legit_glabel
#                     best_match_score = len(legit_glabel_formatted)
#
#         if best_match is not None:
#             if verbose: print('\t', '-->', best_match)
#             if best_match in genres_output.keys():
#                 genres_output[best_match] += genres[glabel]
#             else:
#                 genres_output[best_match] = genres[glabel]
#         else:
#             if "unknown" in genres_output.keys():
#                 genres_output["unknown"] += genres[glabel]
#             else:
#                 genres_output["unknown"] = genres[glabel]
#     for k in genres_output.keys():
#         genres_output[k] = sorted(set(genres_output[k]))
#     return genres_output

def get_all_playlists_uris_from_users(sp, user_ids):
    all_uris = []
    all_names = []
    for user_id in user_ids:
        print(user_id)
        offset = 0
        done = False
        while not done:
            playlist_list = sp.user_playlists(user_id, offset=offset, limit=50)
            these_names = [p['name'] for p in playlist_list['items']]
            these_uris = [p['uri'] for p in playlist_list['items']]
            for name, uri in zip(these_names, these_uris):
                if uri not in all_uris:
                    all_uris.append(uri)
                    all_names.append(user_id + '/' + name)
            if len(playlist_list['items']) < offset:
                done = True
            else:
                offset += 50
    return all_uris, all_names




class StreamlitCacheHandler(spotipy.cache_handler.CacheHandler):
    """
    A cache handler that stores the token info in the session framework
    provided by streamlit.
    """

    def __init__(self, session):
        self.session = session

    def get_cached_token(self):
        token_info = None
        try:
            token_info = self.session["token_info"]
        except KeyError:
            print("Token not found in the session")

        return token_info

    def save_token_to_cache(self, token_info):
        try:
            self.session["token_info"] = token_info
        except Exception as e:
            print("Error saving token to cache: " + str(e))