Mthrfkr commited on
Commit
0367ee3
·
verified ·
1 Parent(s): e0020bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -21
app.py CHANGED
@@ -1,33 +1,105 @@
1
  import gradio as gr
 
2
  import pandas as pd
3
  from io import BytesIO
 
4
 
5
- # Simple example to test in-memory CSV download using gr.Download
6
- # Requires Gradio ≥4.44.1
 
 
 
 
 
7
 
8
- def generate_table_and_csv(text):
9
- # Create a DataFrame based on input text
10
- df = pd.DataFrame({
11
- "Input": [text],
12
- "Length": [len(text)]
13
- })
14
- # Convert DataFrame to CSV in memory
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  buffer = BytesIO()
16
- df.to_csv(buffer, index=False)
17
  buffer.seek(0)
18
- # Return DataFrame and a tuple (filename, bytes) for gr.Download
19
- return df, ("output.csv", buffer.getvalue())
20
 
21
  iface = gr.Interface(
22
- fn=generate_table_and_csv,
23
- inputs=gr.Textbox(label="Enter some text"),
24
- outputs=[
25
- gr.Dataframe(label="Generated Table"),
26
- gr.Download(label="Download CSV")
27
- ],
28
- title="Download Test",
29
- description="Type text to generate a table and download it as CSV (in memory)."
30
  )
31
 
32
  if __name__ == '__main__':
33
- iface.launch()
 
1
  import gradio as gr
2
+ import requests
3
  import pandas as pd
4
  from io import BytesIO
5
+ import os
6
 
7
+ # Configurar tus credenciales de Spotify en variables de entorno
8
+ # SPOTIFY_CLIENT_IDS="id1,id2"
9
+ # SPOTIFY_CLIENT_SECRETS="secret1,secret2"
10
+ client_ids = os.getenv("SPOTIFY_CLIENT_IDS", "").split(',')
11
+ client_secrets = os.getenv("SPOTIFY_CLIENT_SECRETS", "").split(',')
12
+ if not client_ids or not client_secrets:
13
+ raise ValueError("Faltan SPOTIFY_CLIENT_IDS o SPOTIFY_CLIENT_SECRETS en entorno")
14
 
15
+ current_idx = 0
16
+ req_count = 0
17
+ MAX_REQ = 95
18
+
19
+ def rotate_client():
20
+ global current_idx, req_count
21
+ current_idx = (current_idx + 1) % len(client_ids)
22
+ req_count = 0
23
+
24
+
25
+ def get_token():
26
+ global current_idx
27
+ for _ in client_ids:
28
+ cid = client_ids[current_idx]
29
+ csec = client_secrets[current_idx]
30
+ r = requests.post(
31
+ "https://accounts.spotify.com/api/token",
32
+ data={"grant_type": "client_credentials"},
33
+ auth=(cid, csec)
34
+ )
35
+ if r.status_code == 200:
36
+ return r.json()["access_token"]
37
+ rotate_client()
38
+ raise RuntimeError("No se pudo obtener token")
39
+
40
+
41
+ def make_request(url, params=None):
42
+ global req_count
43
+ token = get_token()
44
+ headers = {"Authorization": f"Bearer {token}"}
45
+ for _ in range(3):
46
+ r = requests.get(url, headers=headers, params=params)
47
+ req_count += 1
48
+ if r.status_code == 429:
49
+ rotate_client()
50
+ continue
51
+ if r.status_code == 200:
52
+ if req_count >= MAX_REQ:
53
+ rotate_client()
54
+ return r.json()
55
+ return None
56
+
57
+
58
+ def extract_id(u, kind):
59
+ u = u.split('?')[0].rstrip('/')
60
+ parts = u.split('/')
61
+ if kind in parts:
62
+ return parts[parts.index(kind) + 1]
63
+ return None
64
+
65
+
66
+ def fetch_playlist(playlist_url):
67
+ pl_id = extract_id(playlist_url, 'playlist')
68
+ url = f'https://api.spotify.com/v1/playlists/{pl_id}/tracks'
69
+ params = {'limit':100}
70
+ tracks = []
71
+ while url:
72
+ data = make_request(url, params)
73
+ if not data: break
74
+ for item in data.get('items', []):
75
+ t = item.get('track')
76
+ if t:
77
+ tracks.append({
78
+ 'Artist': t['artists'][0]['name'],
79
+ 'Title': t['name'],
80
+ 'ISRC': t.get('external_ids', {}).get('isrc',''),
81
+ 'URL': t.get('external_urls', {}).get('spotify',''),
82
+ 'URI': t.get('uri'),
83
+ 'Genre': ", ".join(make_request(f"https://api.spotify.com/v1/artists/{t['artists'][0]['id']}").get('genres',[]))
84
+ })
85
+ url = data.get('next')
86
+ return pd.DataFrame(tracks)
87
+
88
+
89
+ def export_csv(playlist_url):
90
+ df = fetch_playlist(playlist_url)
91
  buffer = BytesIO()
92
+ df.to_csv(buffer, index=False, encoding='utf-8')
93
  buffer.seek(0)
94
+ return (buffer, 'playlist.csv', 'text/csv')
 
95
 
96
  iface = gr.Interface(
97
+ fn=export_csv,
98
+ inputs=gr.Textbox(label="URL de playlist"),
99
+ outputs=gr.File(label="Descargar CSV"),
100
+ title="🔻 Descarga CSV de Playlist Spotify",
101
+ description="Introduce la URL de una playlist pública y descarga un CSV con Artist, Title, ISRC, URL, URI y Genre."
 
 
 
102
  )
103
 
104
  if __name__ == '__main__':
105
+ iface.launch(server_name='0.0.0.0', server_port=7860)