import os
import json
import gradio as gr
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import random
# ——————————————————————————————————————————————
# 1) Redirect URI (must exactly match your Spotify Dashboard)
REDIRECT_URI = "https://jisaacso219-rng-shuffle.hf.space/"
# 2) Include `streaming` in your scopes for Web Playback SDK
SCOPE = (
"streaming "
"user-read-playback-state "
"user-modify-playback-state "
"playlist-read-private"
)
CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"]
CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]
sp_oauth = SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE,
show_dialog=True,
)
sp = None
user_playlists = {}
def get_auth_url():
url = sp_oauth.get_authorize_url()
print("[SERVER] Auth URL:", url)
return url
def check_login(code: str):
print("[SERVER] check_login code:", code)
global sp, user_playlists
if not code:
# still waiting for Spotify redirect
return (
gr.update(visible=False), # status
gr.update(visible=False), # dropdown
gr.update(visible=False), # html_token
)
# Exchange code for token
tokinfo = sp_oauth.get_access_token(code, as_dict=True)
access_token = tokinfo["access_token"]
print("[SERVER] Received token:", access_token[:8], "…")
sp = spotipy.Spotify(auth=access_token)
items = sp.current_user_playlists(limit=50)["items"]
user_playlists = {p["name"]: p["id"] for p in items}
print("[SERVER] Playlists:", list(user_playlists.keys()))
# Inject token + SDK loader + init + debug listeners
sdk_js = f"""
"""
return (
gr.update(visible=True, value="✅ Logged in! Choose a playlist below."),
gr.update(visible=True, choices=list(user_playlists.keys())),
gr.update(visible=True, value=sdk_js),
)
def load_playlist_info(pl_name: str):
print("[SERVER] load_playlist_info:", pl_name)
pid = user_playlists[pl_name]
data = sp.playlist(pid)
img = data["images"][0]["url"] if data["images"] else ""
owner = data["owner"]["display_name"]
desc = data.get("description", "")
html = f"""
{pl_name} by {owner}
{desc}
"""
return html, gr.update(visible=True)
def shuffle_and_play(pl_name: str):
print("[SERVER] shuffle_and_play:", pl_name)
pid = user_playlists.get(pl_name)
if not pid:
print("[SERVER] No playlist selected")
return gr.update(value="⚠️ No playlist selected.", visible=True)
# Gather & shuffle URIs
tracks, results = [], sp.playlist_tracks(pid)
tracks.extend(results["items"])
while results["next"]:
results = sp.next(results)
tracks.extend(results["items"])
uris = [t["track"]["uri"] for t in tracks if t["track"]]
random.shuffle(uris)
print(f"[SERVER] Shuffled {len(uris)} tracks")
# JS snippet with on‐UI debugging
uris_json = json.dumps(uris)
play_js = f"""