jisaacso219 commited on
Commit
52a6c11
·
verified ·
1 Parent(s): 4082b56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -89
app.py CHANGED
@@ -4,111 +4,131 @@ import spotipy
4
  from spotipy.oauth2 import SpotifyOAuth
5
  import random
6
 
7
- # Load environment variables securely from Hugging Face secrets
8
- CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"]
 
 
 
9
  CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]
10
- REDIRECT_URI = os.environ.get("SPOTIFY_REDIRECT_URI", "https://jisaacso219-rng-shuffle.hf.space/") # ✅ Updated to match registered redirect URI
11
- SCOPE = "user-read-playback-state user-modify-playback-state playlist-read-private"
 
 
 
12
 
13
  sp_oauth = SpotifyOAuth(
14
  client_id=CLIENT_ID,
15
  client_secret=CLIENT_SECRET,
16
  redirect_uri=REDIRECT_URI,
17
- scope=SCOPE
 
18
  )
19
 
20
- sp = None # Will be set after authorization
21
  user_playlists = {}
22
- selected_playlist_id = None
23
 
24
  def get_auth_url():
25
  return sp_oauth.get_authorize_url()
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.Column():
32
- gr.HTML(f"""
33
- <a href='{get_auth_url()}' target='_blank'>
34
- <button style='font-size: 16px; padding: 10px 20px; width: 100%; background-color: #4f46e5; color: white; border: none; border-radius: 6px;'>🔐 Step 1: Login to Spotify</button>
35
- </a>
36
- <script>
37
- window.onload = () => {{
38
- const params = new URLSearchParams(window.location.search);
39
- const code = params.get("code");
40
- if (code) {{
41
- const textbox = document.querySelector("textarea");
42
- if (textbox) {{
43
- textbox.value = code;
44
- }}
45
- }}
46
- }}
47
- </script>
48
- """)
49
-
50
- auth_code_box = gr.Textbox(label="Step 2: Paste authorization code", placeholder="...?code=ABC123")
51
- authorize_button = gr.Button("✅ Step 3: Complete Authorization")
52
- login_status = gr.Markdown(visible=False)
53
- playlist_dropdown = gr.Dropdown(choices=[], label="Step 4: 🎧 Select a Playlist", visible=False)
54
- shuffle_button = gr.Button("🔀 Step 5: Shuffle and Play", visible=False)
55
- result_box = gr.Markdown(visible=False)
56
-
57
- def check_login(code):
58
- global sp, user_playlists
59
- if not code:
60
- return (
61
- gr.update(visible=True, value="⚠️ No authorization code received."),
62
- gr.update(visible=False),
63
- gr.update(visible=False),
64
- gr.update(visible=False)
65
- )
66
- token_info = sp_oauth.get_access_token(code, as_dict=False)
67
- sp = spotipy.Spotify(auth=token_info)
68
- playlists = sp.current_user_playlists(limit=50)
69
- user_playlists = {p['name']: p['id'] for p in playlists['items']}
70
- return (
71
- gr.update(visible=True, value="✅ Logged in! Select your playlist below."),
72
- gr.update(visible=True, choices=list(user_playlists.keys())),
73
- gr.update(visible=True),
74
- gr.update(visible=True)
75
- )
76
-
77
- def shuffle_and_play(playlist_name):
78
- global selected_playlist_id
79
- if not sp:
80
- return gr.update(value="⚠️ You must login first.", visible=True)
81
-
82
- selected_playlist_id = user_playlists[playlist_name]
83
- tracks = []
84
- results = sp.playlist_tracks(selected_playlist_id)
85
- tracks.extend(results['items'])
86
- while results['next']:
87
- results = sp.next(results)
88
- tracks.extend(results['items'])
89
-
90
- uris = [t['track']['uri'] for t in tracks if t['track']]
91
- random.shuffle(uris)
92
-
93
- devices = sp.devices()
94
- if not devices['devices']:
95
- return gr.update(value="⚠️ No active Spotify devices found. Open the Spotify app and try again.", visible=True)
96
-
97
- device_id = devices['devices'][0]['id']
98
- sp.start_playback(device_id=device_id, uris=uris)
99
- return gr.update(value=f"▶️ Now playing: **{playlist_name}** in shuffled order!", visible=True)
100
-
101
- authorize_button.click(
102
- check_login,
103
- inputs=[auth_code_box],
104
- outputs=[login_status, playlist_dropdown, shuffle_button, result_box]
105
  )
106
- shuffle_button.click(
107
- shuffle_and_play,
108
- inputs=[playlist_dropdown],
109
- outputs=[result_box]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  )
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  if __name__ == "__main__":
113
  demo.launch()
114
 
 
4
  from spotipy.oauth2 import SpotifyOAuth
5
  import random
6
 
7
+ # 1. Hard‐code your redirect URI here:
8
+ REDIRECT_URI = "https://jisaacso219-rng-shuffle.hf.space/"
9
+
10
+ # 2. Keep your client creds in Secrets, as before:
11
+ CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"]
12
  CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]
13
+ SCOPE = (
14
+ "user-read-playback-state "
15
+ "user-modify-playback-state "
16
+ "playlist-read-private"
17
+ )
18
 
