Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,5 @@
|
|
| 1 |
import requests
|
| 2 |
import time
|
| 3 |
-
import gradio as gr
|
| 4 |
-
import pandas as pd
|
| 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 = [
|
|
@@ -20,6 +15,7 @@ client_secrets = [
|
|
| 20 |
'9fdfa58ea0a94ce7a0cb34fa19fb7d74'
|
| 21 |
]
|
| 22 |
current_api_index = 0
|
|
|
|
| 23 |
|
| 24 |
def obtener_token(client_id, client_secret):
|
| 25 |
print(f"Obteniendo token de Spotify con client_id: {client_id}")
|
|
@@ -34,137 +30,48 @@ def obtener_token(client_id, client_secret):
|
|
| 34 |
print(f"Error al obtener token para client_id: {client_id}, status_code: {response.status_code}, response: {response.text}")
|
| 35 |
return None
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def cambiar_api_key():
|
| 38 |
global current_api_index
|
| 39 |
current_api_index = (current_api_index + 1) % len(client_ids)
|
| 40 |
print(f"Cambiando a la siguiente API Key, 铆ndice actual: {current_api_index}")
|
| 41 |
-
|
| 42 |
-
return obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
return cambiar_api_key()
|
| 50 |
return token
|
| 51 |
|
| 52 |
-
def
|
| 53 |
-
|
| 54 |
-
url = 'https://api.spotify.com/v1/search'
|
| 55 |
headers = {'Authorization': f'Bearer {token}'}
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
token = manejar_limite_de_tasa(response, token)
|
| 63 |
-
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 64 |
-
else:
|
| 65 |
-
offset = 0
|
| 66 |
-
while limit > 0:
|
| 67 |
-
params = {'q': query, 'type': 'playlist', 'limit': min(40, limit), 'offset': offset}
|
| 68 |
-
response = requests.get(url, headers=headers, params=params)
|
| 69 |
-
token = manejar_limite_de_tasa(response, token)
|
| 70 |
-
playlists.extend(response.json().get('playlists', {}).get('items', []))
|
| 71 |
-
limit -= min(40, limit)
|
| 72 |
-
offset += 40
|
| 73 |
-
time.sleep(3) # Pausa de 3 segundos entre las solicitudes para evitar el l铆mite de tasa
|
| 74 |
-
except Exception as e:
|
| 75 |
-
print(f"Error al buscar playlists: {e}")
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
tracks = response.json().get('items')
|
| 90 |
-
for item in tracks:
|
| 91 |
-
track = item.get('track')
|
| 92 |
-
if track:
|
| 93 |
-
audio_features = obtener_caracteristicas_audio(token, track['id'])
|
| 94 |
-
canciones.append({
|
| 95 |
-
'playlist_name': playlist_name,
|
| 96 |
-
'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
|
| 97 |
-
'titulo': track['name'],
|
| 98 |
-
'isrc': track['external_ids'].get('isrc', 'No disponible'),
|
| 99 |
-
'popularity': track.get('popularity', 'No disponible'),
|
| 100 |
-
'valence': audio_features.get('valence', 'No disponible'),
|
| 101 |
-
'danceability': audio_features.get('danceability', 'No disponible'),
|
| 102 |
-
'energy': audio_features.get('energy', 'No disponible'),
|
| 103 |
-
'tempo': audio_features.get('tempo', 'No disponible'),
|
| 104 |
-
'speechiness': audio_features.get('speechiness', 'No disponible'),
|
| 105 |
-
'instrumentalness': audio_features.get('instrumentalness', 'No disponible'),
|
| 106 |
-
'duration': track.get('duration_ms', 'No disponible'),
|
| 107 |
-
'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
|
| 108 |
-
'record_label': obtener_record_label_spotify(track['album']['id'], token)
|
| 109 |
-
})
|
| 110 |
-
except Exception as e:
|
| 111 |
-
print(f"Error al obtener canciones de la playlist: {e}")
|
| 112 |
-
|
| 113 |
-
return canciones
|
| 114 |
-
|
| 115 |
-
def obtener_caracteristicas_audio(token, track_id):
|
| 116 |
-
url = f'https://api.spotify.com/v1/audio-features/{track_id}'
|
| 117 |
-
headers = {'Authorization': f'Bearer {token}'}
|
| 118 |
-
response = requests.get(url, headers=headers)
|
| 119 |
-
token = manejar_limite_de_tasa(response, token)
|
| 120 |
-
return response.json() if response.status_code == 200 else {}
|
| 121 |
-
|
| 122 |
-
def obtener_record_label_spotify(album_id, token):
|
| 123 |
-
url = f'https://api.spotify.com/v1/albums/{album_id}'
|
| 124 |
-
headers = {'Authorization': f'Bearer {token}'}
|
| 125 |
-
response = requests.get(url, headers=headers)
|
| 126 |
-
token = manejar_limite_de_tasa(response, token)
|
| 127 |
-
album_info = response.json() if response.status_code == 200 else {}
|
| 128 |
-
return album_info.get('label', 'No disponible')
|
| 129 |
-
|
| 130 |
-
# Funci贸n principal de la interfaz
|
| 131 |
-
def interface(project_name, query, num_spotify_playlists=40):
|
| 132 |
-
# Obtener tokens y claves
|
| 133 |
-
token_spotify = obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
|
| 134 |
-
playlists_spotify = buscar_playlists_spotify(token_spotify, query, num_spotify_playlists)
|
| 135 |
-
canciones_spotify = []
|
| 136 |
-
for playlist in playlists_spotify:
|
| 137 |
-
songs = obtener_canciones_playlist_spotify(token_spotify, playlist['playlist_id'], playlist['playlist_name'])
|
| 138 |
-
canciones_spotify.extend(songs)
|
| 139 |
-
time.sleep(3) # Pausa de 3 segundos entre la obtenci贸n de canciones para evitar el l铆mite de tasa
|
| 140 |
-
|
| 141 |
-
# Crear DataFrame
|
| 142 |
-
df = pd.DataFrame(canciones_spotify)
|
| 143 |
-
df.rename(columns={'isrc': 'ISRCs'}, inplace=True)
|
| 144 |
-
|
| 145 |
-
# Ordenar por popularidad
|
| 146 |
-
df.sort_values(by=['popularity'], ascending=False, inplace=True)
|
| 147 |
-
|
| 148 |
-
# Guardar DataFrame en un archivo Excel
|
| 149 |
-
tmpfile = NamedTemporaryFile(delete=False, suffix='.xlsx')
|
| 150 |
-
df.to_excel(tmpfile.name, index=False)
|
| 151 |
-
|
| 152 |
-
# Renombrar el archivo con el nombre del proyecto
|
| 153 |
-
project_file_name = f"{project_name}.xlsx"
|
| 154 |
-
shutil.move(tmpfile.name, project_file_name)
|
| 155 |
-
|
| 156 |
-
return df, project_file_name # Devuelve el DataFrame y el enlace al archivo Excel
|
| 157 |
-
|
| 158 |
-
# Configuraci贸n de Gradio
|
| 159 |
-
iface = gr.Interface(
|
| 160 |
-
fn=interface,
|
| 161 |
-
inputs=[
|
| 162 |
-
gr.Textbox(label="Nombre del Proyecto"),
|
| 163 |
-
gr.Textbox(label="Keywords - Palabras Clave para tu b煤squeda"),
|
| 164 |
-
gr.Number(label="Numero de Playlists que vamos a buscar con estas Keywords", value=40, minimum=1, maximum=1000)
|
| 165 |
-
],
|
| 166 |
-
outputs=[gr.Dataframe(), gr.File(label="Download Excel")],
|
| 167 |
-
title="Spotify Playlist Fetcher",
|
| 168 |
-
description="Enter a search query to fetch playlists and their songs from Spotify. Client credentials are pre-configured."
|
| 169 |
-
)
|
| 170 |
-
iface.launch()
|
|
|
|
| 1 |
import requests
|
| 2 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
# Lista de credenciales de API de Spotify
|
| 5 |
client_ids = [
|
|
|
|
| 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 |
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 realizar_solicitud_con_nuevo_token(url, params):
|
| 55 |
+
token = obtener_nuevo_token()
|
|
|
|
| 56 |
headers = {'Authorization': f'Bearer {token}'}
|
| 57 |
+
response = session.get(url, headers=headers, params=params)
|
| 58 |
+
print(f"Solicitud realizada con nuevo token. C贸digo de estado: {response.status_code}")
|
| 59 |
+
return response
|
| 60 |
|
| 61 |
+
# Ejemplo de uso
|
| 62 |
+
def main():
|
| 63 |
+
url = 'https://api.spotify.com/v1/search'
|
| 64 |
+
params = {'q': 'rancheras', 'type': 'playlist', 'limit': 40}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
print("Realizando primera solicitud...")
|
| 67 |
+
response = realizar_solicitud_con_nuevo_token(url, params)
|
| 68 |
+
print("Respuesta de la primera solicitud:", response.json())
|
| 69 |
+
|
| 70 |
+
# Simular cambio de API key despu茅s de recibir un c贸digo 429
|
| 71 |
+
if response.status_code == 429:
|
| 72 |
+
print("L铆mite de peticiones alcanzado, cambiando API key y realizando una nueva solicitud...")
|
| 73 |
+
response = realizar_solicitud_con_nuevo_token(url, params)
|
| 74 |
+
print("Respuesta de la segunda solicitud:", response.json())
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|