Mthrfkr commited on
Commit
64d9cba
·
verified ·
1 Parent(s): efa5acc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -50
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
  import requests
3
  import pandas as pd
4
- from io import BytesIO
5
 
6
  # —————— PARCHE Pydantic para FastAPI ——————
7
  import pydantic
@@ -20,90 +19,90 @@ client_utils.get_type = patched_get_type
20
 
21
  import gradio as gr
22
 
23
- # Config Spotify (Client Credentials)
24
  CLIENT_ID = os.getenv("SPOTIFY_CLIENT_IDS", "").split(',')[0]
25
  CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRETS", "").split(',')[0]
26
 
27
- # Obtiene token
28
  def get_token():
29
- r = requests.post(
30
  "https://accounts.spotify.com/api/token",
31
- data={"grant_type":"client_credentials"},
32
  auth=(CLIENT_ID, CLIENT_SECRET)
33
  )
34
- r.raise_for_status()
35
- return r.json()["access_token"]
36
 
37
- # Extrae ID de playlist
38
  def extract_pid(url):
39
  return url.strip().rstrip('/').split('/')[-1].split('?')[0]
40
 
41
- # Cache géneros
42
  _artist_cache = {}
43
 
44
  def get_artist_genres(aid, headers):
45
  if aid in _artist_cache:
46
  return _artist_cache[aid]
47
  r = requests.get(f"https://api.spotify.com/v1/artists/{aid}", headers=headers)
48
- genres = r.json().get('genres', []) if r.status_code==200 else []
49
  _artist_cache[aid] = genres
50
  return genres
51
 
52
- # Trae tabla
53
  def fetch_playlist_table(url):
54
  if not CLIENT_ID or not CLIENT_SECRET:
55
- return pd.DataFrame([{'Error':'Faltan credenciales'}])
56
  token = get_token()
57
  pid = extract_pid(url)
58
- headers={"Authorization":f"Bearer {token}"}
59
  meta = requests.get(f"https://api.spotify.com/v1/playlists/{pid}", headers=headers)
60
- if meta.status_code!=200:
61
- return pd.DataFrame([{'Error':f"Playlist error {meta.status_code}"}])
62
- total = meta.json().get('tracks',{}).get('total',0)
63
- records=[]
64
- limit=100
65
- offset=0
66
- while offset<total:
 
67
  r = requests.get(
68
  f"https://api.spotify.com/v1/playlists/{pid}/tracks",
69
  headers=headers,
70
- params={'limit':limit,'offset':offset}
71
  )
72
  r.raise_for_status()
73
- for item in r.json().get('items',[]):
74
- tr=item.get('track',{})
75
- if not tr: continue
76
- aid=tr['artists'][0]['id'] if tr.get('artists') else None
77
- genres=get_artist_genres(aid,headers) if aid else []
 
78
  records.append({
79
- 'Artist':tr['artists'][0]['name'] if tr.get('artists') else '',
80
- 'Title':tr.get('name',''),
81
- 'ISRC':tr.get('external_ids',{}).get('isrc',''),
82
- 'URL':tr.get('external_urls',{}).get('spotify',''),
83
- 'URI':tr.get('uri',''),
84
- 'Genres':', '.join(genres)
85
  })
86
- offset+=limit
87
  return pd.DataFrame(records)
88
 
89
- # Función principal: retorna DataFrame y bytes para descargar
90
- ndef main(url):
91
- df=fetch_playlist_table(url)
92
- buf=BytesIO()
93
- df.to_csv(buf,index=False)
94
- buf.seek(0)
95
- return df, ("playlist.csv", buf.getvalue())
96
 
97
- iface=gr.Interface(
 
 
 
 
98
  fn=main,
99
- inputs=gr.Textbox(label="URL de playlist"),
100
- outputs=[
101
- gr.Dataframe(headers=['Artist','Title','ISRC','URL','URI','Genres'], label="Tabla Spotify"),
102
- gr.File(label="Descargar CSV")
103
- ],
104
- title="🎵 Spotify Playlist Table",
105
- description="Muestra y descarga CSV sin usar disco"
106
  )
107
 
108
- if __name__=='__main__':
109
- iface.launch(server_name='0.0.0.0',server_port=7860)
 
