Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,8 @@ import time
|
|
| 5 |
from tempfile import NamedTemporaryFile
|
| 6 |
from openpyxl import Workbook
|
| 7 |
import shutil
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Lista de credenciales de API de Spotify
|
| 10 |
client_ids = [
|
|
@@ -27,6 +29,7 @@ client_secrets = [
|
|
| 27 |
]
|
| 28 |
current_api_index = 0
|
| 29 |
session = requests.Session()
|
|
|
|
| 30 |
|
| 31 |
def obtener_token(client_id, client_secret):
|
| 32 |
print(f"Obteniendo token de Spotify con client_id: {client_id}")
|
|
@@ -62,14 +65,22 @@ def obtener_nuevo_token():
|
|
| 62 |
print(f"Nuevo token obtenido: {token}")
|
| 63 |
return token
|
| 64 |
|
| 65 |
-
def
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
response = session.get(url, headers=headers, params=params)
|
| 69 |
-
if response.status_code == 429
|
| 70 |
-
print("Límite de peticiones alcanzado, esperando
|
| 71 |
-
time.sleep(
|
| 72 |
-
|
| 73 |
return response
|
| 74 |
|
| 75 |
def buscar_playlists_spotify(token, query, limit=50):
|
|
@@ -81,23 +92,16 @@ def buscar_playlists_spotify(token, query, limit=50):
|
|
| 81 |
try:
|
| 82 |
if limit <= 50:
|
| 83 |
params = {'q': query, 'type': 'playlist', 'limit': limit}
|
| 84 |
-
response =
|
| 85 |
-
if response.status_code == 429: # Límite alcanzado
|
| 86 |
-
print("Límite de peticiones alcanzado, cambiando API Key...")
|
| 87 |
-
response = realizar_solicitud_con_nuevo_token(url, headers, params)
|
| 88 |
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 89 |
else:
|
| 90 |
offset = 0
|
| 91 |
while limit > 0:
|
| 92 |
params = {'q': query, 'type': 'playlist', 'limit': min(50, limit), 'offset': offset}
|
| 93 |
-
response =
|
| 94 |
-
if response.status_code == 429: # Límite alcanzado
|
| 95 |
-
print("Límite de peticiones alcanzado, cambiando API Key...")
|
| 96 |
-
response = realizar_solicitud_con_nuevo_token(url, headers, params)
|
| 97 |
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 98 |
limit -= min(50, limit)
|
| 99 |
offset += 50
|
| 100 |
-
time.sleep(5) # Pausa de 5 segundos entre las solicitudes para evitar el límite de tasa
|
| 101 |
except Exception as e:
|
| 102 |
print(f"Error al buscar playlists: {e}")
|
| 103 |
|
|
@@ -110,16 +114,13 @@ def obtener_canciones_playlist_spotify(token, playlist_id, playlist_name):
|
|
| 110 |
canciones = []
|
| 111 |
|
| 112 |
try:
|
| 113 |
-
response =
|
| 114 |
-
if response.status_code == 429: # Límite alcanzado
|
| 115 |
-
print("Límite de peticiones alcanzado, cambiando API Key...")
|
| 116 |
-
response = realizar_solicitud_con_nuevo_token(url, headers, {})
|
| 117 |
if response.status_code == 200:
|
| 118 |
tracks = response.json().get('items')
|
| 119 |
for item in tracks:
|
| 120 |
track = item.get('track')
|
| 121 |
if track:
|
| 122 |
-
audio_features = obtener_caracteristicas_audio(track['id'])
|
| 123 |
canciones.append({
|
| 124 |
'playlist_name': playlist_name,
|
| 125 |
'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
|
|
@@ -134,29 +135,23 @@ def obtener_canciones_playlist_spotify(token, playlist_id, playlist_name):
|
|
| 134 |
'instrumentalness': audio_features.get('instrumentalness', 'No disponible'),
|
| 135 |
'duration': track.get('duration_ms', 'No disponible'),
|
| 136 |
'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
|
| 137 |
-
'record_label': obtener_record_label_spotify(track['album']['id'])
|
| 138 |
})
|
| 139 |
except Exception as e:
|
| 140 |
print(f"Error al obtener canciones de la playlist: {e}")
|
| 141 |
|
| 142 |
return canciones
|
| 143 |
|
| 144 |
-
def obtener_caracteristicas_audio(track_id):
|
| 145 |
url = f'https://api.spotify.com/v1/audio-features/{track_id}'
|
| 146 |
-
headers = {'Authorization': f'Bearer {
|
| 147 |
-
response =
|
| 148 |
-
if response.status_code == 429: # Límite alcanzado
|
| 149 |
-
print("Límite de peticiones alcanzado al obtener características de audio, cambiando API Key...")
|
| 150 |
-
response = realizar_solicitud_con_nuevo_token(url, headers, {})
|
| 151 |
return response.json() if response.status_code == 200 else {}
|
| 152 |
|
| 153 |
-
def obtener_record_label_spotify(album_id):
|
| 154 |
url = f'https://api.spotify.com/v1/albums/{album_id}'
|
| 155 |
-
headers = {'Authorization': f'Bearer {
|
| 156 |
-
response =
|
| 157 |
-
if response.status_code == 429: # Límite alcanzado
|
| 158 |
-
print("Límite de peticiones alcanzado al obtener la discográfica, cambiando API Key...")
|
| 159 |
-
response = realizar_solicitud_con_nuevo_token(url, headers, {})
|
| 160 |
album_info = response.json() if response.status_code == 200 else {}
|
| 161 |
return album_info.get('label', 'No disponible')
|
| 162 |
|
|
@@ -171,7 +166,6 @@ def interface(project_name, query, num_spotify_playlists=50):
|
|
| 171 |
for playlist in playlists_spotify:
|
| 172 |
songs = obtener_canciones_playlist_spotify(token_spotify, playlist['playlist_id'], playlist['playlist_name'])
|
| 173 |
canciones_spotify.extend(songs)
|
| 174 |
-
time.sleep(1) # Pausa de 1 segundo entre la obtención de canciones para evitar el límite de tasa
|
| 175 |
|
| 176 |
# Crear DataFrame
|
| 177 |
df = pd.DataFrame(canciones_spotify)
|
|
|
|
| 5 |
from tempfile import NamedTemporaryFile
|
| 6 |
from openpyxl import Workbook
|
| 7 |
import shutil
|
| 8 |
+
from collections import deque
|
| 9 |
+
from datetime import datetime, timedelta
|
| 10 |
|
| 11 |
# Lista de credenciales de API de Spotify
|
| 12 |
client_ids = [
|
|
|
|
| 29 |
]
|
| 30 |
current_api_index = 0
|
| 31 |
session = requests.Session()
|
| 32 |
+
requests_queue = deque(maxlen=100)
|
| 33 |
|
| 34 |
def obtener_token(client_id, client_secret):
|
| 35 |
print(f"Obteniendo token de Spotify con client_id: {client_id}")
|
|
|
|
| 65 |
print(f"Nuevo token obtenido: {token}")
|
| 66 |
return token
|
| 67 |
|
| 68 |
+
def manejar_limite_peticiones():
|
| 69 |
+
now = datetime.now()
|
| 70 |
+
while requests_queue and now - requests_queue[0] > timedelta(minutes=1):
|
| 71 |
+
requests_queue.popleft()
|
| 72 |
+
if len(requests_queue) >= 100:
|
| 73 |
+
print("Límite de 100 peticiones por minuto alcanzado, esperando...")
|
| 74 |
+
time.sleep(60 - (now - requests_queue[0]).seconds)
|
| 75 |
+
requests_queue.append(now)
|
| 76 |
+
|
| 77 |
+
def realizar_solicitud(url, headers, params):
|
| 78 |
+
manejar_limite_peticiones()
|
| 79 |
response = session.get(url, headers=headers, params=params)
|
| 80 |
+
if response.status_code == 429:
|
| 81 |
+
print("Límite de peticiones alcanzado, esperando y reintentando...")
|
| 82 |
+
time.sleep(60)
|
| 83 |
+
response = session.get(url, headers=headers, params=params)
|
| 84 |
return response
|
| 85 |
|
| 86 |
def buscar_playlists_spotify(token, query, limit=50):
|
|
|
|
| 92 |
try:
|
| 93 |
if limit <= 50:
|
| 94 |
params = {'q': query, 'type': 'playlist', 'limit': limit}
|
| 95 |
+
response = realizar_solicitud(url, headers, params)
|
|
|
|
|
|
|
|
|
|
| 96 |
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 97 |
else:
|
| 98 |
offset = 0
|
| 99 |
while limit > 0:
|
| 100 |
params = {'q': query, 'type': 'playlist', 'limit': min(50, limit), 'offset': offset}
|
| 101 |
+
response = realizar_solicitud(url, headers, params)
|
|
|
|
|
|
|
|
|
|
| 102 |
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 103 |
limit -= min(50, limit)
|
| 104 |
offset += 50
|
|
|
|
| 105 |
except Exception as e:
|
| 106 |
print(f"Error al buscar playlists: {e}")
|
| 107 |
|
|
|
|
| 114 |
canciones = []
|
| 115 |
|
| 116 |
try:
|
| 117 |
+
response = realizar_solicitud(url, headers, {})
|
|
|
|
|
|
|
|
|
|
| 118 |
if response.status_code == 200:
|
| 119 |
tracks = response.json().get('items')
|
| 120 |
for item in tracks:
|
| 121 |
track = item.get('track')
|
| 122 |
if track:
|
| 123 |
+
audio_features = obtener_caracteristicas_audio(token, track['id'])
|
| 124 |
canciones.append({
|
| 125 |
'playlist_name': playlist_name,
|
| 126 |
'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
|
|
|
|
| 135 |
'instrumentalness': audio_features.get('instrumentalness', 'No disponible'),
|
| 136 |
'duration': track.get('duration_ms', 'No disponible'),
|
| 137 |
'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
|
| 138 |
+
'record_label': obtener_record_label_spotify(track['album']['id'], token)
|
| 139 |
})
|
| 140 |
except Exception as e:
|
| 141 |
print(f"Error al obtener canciones de la playlist: {e}")
|
| 142 |
|
| 143 |
return canciones
|
| 144 |
|
| 145 |
+
def obtener_caracteristicas_audio(token, track_id):
|
| 146 |
url = f'https://api.spotify.com/v1/audio-features/{track_id}'
|
| 147 |
+
headers = {'Authorization': f'Bearer {token}'}
|
| 148 |
+
response = realizar_solicitud(url, headers, {})
|
|
|
|
|
|
|
|
|
|
| 149 |
return response.json() if response.status_code == 200 else {}
|
| 150 |
|
| 151 |
+
def obtener_record_label_spotify(album_id, token):
|
| 152 |
url = f'https://api.spotify.com/v1/albums/{album_id}'
|
| 153 |
+
headers = {'Authorization': f'Bearer {token}'}
|
| 154 |
+
response = realizar_solicitud(url, headers, {})
|
|
|
|
|
|
|
|
|
|
| 155 |
album_info = response.json() if response.status_code == 200 else {}
|
| 156 |
return album_info.get('label', 'No disponible')
|
| 157 |
|
|
|
|
| 166 |
for playlist in playlists_spotify:
|
| 167 |
songs = obtener_canciones_playlist_spotify(token_spotify, playlist['playlist_id'], playlist['playlist_name'])
|
| 168 |
canciones_spotify.extend(songs)
|
|
|
|
| 169 |
|
| 170 |
# Crear DataFrame
|
| 171 |
df = pd.DataFrame(canciones_spotify)
|