Spaces:
Running
Running
import os, json, random | |
import gradio as gr | |
import spotipy | |
from spotipy.oauth2 import SpotifyOAuth | |
# ββββββββββββββββββββββββββββββββββββββββββββββ | |
# Spotify app creds in HF Secrets | |
CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"] | |
CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"] | |
REDIRECT_URI = "https://jisaacso219-rng-shuffle.hf.space/" | |
# streaming scope for Web Playback SDK + playback | |
SCOPE = ( | |
"streaming " | |
"user-read-playback-state " | |
"user-modify-playback-state " | |
"playlist-read-private" | |
) | |
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(): | |
return sp_oauth.get_authorize_url() | |
def check_login(code: str): | |
global sp, user_playlists | |
# hide UI until we get a code | |
if not code: | |
return ( | |
gr.update(visible=False), | |
gr.update(visible=False), | |
gr.update(visible=False), | |
) | |
# exchange code for token | |
tokinfo = sp_oauth.get_access_token(code, as_dict=True) | |
access_token = tokinfo["access_token"] | |
sp = spotipy.Spotify(auth=access_token) | |
# fetch playlists | |
items = sp.current_user_playlists(limit=50)["items"] | |
user_playlists = {p["name"]: p["id"] for p in items} | |
# inject SDK + auto-bust + debug | |
sdk_js = f""" | |
<script> | |
if (window.self !== window.top) {{ | |
console.log("β οΈ Busting out of iframe"); | |
window.top.location.href = window.location.href; | |
}} | |
console.log("[SDK] ACCESS_TOKEN set"); | |
window.ACCESS_TOKEN = "{access_token}"; | |
</script> | |
<script src="https://sdk.scdn.co/spotify-player.js"></script> | |
<script> | |
window.onSpotifyWebPlaybackSDKReady = () => {{ | |
console.log("[SDK] Ready"); | |
const player = new Spotify.Player({{ | |
name: 'RNG Web Player', | |
getOAuthToken: cb => cb(window.ACCESS_TOKEN), | |
volume: 0.5 | |
}}); | |
['initialization_error','authentication_error','account_error','playback_error'] | |
.forEach(evt => player.addListener(evt, e => console.error(`[SDK ${evt}]`, e))); | |
player.addListener('ready', ({ device_id }) => {{ | |
console.log('[SDK] device_id:', device_id); | |
window._webDeviceId = device_id; | |
}}); | |
player.connect().then(ok => console.log('[SDK] connect()', ok)); | |
}}; | |
</script> | |
""" | |
return ( | |
gr.update(visible=True, value="β Logged in! Select a playlist below."), | |
gr.update(visible=True, choices=list(user_playlists.keys())), | |
gr.update(visible=True, value=sdk_js), | |
) | |
def load_playlist_info(name: str): | |
pid = user_playlists[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""" | |
<img src="{img}" width="300" style="border-radius:8px;"/><br/> | |
<strong>{name}</strong> by {owner}<br/>{desc} | |
""" | |
return html, gr.update(visible=True) | |
def shuffle_and_play(name: str): | |
pid = user_playlists[name] | |
# gather & shuffle URIs | |
tracks, res = [], sp.playlist_tracks(pid) | |
tracks.extend(res["items"]) | |
while res["next"]: | |
res = sp.next(res); tracks.extend(res["items"]) | |
uris = [t["track"]["uri"] for t in tracks if t["track"]] | |
random.shuffle(uris) | |
# fire Web Playback SDK | |
js_uris = json.dumps(uris) | |
play_js = f""" | |
<div id="player_debug" style="color:white;font-family:monospace;"></div> | |
<script> | |
console.log("[JS] playβ", window._webDeviceId, {len(uris)}, "tracks"); | |
(async () => {{ | |
try {{ | |
const resp = await fetch( | |
'https://api.spotify.com/v1/me/player/play?device_id=' + window._webDeviceId, | |
{{ | |
method:'PUT', | |
headers:{{'Authorization':'Bearer '+window.ACCESS_TOKEN,'Content-Type':'application/json'}}, | |
body:JSON.stringify({{uris:{js_uris}}}) | |
}} | |
); | |
const text = await resp.text(); | |
console.log("[JS] status:", resp.status, text); | |
document.getElementById("player_debug").innerText = | |
`[JS] status: ${{resp.status}} β ${{text}}`; | |
}} catch(e) {{ | |
console.error("[JS] Playback error:", e); | |
document.getElementById("player_debug").innerText = | |
"[JS] Playback error: " + e; | |
}} | |
}})(); | |
</script> | |
""" | |
return gr.update(value="βΆοΈ Now playing in-browser!"+play_js, visible=True) | |
with gr.Blocks() as demo: | |
# iframe-bust on initial load | |
gr.HTML(""" | |
<script> | |
if (window.self !== window.top) { | |
window.top.location.href = window.location.href; | |
} | |
</script>""") | |
# fallback link | |
gr.HTML('<a href="https://jisaacso219-rng-shuffle.hf.space/" target="_blank">' | |
'π Open standalone tab</a>') | |
gr.Markdown("1) Login β 2) Pick a playlist β 3) Shuffle & Play in-browser") | |
# Step 1: Login (same tab) | |
login_btn = gr.Button("π Step 1: Login to Spotify") | |
login_btn.click(None, None, None, | |
js=f"() => window.location.href = '{get_auth_url()}'" | |
) | |
# hidden components | |
code_box = gr.Textbox(visible=False, elem_id="auth_code") | |
status = gr.Markdown(visible=False) | |
playlist_dd = gr.Dropdown([], label="Step 2: Select a Playlist", visible=False) | |
sdk_html = gr.HTML(visible=False) | |
info_html = gr.HTML(visible=False) | |
shuffle_btn = gr.Button("π Step 3: Shuffle & Play", visible=False) | |
result = gr.HTML(visible=False) | |
# hidden button to trigger check_login | |
check_btn = gr.Button(visible=False, elem_id="check_code_btn") | |
check_btn.click( | |
check_login, | |
inputs=[code_box], | |
outputs=[status, playlist_dd, sdk_html], | |
) | |
# playlist info β reveal shuffle | |
playlist_dd.change(load_playlist_info, [playlist_dd], [info_html, shuffle_btn]) | |
shuffle_btn.click(shuffle_and_play, [playlist_dd], [result]) | |
# auto-fill & auto-click on load | |
gr.HTML(""" | |
<script> | |
window.addEventListener('load',() => { | |
const code = new URLSearchParams(window.location.search).get('code'); | |
console.log('[JS] got code:', code); | |
if (code) { | |
const ta = document.getElementById('component-auth_code')?.querySelector('textarea'); | |
const btn = document.getElementById('component-check_code_btn'); | |
if (ta) ta.value = code; | |
if (btn) btn.click(); | |
} | |
}); | |
</script> | |
""") | |
if __name__ == "__main__": | |
demo.launch(server_name="0.0.0.0", ssr_mode=False) | |