Spaces:
Running
Running
File size: 4,501 Bytes
52c1c26 4524b1c dbdd344 9faaa03 dbdd344 5afe83b 9faaa03 5afe83b e4f4d5f dbdd344 52a6c11 dbdd344 7507bae 52a6c11 9faaa03 4bbe919 9faaa03 4524b1c b414958 a8c78b0 b414958 4524b1c 4bbe919 3582f7d 4bbe919 48b24f7 b6411f2 48b24f7 5afe83b 4bbe919 dc5eb33 52c1c26 5afe83b 4524b1c 5afe83b 4524b1c 5afe83b 4bbe919 5afe83b b6411f2 4bbe919 5afe83b 52c1c26 52a6c11 b6411f2 e4f4d5f 4bbe919 671016b 52a6c11 4524b1c 5afe83b 4bbe919 4524b1c 5afe83b 4524b1c 4bbe919 5afe83b f8df622 6645382 52c1c26 4bbe919 5709789 4524b1c b6411f2 4524b1c 4bbe919 dc5eb33 4524b1c b6411f2 4524b1c a8c78b0 5afe83b 4524b1c 5afe83b 4524b1c 5709789 4524b1c 5709789 4524b1c 03438b7 48b24f7 4bbe919 4524b1c 4bbe919 b6411f2 e4f4d5f 4bbe919 4524b1c 52a6c11 9faaa03 e4f4d5f 6645382 5709789 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
import os
import random
import time
import gradio as gr
import spotipy
from spotipy.oauth2 import SpotifyOAuth
CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"]
CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]
REDIRECT_URI = "https://jisaacso219-rng-shuffle.hf.space/"
SCOPE = "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 = {}
device_map = {}
def get_auth_url():
return sp_oauth.get_authorize_url()
def try_login(current_url, filter_keyword):
global sp, user_playlists, device_map
if "?code=" not in current_url:
return (
"π Please login to Spotify.",
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
)
code = current_url.split("?code=")[1].split("&")[0]
token_info = sp_oauth.get_access_token(code, as_dict=True)
access_token = token_info["access_token"]
sp = spotipy.Spotify(auth=access_token)
playlists = sp.current_user_playlists(limit=50)["items"]
user_playlists.clear()
for p in playlists:
name = p["name"]
if not filter_keyword or filter_keyword.lower() in name.lower():
user_playlists[name] = p["id"]
devices = sp.devices()["devices"]
device_map.clear()
for d in devices:
device_map[d["name"]] = d["id"]
if not device_map:
return (
"β οΈ No active Spotify devices found.",
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
)
return (
"β
Logged in!",
gr.update(visible=True, choices=list(user_playlists.keys())),
gr.update(visible=True, choices=list(device_map.keys())),
gr.update(visible=True),
)
def shuffle_and_play(playlist_name, device_name):
pid = user_playlists.get(playlist_name)
device_id = device_map.get(device_name)
if not pid or not device_id:
return "β Invalid playlist or device."
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)
try:
sp.start_playback(device_id=device_id, uris=uris[:100])
for uri in uris[100:]:
sp.add_to_queue(uri, device_id=device_id)
time.sleep(0.1)
return f"βΆοΈ Now playing **{playlist_name}** on **{device_name}**."
except Exception as e:
return f"β Playback failed: {str(e)}"
def now_playing():
try:
data = sp.current_playback()
if not data or not data.get("is_playing"):
return "β οΈ Nothing is currently playing."
track = data["item"]
name = track["name"]
artist = ", ".join([a["name"] for a in track["artists"]])
album = track["album"]["name"]
image = track["album"]["images"][0]["url"]
html = f"""
<img src='{image}' width='300'><br>
<b>{name}</b> by {artist}<br/>
<i>{album}</i>
"""
return html
except Exception as e:
return f"β Error fetching current track: {e}"
with gr.Blocks() as demo:
gr.Markdown("## π΅ RNG Spotify Playlist Shuffler")
gr.HTML(f'<a href="{get_auth_url()}"><button style="width:100%;height:40px;">π Login to Spotify</button></a>')
url_state = gr.Textbox(visible=False)
filter_txt = gr.Textbox(label="Optional: Filter Playlists by Keyword")
status = gr.Markdown()
playlist_dd = gr.Dropdown(label="Step 2: Select a Playlist", visible=False)
device_dd = gr.Dropdown(label="Step 3: Select a Device", visible=False)
shuffle_btn = gr.Button("π Step 4: Shuffle & Play", visible=False)
result = gr.Markdown()
now_box = gr.HTML()
refresh_btn = gr.Button("π Show Current Track")
demo.load(
fn=try_login,
inputs=[url_state, filter_txt],
outputs=[status, playlist_dd, device_dd, shuffle_btn],
js="() => { return [window.location.href, '']; }"
)
shuffle_btn.click(shuffle_and_play, [playlist_dd, device_dd], [result])
refresh_btn.click(now_playing, outputs=[now_box])
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", ssr_mode=False)
|