Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,31 @@
|
|
|
|
|
| 1 |
import requests
|
|
|
|
| 2 |
import time
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
# Lista de credenciales de API de Spotify
|
| 5 |
client_ids = [
|
| 6 |
-
'807008cb2ce041178c1871973fc81716',
|
| 7 |
-
'
|
| 8 |
-
'
|
|
|
|
|
|
|
|
|
|
| 9 |
'e272c0705c7c4fd68937c58adaa446ed'
|
| 10 |
]
|
| 11 |
client_secrets = [
|
| 12 |
-
'b6c3fbe2304145e4b268f05eefd6ab2a',
|
| 13 |
-
'
|
| 14 |
-
'
|
|
|
|
|
|
|
|
|
|
| 15 |
'9fdfa58ea0a94ce7a0cb34fa19fb7d74'
|
| 16 |
]
|
| 17 |
current_api_index = 0
|
| 18 |
-
session = requests.Session()
|
| 19 |
|
| 20 |
def obtener_token(client_id, client_secret):
|
| 21 |
print(f"Obteniendo token de Spotify con client_id: {client_id}")
|
|
@@ -30,48 +40,151 @@ def obtener_token(client_id, client_secret):
|
|
| 30 |
print(f"Error al obtener token para client_id: {client_id}, status_code: {response.status_code}, response: {response.text}")
|
| 31 |
return None
|
| 32 |
|
| 33 |
-
def cerrar_y_reiniciar_sesion():
|
| 34 |
-
global session
|
| 35 |
-
if session:
|
| 36 |
-
session.close()
|
| 37 |
-
print("Sesión cerrada.")
|
| 38 |
-
session = requests.Session()
|
| 39 |
-
print("Nueva sesión creada.")
|
| 40 |
-
|
| 41 |
def cambiar_api_key():
|
| 42 |
global current_api_index
|
| 43 |
current_api_index = (current_api_index + 1) % len(client_ids)
|
| 44 |
print(f"Cambiando a la siguiente API Key, índice actual: {current_api_index}")
|
| 45 |
-
return client_ids[current_api_index], client_secrets[current_api_index]
|
| 46 |
-
|
| 47 |
-
def obtener_nuevo_token():
|
| 48 |
-
cerrar_y_reiniciar_sesion()
|
| 49 |
-
client_id, client_secret = cambiar_api_key()
|
| 50 |
-
token = obtener_token(client_id, client_secret)
|
| 51 |
-
print(f"Nuevo token obtenido: {token}")
|
| 52 |
-
return token
|
| 53 |
|
| 54 |
-
def
|
| 55 |
-
|
|
|
|
| 56 |
headers = {'Authorization': f'Bearer {token}'}
|
| 57 |
-
|
| 58 |
-
print(f"Solicitud realizada con nuevo token. Código de estado: {response.status_code}")
|
| 59 |
-
return response
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
if
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
import requests
|
| 3 |
+
import pandas as pd
|
| 4 |
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 = [
|
| 11 |
+
'807008cb2ce041178c1871973fc81716',
|
| 12 |
+
'107286416613436ab5c63b56d3564f9e',
|
| 13 |
+
'528d1d6733ba46eb8e9532e56ced61eb',
|
| 14 |
+
'aed6435c51484dc18b8c18aa74dd51f8',
|
| 15 |
+
'9df51caba5d247dc921b21de35a47c44',
|
| 16 |
+
'191227c66e0d4be692bc8ee73ea6eb3d',
|
| 17 |
'e272c0705c7c4fd68937c58adaa446ed'
|
| 18 |
]
|
| 19 |
client_secrets = [
|
| 20 |
+
'b6c3fbe2304145e4b268f05eefd6ab2a',
|
| 21 |
+
'4de4c14ed109420c9517c083b8018f8c',
|
| 22 |
+
'3dbdcf9a12634cfca9e6aca8d3093020',
|
| 23 |
+
'8662b33d594f4d198ea025d4aa9f0b98',
|
| 24 |
+
'0e39502ec7e74fe99bb74245678d5f0d',
|
| 25 |
+
'2d2a895d85874c088897dd9894dc64ad',
|
| 26 |
'9fdfa58ea0a94ce7a0cb34fa19fb7d74'
|
| 27 |
]
|
| 28 |
current_api_index = 0
|
|
|
|
| 29 |
|
| 30 |
def obtener_token(client_id, client_secret):
|
| 31 |
print(f"Obteniendo token de Spotify con client_id: {client_id}")
|
|
|
|
| 40 |
print(f"Error al obtener token para client_id: {client_id}, status_code: {response.status_code}, response: {response.text}")
|
| 41 |
return None
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def cambiar_api_key():
|
| 44 |
global current_api_index
|
| 45 |
current_api_index = (current_api_index + 1) % len(client_ids)
|
| 46 |
print(f"Cambiando a la siguiente API Key, índice actual: {current_api_index}")
|
| 47 |
+
return obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
def buscar_playlists_spotify(token, query, limit=50):
|
| 50 |
+
print("Buscando playlists en Spotify...")
|
| 51 |
+
url = 'https://api.spotify.com/v1/search'
|
| 52 |
headers = {'Authorization': f'Bearer {token}'}
|
| 53 |
+
playlists = []
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
try:
|
| 56 |
+
if limit <= 50:
|
| 57 |
+
params = {'q': query, 'type': 'playlist', 'limit': limit}
|
| 58 |
+
response = requests.get(url, headers=headers, params=params)
|
| 59 |
+
if response.status_code == 429: # Límite alcanzado
|
| 60 |
+
print("Límite de peticiones alcanzado, cambiando API Key...")
|
| 61 |
+
token = cambiar_api_key()
|
| 62 |
+
time.sleep(1) # Pausa de 1 segundo para evitar el límite de tasa
|
| 63 |
+
response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
|
| 64 |
+
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 65 |
+
else:
|
| 66 |
+
offset = 0
|
| 67 |
+
while limit > 0:
|
| 68 |
+
params = {'q': query, 'type': 'playlist', 'limit': min(50, limit), 'offset': offset}
|
| 69 |
+
response = requests.get(url, headers=headers, params=params)
|
| 70 |
+
if response.status_code == 429: # Límite alcanzado
|
| 71 |
+
print("Límite de peticiones alcanzado, cambiando API Key...")
|
| 72 |
+
token = cambiar_api_key()
|
| 73 |
+
time.sleep(1) # Pausa de 1 segundo para evitar el límite de tasa
|
| 74 |
+
response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
|
| 75 |
+
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 76 |
+
limit -= min(50, limit)
|
| 77 |
+
offset += 50
|
| 78 |
+
time.sleep(5) # Pausa de 5 segundos entre las solicitudes para evitar el límite de tasa
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"Error al buscar playlists: {e}")
|
| 81 |
|
| 82 |
+
return [{'playlist_id': playlist['id'], 'playlist_name': playlist['name']} for playlist in playlists]
|
| 83 |
+
|
| 84 |
+
def obtener_canciones_playlist_spotify(token, playlist_id, playlist_name):
|
| 85 |
+
print(f"Obteniendo canciones de la playlist {playlist_id} ({playlist_name}) de Spotify...")
|
| 86 |
+
url = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'
|
| 87 |
+
headers = {'Authorization': f'Bearer {token}'}
|
| 88 |
+
canciones = []
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
response = requests.get(url, headers=headers)
|
| 92 |
+
if response.status_code == 429: # Límite alcanzado
|
| 93 |
+
print("Límite de peticiones alcanzado, cambiando API Key...")
|
| 94 |
+
token = cambiar_api_key()
|
| 95 |
+
time.sleep(1) # Pausa de 1 segundo para evitar el límite de tasa
|
| 96 |
+
response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
|
| 97 |
+
if response.status_code == 200:
|
| 98 |
+
tracks = response.json().get('items')
|
| 99 |
+
for item in tracks:
|
| 100 |
+
track = item.get('track')
|
| 101 |
+
if track:
|
| 102 |
+
audio_features = obtener_caracteristicas_audio(token, track['id'])
|
| 103 |
+
canciones.append({
|
| 104 |
+
'playlist_name': playlist_name,
|
| 105 |
+
'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
|
| 106 |
+
'titulo': track['name'],
|
| 107 |
+
'isrc': track['external_ids'].get('isrc', 'No disponible'),
|
| 108 |
+
'popularity': track.get('popularity', 'No disponible'),
|
| 109 |
+
'valence': audio_features.get('valence', 'No disponible'),
|
| 110 |
+
'danceability': audio_features.get('danceability', 'No disponible'),
|
| 111 |
+
'energy': audio_features.get('energy', 'No disponible'),
|
| 112 |
+
'tempo': audio_features.get('tempo', 'No disponible'),
|
| 113 |
+
'speechiness': audio_features.get('speechiness', 'No disponible'),
|
| 114 |
+
'instrumentalness': audio_features.get('instrumentalness', 'No disponible'),
|
| 115 |
+
'duration': track.get('duration_ms', 'No disponible'),
|
| 116 |
+
'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
|
| 117 |
+
'record_label': obtener_record_label_spotify(track['album']['id'], token)
|
| 118 |
+
})
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"Error al obtener canciones de la playlist: {e}")
|
| 121 |
+
|
| 122 |
+
return canciones
|
| 123 |
+
|
| 124 |
+
def obtener_caracteristicas_audio(token, track_id):
|
| 125 |
+
url = f'https://api.spotify.com/v1/audio-features/{track_id}'
|
| 126 |
+
headers = {'Authorization': f'Bearer {token}'}
|
| 127 |
+
response = requests.get(url, headers=headers)
|
| 128 |
+
if response.status_code == 429: # Límite alcanzado
|
| 129 |
+
print("Límite de peticiones alcanzado al obtener características de audio, cambiando API Key...")
|
| 130 |
+
token = cambiar_api_key()
|
| 131 |
+
time.sleep(1) # Pausa de 1 segundo para evitar el límite de tasa
|
| 132 |
+
response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
|
| 133 |
+
return response.json() if response.status_code == 200 else {}
|
| 134 |
+
|
| 135 |
+
def obtener_record_label_spotify(album_id, token):
|
| 136 |
+
url = f'https://api.spotify.com/v1/albums/{album_id}'
|
| 137 |
+
headers = {'Authorization': f'Bearer {token}'}
|
| 138 |
+
response = requests.get(url, headers=headers)
|
| 139 |
+
if response.status_code == 429: # Límite alcanzado
|
| 140 |
+
print("Límite de peticiones alcanzado al obtener la discográfica, cambiando API Key...")
|
| 141 |
+
token = cambiar_api_key()
|
| 142 |
+
time.sleep(1) # Pausa de 1 segundo para evitar el límite de tasa
|
| 143 |
+
response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
|
| 144 |
+
album_info = response.json() if response.status_code == 200 else {}
|
| 145 |
+
return album_info.get('label', 'No disponible')
|
| 146 |
+
|
| 147 |
+
def interface(project_name, query, num_spotify_playlists=50):
|
| 148 |
+
# Obtener tokens y claves
|
| 149 |
+
token_spotify = obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
|
| 150 |
+
if not token_spotify:
|
| 151 |
+
return pd.DataFrame(), "Error obteniendo el token de Spotify. Intenta de nuevo."
|
| 152 |
+
|
| 153 |
+
playlists_spotify = buscar_playlists_spotify(token_spotify, query, num_spotify_playlists)
|
| 154 |
+
canciones_spotify = []
|
| 155 |
+
for playlist in playlists_spotify:
|
| 156 |
+
songs = obtener_canciones_playlist_spotify(token_spotify, playlist['playlist_id'], playlist['playlist_name'])
|
| 157 |
+
canciones_spotify.extend(songs)
|
| 158 |
+
time.sleep(1) # Pausa de 1 segundo entre la obtención de canciones para evitar el límite de tasa
|
| 159 |
+
|
| 160 |
+
# Crear DataFrame
|
| 161 |
+
df = pd.DataFrame(canciones_spotify)
|
| 162 |
+
df.rename(columns={'isrc': 'ISRCs'}, inplace=True)
|
| 163 |
+
|
| 164 |
+
# Ordenar por popularidad
|
| 165 |
+
df.sort_values(by=['popularity'], ascending=False, inplace=True)
|
| 166 |
+
|
| 167 |
+
# Guardar DataFrame en un archivo Excel
|
| 168 |
+
tmpfile = NamedTemporaryFile(delete=False, suffix='.xlsx')
|
| 169 |
+
df.to_excel(tmpfile.name, index=False)
|
| 170 |
+
|
| 171 |
+
# Renombrar el archivo con el nombre del proyecto
|
| 172 |
+
project_file_name = f"{project_name}.xlsx"
|
| 173 |
+
shutil.move(tmpfile.name, project_file_name)
|
| 174 |
+
|
| 175 |
+
return df, project_file_name # Devuelve el DataFrame y el enlace al archivo Excel
|
| 176 |
+
|
| 177 |
+
# Configuración de Gradio
|
| 178 |
+
iface = gr.Interface(
|
| 179 |
+
fn=interface,
|
| 180 |
+
inputs=[
|
| 181 |
+
gr.Textbox(label="Nombre del Proyecto"),
|
| 182 |
+
gr.Textbox(label="Keywords - Palabras Clave para tu búsqueda"),
|
| 183 |
+
gr.Number(label="Numero de Playlists que vamos a buscar con estas Keywords", value=50, minimum=1, maximum=1000)
|
| 184 |
+
],
|
| 185 |
+
outputs=[gr.Dataframe(), gr.File(label="Download Excel")],
|
| 186 |
+
title="Spotify Playlist Fetcher",
|
| 187 |
+
description="Introduce una consulta de búsqueda para obtener playlists y sus canciones de Spotify. Las credenciales del cliente están preconfiguradas."
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
iface.launch()
|