jisaacso219 commited on
Commit
9faaa03
ยท
verified ยท
1 Parent(s): c468cd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -69
app.py CHANGED
@@ -1,19 +1,16 @@
1
  import os
2
  import gradio as gr
3
- from flask import Flask, request, redirect
4
- from spotipy import Spotify, SpotifyOAuth
5
- from threading import Thread
6
  import random
7
  import time
8
 
9
- # ========== Spotify OAuth Setup ==========
10
- CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
11
- CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
12
- REDIRECT_URI = REDIRECT_URI = "https://jisaacso219-rng-shuffle.hf.space/callback"
13
  SCOPE = "user-read-playback-state user-modify-playback-state playlist-read-private"
14
 
15
- auth_codes = {} # Store auth tokens per session (not secure for prod)
16
-
17
  sp_oauth = SpotifyOAuth(
18
  client_id=CLIENT_ID,
19
  client_secret=CLIENT_SECRET,
@@ -21,70 +18,69 @@ sp_oauth = SpotifyOAuth(
21
  scope=SCOPE
22
  )
23
 
24
- # ========== Flask Redirect Server ==========
25
- app = Flask(__name__)
26
-
27
- @app.route("/callback")
28
- def callback():
29
- code = request.args.get("code")
30
- token_info = sp_oauth.get_access_token(code, as_dict=True)
31
- auth_codes["user"] = token_info # Single-user session for now
32
- return "โœ… Spotify login successful! You can return to the app."
33
-
34
- Thread(target=lambda: app.run(host="0.0.0.0", port=7861)).start()
35
-
36
- # ========== Gradio UI ==========
37
- def login():
38
- return sp_oauth.get_authorize_url()
39
-
40
- def list_playlists():
41
- if "user" not in auth_codes:
42
- return [], "โš ๏ธ Please log in first."
43
- sp = Spotify(auth=auth_codes["user"]["access_token"])
44
- pl = sp.current_user_playlists(limit=50)
45
- choices = {p['name']: p['id'] for p in pl['items']}
46
- return list(choices.keys()), "Select a playlist to shuffle and play."
47
-
48
- def shuffle_and_play(playlist_name):
49
- if "user" not in auth_codes:
50
- return "โš ๏ธ Please log in first."
51
- sp = Spotify(auth=auth_codes["user"]["access_token"])
52
- pl = sp.current_user_playlists(limit=50)
53
- pl_map = {p['name']: p['id'] for p in pl['items']}
54
- playlist_id = pl_map[playlist_name]
55
-
56
- tracks = []
57
- results = sp.playlist_tracks(playlist_id)
58
- tracks.extend(results['items'])
59
- while results['next']:
60
- results = sp.next(results)
 
 
 
 
 
61
  tracks.extend(results['items'])
 
 
 
62
 
63
- uris = [t['track']['uri'] for t in tracks if t['track']]
64
- random.shuffle(uris)
65
-
66
- devices = sp.devices()
67
- if not devices['devices']:
68
- return "โš ๏ธ No active Spotify devices found. Open the Spotify app and try again."
69
- device_id = devices['devices'][0]['id']
70
-
71
- sp.start_playback(device_id=device_id, uris=uris)
72
- return f"โ–ถ๏ธ Playing {len(uris)} shuffled tracks from '{playlist_name}'!"
73
 
74
- with gr.Blocks() as demo:
75
- gr.Markdown("# ๐ŸŽถ Spotify Playlist Shuffler")
76
- login_btn = gr.Button("๐Ÿ” Log in to Spotify")
77
- login_out = gr.Textbox(label="Login URL")
78
 
79
- playlist_list = gr.Dropdown(label="Your Playlists")
80
- refresh_btn = gr.Button("๐Ÿ”„ Load My Playlists")
81
- status = gr.Textbox()
82
 
83
- play_btn = gr.Button("โ–ถ๏ธ Shuffle + Play")
84
- result = gr.Textbox()
85
 
86
- login_btn.click(fn=login, outputs=login_out)
87
- refresh_btn.click(fn=list_playlists, outputs=[playlist_list, status])
88
- play_btn.click(fn=shuffle_and_play, inputs=playlist_list, outputs=result)
89
 
90
- demo.launch(server_port=7860, server_name="0.0.0.0")
 
 
1
  import os
2
  import gradio as gr
3
+ import spotipy
4
+ from spotipy.oauth2 import SpotifyOAuth
 
5
  import random
6
  import time
7
 
8
+ # Load environment variables securely from Hugging Face secrets
9
+ CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"]
10
+ CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]
11
+ REDIRECT_URI = os.environ.get("SPOTIFY_REDIRECT_URI", "https://jisaacso219-rng-shuffle.hf.space/callback")
12
  SCOPE = "user-read-playback-state user-modify-playback-state playlist-read-private"