1
  import os
2
  import requests
3
  import pandas as pd
 
4
 
5
  # —————— PARCHE Pydantic para FastAPI ——————
6
  import pydantic
 
19
 
20
  import gradio as gr
21
 
22
+ # Configuración Spotify (Client Credentials)
23
  CLIENT_ID = os.getenv("SPOTIFY_CLIENT_IDS", "").split(',')[0]
24
  CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRETS", "").split(',')[0]
25
 
26
+ # Función para obtener token
27
  def get_token():
28
+ resp = requests.post(
29
  "https://accounts.spotify.com/api/token",
30
+ data={"grant_type": "client_credentials"},
31
  auth=(CLIENT_ID, CLIENT_SECRET)
32
  )
33
+ resp.raise_for_status()
34
+ return resp.json()["access_token"]
35
 
36
+ # Extrae el ID de playlist de la URL
37
  def extract_pid(url):
38
  return url.strip().rstrip('/').split('/')[-1].split('?')[0]
39
 
40
+ # Caché de géneros por artista
41
  _artist_cache = {}
42
 
43
  def get_artist_genres(aid, headers):
44
  if aid in _artist_cache:
45
  return _artist_cache[aid]
46
  r = requests.get(f"https://api.spotify.com/v1/artists/{aid}", headers=headers)
47
+ genres = r.json().get('genres', []) if r.status_code == 200 else []
48
  _artist_cache[aid] = genres
49
  return genres
50
 
51
+ # Trae tabla y devuelve DataFrame
52
  def fetch_playlist_table(url):
53
  if not CLIENT_ID or not CLIENT_SECRET:
54
+ return pd.DataFrame([{'Error': 'Faltan credenciales'}])
55
  token = get_token()
56
  pid = extract_pid(url)
57
+ headers = {"Authorization": f"Bearer {token}"}
58
  meta = requests.get(f"https://api.spotify.com/v1/playlists/{pid}", headers=headers)
59
+ if meta.status_code != 200:
60
+ return pd.DataFrame([{'Error': f"Playlist error {meta.status_code}: {meta.json()}"}])
61
+ total = meta.json().get('tracks', {}).get('total', 0)
62
+ records = []
63
+ limit = 100
64
+ offset = 0
65
+ while offset < total:
66
+ params = {'limit': limit, 'offset': offset}
67
  r = requests.get(
68
  f"https://api.spotify.com/v1/playlists/{pid}/tracks",
69
  headers=headers,
70
+ params=params
71
  )
72
  r.raise_for_status()
73
+ for item in r.json().get('items', []):
74
+ tr = item.get('track', {})
75
+ if not tr:
76
+ continue
77
+ aid = tr['artists'][0]['id'] if tr.get('artists') else None
78
+ genres = get_artist_genres(aid, headers) if aid else []
79
  records.append({
80
+ 'Artist': tr['artists'][0]['name'] if tr.get('artists') else '',
81
+ 'Title': tr.get('name', ''),
82
+ 'ISRC': tr.get('external_ids', {}).get('isrc', ''),
83
+ 'URL': tr.get('external_urls', {}).get('spotify', ''),
84
+ 'URI': tr.get('uri', ''),
85
+ 'Genres': ', '.join(genres)
86
  })
87
+ offset += limit
88
  return pd.DataFrame(records)
89
 
90
+ # Función principal: retorna sólo DataFrame
 
 
 
 
 
 
91
 
92
+ def main(url):
93
+ return fetch_playlist_table(url)
94
+
95
+ # Configuración de la interfaz Gradio
96
+ iface = gr.Interface(
97
  fn=main,
98
+ inputs=gr.Textbox(label="URL de playlist", placeholder="https://open.spotify.com/playlist/..."),
99
+ outputs=gr.Dataframe(
100
+ headers=['Artist','Title','ISRC','URL','URI','Genres'],
101
+ label="Tabla de Playlist Spotify"
102
+ ),
103
+ title="🎵 Tabla de Playlist Spotify",
104
+ description="Trae Artist, Title, ISRC, URL, URI y Géneros de cada track"
105
  )
106
 
107
+ if __name__ == '__main__':
108
+ iface.launch(server_name='0.0.0.0', server_port=7860)