Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,7 @@ import shutil
|
|
| 9 |
|
| 10 |
# Lista de credenciales de API de Spotify
|
| 11 |
client_ids =[
|
|
|
|
| 12 |
'066bb9a3e0ac40aba89732f9a97249bf',
|
| 13 |
'cfbe3754c86048d1a82542a5ab432b9a',
|
| 14 |
'37492f29c7fe478391e8fd8fe66f3f1b',
|
|
@@ -22,6 +23,7 @@ client_ids =[
|
|
| 22 |
'e272c0705c7c4fd68937c58adaa446ed'
|
| 23 |
]
|
| 24 |
client_secrets = [
|
|
|
|
| 25 |
'9cdae5b56ec24aed91bb3958823ff39e',
|
| 26 |
'c55801afd5c24df3b8673cc07468c7b6',
|
| 27 |
'b61fa17afff64c8693ea5147b79562be',
|
|
@@ -36,6 +38,9 @@ client_secrets = [
|
|
| 36 |
]
|
| 37 |
current_api_index = 0
|
| 38 |
|
|
|
|
|
|
|
|
|
|
| 39 |
# Funciones para Spotify
|
| 40 |
def obtener_token(client_id, client_secret):
|
| 41 |
print(f"Obteniendo token de Spotify con client_id: {client_id}")
|
|
@@ -43,6 +48,8 @@ def obtener_token(client_id, client_secret):
|
|
| 43 |
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
| 44 |
payload = {'grant_type': 'client_credentials'}
|
| 45 |
response = requests.post(url, headers=headers, data=payload, auth=(client_id, client_secret))
|
|
|
|
|
|
|
| 46 |
if response.status_code == 200:
|
| 47 |
print(f"Token obtenido exitosamente para client_id: {client_id}")
|
| 48 |
return response.json().get('access_token')
|
|
@@ -56,20 +63,21 @@ def cambiar_api_key():
|
|
| 56 |
print(f"Cambiando a la siguiente API Key, 铆ndice actual: {current_api_index}")
|
| 57 |
return obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
|
| 58 |
|
| 59 |
-
def manejar_rate_limit(response):
|
| 60 |
if response.status_code == 429:
|
| 61 |
retry_after = int(response.headers.get('Retry-After', 1))
|
| 62 |
-
|
| 63 |
-
wait_time = retry_after + 10
|
| 64 |
print(f"L铆mite de peticiones alcanzado, Retry-After: {retry_after} segundos. Esperando {wait_time} segundos.")
|
| 65 |
time.sleep(wait_time)
|
| 66 |
return True
|
| 67 |
return False
|
| 68 |
|
| 69 |
def hacer_request_con_reintento(url, headers, params=None, max_retries=5):
|
| 70 |
-
|
|
|
|
| 71 |
response = requests.get(url, headers=headers, params=params)
|
| 72 |
-
|
|
|
|
| 73 |
continue
|
| 74 |
if response.status_code == 200:
|
| 75 |
return response
|
|
@@ -113,39 +121,72 @@ def obtener_canciones_playlist_spotify(token, playlist_id, playlist_name):
|
|
| 113 |
response = hacer_request_con_reintento(url, headers)
|
| 114 |
if response:
|
| 115 |
tracks = response.json().get('items')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
for item in tracks:
|
| 117 |
-
track = item
|
| 118 |
if track:
|
| 119 |
-
|
|
|
|
| 120 |
canciones.append({
|
| 121 |
'playlist_name': playlist_name,
|
| 122 |
'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
|
| 123 |
'titulo': track['name'],
|
| 124 |
'isrc': track['external_ids'].get('isrc', 'No disponible'),
|
| 125 |
'popularity': track.get('popularity', 'No disponible'),
|
| 126 |
-
'valence':
|
| 127 |
-
'danceability':
|
| 128 |
-
'energy':
|
| 129 |
-
'tempo':
|
| 130 |
-
'speechiness':
|
| 131 |
-
'instrumentalness':
|
| 132 |
'duration': track.get('duration_ms', 'No disponible'),
|
| 133 |
'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
|
| 134 |
-
'record_label':
|
| 135 |
})
|
| 136 |
return canciones
|
| 137 |
|
| 138 |
-
def
|
| 139 |
-
|
|
|
|
| 140 |
headers = {'Authorization': f'Bearer {token}'}
|
| 141 |
-
response = hacer_request_con_reintento(url, headers)
|
| 142 |
-
return response.json() if response else {}
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
headers = {'Authorization': f'Bearer {token}'}
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
# Funci贸n principal de la interfaz
|
| 151 |
def interface(project_name, query, num_spotify_playlists=50):
|
|
|
|
| 9 |
|
| 10 |
# Lista de credenciales de API de Spotify
|
| 11 |
client_ids =[
|
| 12 |
+
'0ef8df0b57864accb36251fb0b741935',
|
| 13 |
'066bb9a3e0ac40aba89732f9a97249bf',
|
| 14 |
'cfbe3754c86048d1a82542a5ab432b9a',
|
| 15 |
'37492f29c7fe478391e8fd8fe66f3f1b',
|
|
|
|
| 23 |
'e272c0705c7c4fd68937c58adaa446ed'
|
| 24 |
]
|
| 25 |
client_secrets = [
|
| 26 |
+
'8a1bb6f0f8f14feb9be2dff4b603bb5f',
|
| 27 |
'9cdae5b56ec24aed91bb3958823ff39e',
|
| 28 |
'c55801afd5c24df3b8673cc07468c7b6',
|
| 29 |
'b61fa17afff64c8693ea5147b79562be',
|
|
|
|
| 38 |
]
|
| 39 |
current_api_index = 0
|
| 40 |
|
| 41 |
+
# Contadores de solicitudes
|
| 42 |
+
solicitudes_totales = 0
|
| 43 |
+
|
| 44 |
# Funciones para Spotify
|
| 45 |
def obtener_token(client_id, client_secret):
|
| 46 |
print(f"Obteniendo token de Spotify con client_id: {client_id}")
|
|
|
|
| 48 |
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
| 49 |
payload = {'grant_type': 'client_credentials'}
|
| 50 |
response = requests.post(url, headers=headers, data=payload, auth=(client_id, client_secret))
|
| 51 |
+
global solicitudes_totales
|
| 52 |
+
solicitudes_totales += 1 # Contando solicitud
|
| 53 |
if response.status_code == 200:
|
| 54 |
print(f"Token obtenido exitosamente para client_id: {client_id}")
|
| 55 |
return response.json().get('access_token')
|
|
|
|
| 63 |
print(f"Cambiando a la siguiente API Key, 铆ndice actual: {current_api_index}")
|
| 64 |
return obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
|
| 65 |
|
| 66 |
+
def manejar_rate_limit(response, intento):
|
| 67 |
if response.status_code == 429:
|
| 68 |
retry_after = int(response.headers.get('Retry-After', 1))
|
| 69 |
+
wait_time = retry_after + 10 * (2 ** intento) # Retroceso exponencial
|
|
|
|
| 70 |
print(f"L铆mite de peticiones alcanzado, Retry-After: {retry_after} segundos. Esperando {wait_time} segundos.")
|
| 71 |
time.sleep(wait_time)
|
| 72 |
return True
|
| 73 |
return False
|
| 74 |
|
| 75 |
def hacer_request_con_reintento(url, headers, params=None, max_retries=5):
|
| 76 |
+
global solicitudes_totales
|
| 77 |
+
for intento in range(max_retries):
|
| 78 |
response = requests.get(url, headers=headers, params=params)
|
| 79 |
+
solicitudes_totales += 1 # Contando solicitud
|
| 80 |
+
if manejar_rate_limit(response, intento):
|
| 81 |
continue
|
| 82 |
if response.status_code == 200:
|
| 83 |
return response
|
|
|
|
| 121 |
response = hacer_request_con_reintento(url, headers)
|
| 122 |
if response:
|
| 123 |
tracks = response.json().get('items')
|
| 124 |
+
track_ids = [item['track']['id'] for item in tracks if item['track']]
|
| 125 |
+
album_ids = [item['track']['album']['id'] for item in tracks if item['track']]
|
| 126 |
+
|
| 127 |
+
# Obtener caracter铆sticas de audio en batch
|
| 128 |
+
audio_features = obtener_caracteristicas_audio_batch(token, track_ids)
|
| 129 |
+
# Obtener informaci贸n de 谩lbum en batch
|
| 130 |
+
album_info = obtener_record_label_spotify_batch(token, album_ids)
|
| 131 |
+
|
| 132 |
for item in tracks:
|
| 133 |
+
track = item['track']
|
| 134 |
if track:
|
| 135 |
+
audio = audio_features.get(track['id'], {})
|
| 136 |
+
album = album_info.get(track['album']['id'], {})
|
| 137 |
canciones.append({
|
| 138 |
'playlist_name': playlist_name,
|
| 139 |
'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
|
| 140 |
'titulo': track['name'],
|
| 141 |
'isrc': track['external_ids'].get('isrc', 'No disponible'),
|
| 142 |
'popularity': track.get('popularity', 'No disponible'),
|
| 143 |
+
'valence': audio.get('valence', 'No disponible'),
|
| 144 |
+
'danceability': audio.get('danceability', 'No disponible'),
|
| 145 |
+
'energy': audio.get('energy', 'No disponible'),
|
| 146 |
+
'tempo': audio.get('tempo', 'No disponible'),
|
| 147 |
+
'speechiness': audio.get('speechiness', 'No disponible'),
|
| 148 |
+
'instrumentalness': audio.get('instrumentalness', 'No disponible'),
|
| 149 |
'duration': track.get('duration_ms', 'No disponible'),
|
| 150 |
'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
|
| 151 |
+
'record_label': album.get('label', 'No disponible')
|
| 152 |
})
|
| 153 |
return canciones
|
| 154 |
|
| 155 |
+
def obtener_caracteristicas_audio_batch(token, track_ids):
|
| 156 |
+
audio_features = {}
|
| 157 |
+
url = 'https://api.spotify.com/v1/audio-features'
|
| 158 |
headers = {'Authorization': f'Bearer {token}'}
|
|
|
|
|
|
|
| 159 |
|
| 160 |
+
for i in range(0, len(track_ids), 100):
|
| 161 |
+
batch_ids = track_ids[i:i+100]
|
| 162 |
+
params = {'ids': ','.join(batch_ids)}
|
| 163 |
+
response = hacer_request_con_reintento(url, headers, params)
|
| 164 |
+
if response:
|
| 165 |
+
for feature in response.json().get('audio_features', []):
|
| 166 |
+
if feature:
|
| 167 |
+
audio_features[feature['id']] = feature
|
| 168 |
+
return audio_features
|
| 169 |
+
|
| 170 |
+
def obtener_record_label_spotify_batch(token, album_ids):
|
| 171 |
+
album_info = {}
|
| 172 |
+
url = 'https://api.spotify.com/v1/albums'
|
| 173 |
headers = {'Authorization': f'Bearer {token}'}
|
| 174 |
+
|
| 175 |
+
for i in range(0, len(album_ids), 20):
|
| 176 |
+
batch_ids = album_ids[i:i+20]
|
| 177 |
+
params = {'ids': ','.join(batch_ids)}
|
| 178 |
+
response = hacer_request_con_reintento(url, headers, params)
|
| 179 |
+
if response:
|
| 180 |
+
for album in response.json().get('albums', []):
|
| 181 |
+
if album:
|
| 182 |
+
album_info[album['id']] = {
|
| 183 |
+
'label': album.get('label', 'No disponible'),
|
| 184 |
+
'release_date': album.get('release_date', 'No disponible'),
|
| 185 |
+
'total_tracks': album.get('total_tracks', 'No disponible'),
|
| 186 |
+
'name': album.get('name', 'No disponible'),
|
| 187 |
+
'artists': [artist['name'] for artist in album.get('artists', [])]
|
| 188 |
+
}
|
| 189 |
+
return album_info
|
| 190 |
|
| 191 |
# Funci贸n principal de la interfaz
|
| 192 |
def interface(project_name, query, num_spotify_playlists=50):
|