13
 
 
 
14
  sp_oauth = SpotifyOAuth(
15
  client_id=CLIENT_ID,
16
  client_secret=CLIENT_SECRET,
 
18
  scope=SCOPE
19
  )
20
 
21
+ auth_url = sp_oauth.get_authorize_url()
22
+
23
+ sp = None # Will be set after authorization
24
+ user_playlists = {}
25
+ selected_playlist_id = None
26
+
27
+ with gr.Blocks(title="RNG Spotify Playlist Shuffler") as demo:
28
+ gr.Markdown("## ๐ŸŽต RNG Spotify Playlist Shuffler", elem_id="title")
29
+ gr.Markdown("A clean and simple way to shuffle your Spotify playlists with one click.")
30
+
31
+ with gr.Row():
32
+ login_button = gr.Button("๐Ÿ” Login to Spotify")
33
+
34
+ login_status = gr.Markdown(visible=False)
35
+ playlist_dropdown = gr.Dropdown(choices=[], label="๐ŸŽง Select a Playlist", visible=False)
36
+ shuffle_button = gr.Button("๐Ÿ”€ Shuffle and Play", visible=False)
37
+ result_box = gr.Markdown(visible=False)
38
+
39
+ # Open Spotify login in a new tab
40
+ login_button.click(
41
+ None,
42
+ _js=f"() => window.open('{auth_url}', '_blank')"
43
+ )
44
+
45
+ def check_login(code):
46
+ global sp, user_playlists
47
+ if not code:
48
+ return gr.update(visible=True, value="โš ๏ธ No authorization code received."), gr.update(visible=False), gr.update(visible=False)
49
+ token_info = sp_oauth.get_access_token(code, as_dict=False)
50
+ sp = spotipy.Spotify(auth=token_info)
51
+ playlists = sp.current_user_playlists(limit=50)
52
+ user_playlists = {p['name']: p['id'] for p in playlists['items']}
53
+ return gr.update(visible=True, value="โœ… Logged in! Select your playlist below."), gr.update(visible=True, choices=list(user_playlists.keys())), gr.update(visible=True)
54
+
55
+ def shuffle_and_play(playlist_name):
56
+ global selected_playlist_id
57
+ if not sp:
58
+ return gr.update(value="โš ๏ธ You must login first.", visible=True)
59
+
60
+ selected_playlist_id = user_playlists[playlist_name]
61
+ tracks = []
62
+ results = sp.playlist_tracks(selected_playlist_id)
63
  tracks.extend(results['items'])
64
+ while results['next']:
65
+ results = sp.next(results)
66
+ tracks.extend(results['items'])
67
 
68
+ uris = [t['track']['uri'] for t in tracks if t['track']]
69
+ random.shuffle(uris)
 
 
 
 
 
 
 
 
70
 
71
+ devices = sp.devices()
72
+ if not devices['devices']:
73
+ return gr.update(value="โš ๏ธ No active Spotify devices found. Open the Spotify app and try again.", visible=True)
 
74
 
75
+ device_id = devices['devices'][0]['id']
76
+ sp.start_playback(device_id=device_id, uris=uris)
77
+ return gr.update(value=f"โ–ถ๏ธ Now playing: **{playlist_name}** in shuffled order!", visible=True)
78
 
79
+ code_box = gr.Textbox(label="Paste the authorization code from the redirected URL here", placeholder="...?code=ABC123", visible=True)
80
+ authorize_button = gr.Button("โœ… Complete Authorization", visible=True)
81
 
82
+ authorize_button.click(check_login, inputs=[code_box], outputs=[login_status, playlist_dropdown, shuffle_button])
83
+ shuffle_button.click(shuffle_and_play, inputs=[playlist_dropdown], outputs=[result_box])
 
84
 
85
+ if __name__ == "__main__":
86
+ demo.launch()