19
  sp_oauth = SpotifyOAuth(
20
  client_id=CLIENT_ID,
21
  client_secret=CLIENT_SECRET,
22
  redirect_uri=REDIRECT_URI,
23
+ scope=SCOPE,
24
+ show_dialog=True,
25
  )
26
 
27
+ sp = None
28
  user_playlists = {}
 
29
 
30
  def get_auth_url():
31
  return sp_oauth.get_authorize_url()
32
 
33
+ def check_login(code: str):
34
+ global sp, user_playlists
35
+ token = sp_oauth.get_access_token(code, as_dict=False)
36
+ sp = spotipy.Spotify(auth=token)
37
+ # pull their first 50 playlists
38
+ pls = sp.current_user_playlists(limit=50)["items"]
39
+ user_playlists = {p["name"]: p["id"] for p in pls}
40
+ return (
41
+ gr.update(visible=True, value="✅ Logged in! Choose a playlist below."),
42
+ gr.update(visible=True, choices=list(user_playlists.keys()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  )
44
+
45
+ def load_playlist_info(pl_name):
46
+ pid = user_playlists[pl_name]
47
+ data = sp.playlist(pid)
48
+ img = data["images"][0]["url"] if data["images"] else ""
49
+ owner = data["owner"]["display_name"]
50
+ desc = data.get("description", "")
51
+ html = f"""
52
+ <img src="{img}" width="300px" style="border-radius:10px;"/><br/>
53
+ <strong>{pl_name}</strong> by {owner}<br/>
54
+ {desc}
55
+ """
56
+ return gr.update(visible=True, value=html), gr.update(visible=True)
57
+
58
+ def shuffle_and_play(pl_name):
59
+ pid = user_playlists[pl_name]
60
+ # grab all tracks
61
+ tracks, results = [], sp.playlist_tracks(pid)
62
+ tracks += results["items"]
63
+ while results["next"]:
64
+ results = sp.next(results)
65
+ tracks += results["items"]
66
+ uris = [t["track"]["uri"] for t in tracks if t["track"]]
67
+ random.shuffle(uris)
68
+
69
+ # send to their first active device
70
+ devs = sp.devices()["devices"]
71
+ if not devs:
72
+ return gr.update(value="⚠️ No active Spotify device found. Start Spotify on one of your devices.", visible=True)
73
+ sp.start_playback(device_id=devs[0]["id"], uris=uris)
74
+
75
+ # show the first shuffled track’s info:
76
+ now = sp.current_playback()
77
+ if now and now.get("item"):
78
+ it = now["item"]
79
+ art = it["album"]["images"][0]["url"]
80
+ title = it["name"]
81
+ artists = ", ".join(a["name"] for a in it["artists"])
82
+ html = f"""
83
+ <img src="{art}" width="200px" style="border-radius:8px;"/><br/>
84
+ ▶️ <strong>{title}</strong><br/>
85
+ by {artists}
86
+ """
87
+ return gr.update(value=html, visible=True)
88
+ return gr.update(value="▶️ Playing your shuffled playlist!", visible=True)
89
+
90
+ with gr.Blocks() as demo:
91
+ gr.Markdown("## 🎵 RNG Spotify Playlist Shuffler")
92
+ gr.Markdown("Login, pick a playlist, then shuffle & play—all in one flow.")
93
+
94
+ # 1. Launch the login page
95
+ login_btn = gr.Button("🔐 Step 1: Login to Spotify")
96
+ login_btn.click(
97
+ lambda: get_auth_url(), None, None,
98
+ _js="(url) => window.open(url, '_blank')"
99
  )
100
 
101
+ # 2. Hidden “code” container (we’ll fill it automatically via JS)
102
+ code_box = gr.Textbox(visible=False, elem_id="auth_code")
103
+
104
+ # 3. When we have a code, finish the OAuth step…
105
+ status = gr.Markdown(visible=False)
106
+ demo.load( # run on every page‐load
107
+ fn=check_login,
108
+ inputs=[code_box],
109
+ outputs=[status, gr.State()],
110
+ _js="""
111
+ // on-load JS: grab ?code= from URL and stuff it into the hidden box
112
+ const p = new URLSearchParams(window.location.search);
113
+ const c = p.get("code");
114
+ if(c) {
115
+ document
116
+ .getElementById("component-auth_code")
117
+ .querySelector("textarea").value = c;
118
+ }
119
+ """
120
+ )
121
+
122
+ # 4. Playlist dropdown + info
123
+ dropdown = gr.Dropdown(choices=[], label="Step 2: Select a Playlist", visible=False)
124
+ info_html = gr.HTML(visible=False)
125
+ dropdown.change(load_playlist_info, [dropdown], [info_html, gr.update(dropdown, visible=True)])
126
+
127
+ # 5. Shuffle & play
128
+ result = gr.HTML(visible=False)
129
+ shuffle_btn = gr.Button("🔀 Step 3: Shuffle & Play", visible=False)
130
+ shuffle_btn.click(shuffle_and_play, [dropdown], [result])
131
+
132
  if __name__ == "__main__":
133
  demo.launch()
134