| import gradio as gr | |
| from urllib.parse import urlparse, parse_qs | |
| import spotipy | |
| redirect_uri = "https://huggingface.co/sjw" | |
| scope = ['user-library-read', | |
| 'user-read-playback-state', | |
| 'user-modify-playback-state', | |
| 'playlist-modify-public', | |
| 'user-top-read'] | |
| sp_state = gr.State() | |
| device_id_state = gr.State() | |
| with gr.Blocks() as auth_page: | |
| with gr.Row(): | |
| client_id = gr.Textbox(label="Spotify Client ID") | |
| generate_link = gr.Button("Get Authentication Link") | |
| display_link = gr.Markdown() | |
| url = gr.Textbox(label="Paste URL") | |
| authorize_url = gr.Button("Authorize URL") | |
| auth_result = gr.Textbox() | |
| def spotify_auth(client_id, url=None): | |
| if url: | |
| parsed_url = urlparse(url) | |
| fragment = parsed_url.fragment | |
| access_token = parse_qs(fragment)['access_token'][0] | |
| sp = spotipy.Spotify(auth=access_token) | |
| device_id = sp.devices()['devices'][0]['id'] | |
| sp_state.value = sp | |
| device_id_state.value = device_id | |
| print(sp_state.value, device_id_state.value) | |
| results = sp_state.value.search(q="Passionfruit", type='track') | |
| track_uri = results['tracks']['items'][0]['uri'] | |
| sp_state.value.start_playback(device_id=device_id_state.value, uris=[track_uri]) | |
| return access_token | |
| else: | |
| auth_url = f"https://accounts.spotify.com/authorize?response_type=token&client_id={client_id}&scope={'%20'.join(scope)}&redirect_uri={redirect_uri}" | |
| return f"Please authorize the app by clicking [here]({auth_url}) and then paste the URL you are redirected to below." | |
| generate_link.click(spotify_auth, inputs=[client_id], outputs=display_link) | |
| authorize_url.click(spotify_auth, inputs=[client_id, url], outputs=auth_result) | |
| auth_page.launch() |