Mthrfkr commited on
Commit
80dc031
verified
1 Parent(s): 729bed3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -0
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import pandas as pd
4
+ from tempfile import NamedTemporaryFile
5
+ from openpyxl import Workbook
6
+
7
+ # Lista de credenciales de API de Spotify
8
+ client_ids = ['b4a2add66ffb4f1198b94b087b365c65', '9df51caba5d247dc921b21de35a47c44']
9
+ client_secrets = ['8045eacf956a477299d2bc41752f1f73', '0e39502ec7e74fe99bb74245678d5f0d]
10
+ current_api_index = 0
11
+
12
+ # Funciones para Spotify
13
+ def obtener_token(client_id, client_secret):
14
+ print(f"Obteniendo token de Spotify con client_id {client_id}...")
15
+ url = 'https://accounts.spotify.com/api/token'
16
+ headers = {'Content-Type': 'application/x-www-form-urlencoded'}
17
+ payload = {'grant_type': 'client_credentials'}
18
+ response = requests.post(url, headers=headers, data=payload, auth=(client_id, client_secret))
19
+ return response.json().get('access_token')
20
+
21
+ def cambiar_api_key():
22
+ global current_api_index
23
+ current_api_index = (current_api_index + 1) % len(client_ids)
24
+ return obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
25
+
26
+ def buscar_playlists_spotify(token, query, limit=50):
27
+ print("Buscando playlists en Spotify...")
28
+ url = 'https://api.spotify.com/v1/search'
29
+ headers = {'Authorization': f'Bearer {token}'}
30
+ playlists = []
31
+
32
+ try:
33
+ if limit <= 50:
34
+ params = {'q': query, 'type': 'playlist', 'limit': limit}
35
+ response = requests.get(url, headers=headers, params=params)
36
+ if response.status_code == 429: # L铆mite alcanzado
37
+ token = cambiar_api_key()
38
+ response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
39
+ playlists.extend(response.json().get('playlists', {}).get('items', []))
40
+ else:
41
+ offset = 0
42
+ while limit > 0:
43
+ params = {'q': query, 'type': 'playlist', 'limit': min(50, limit), 'offset': offset}
44
+ response = requests.get(url, headers=headers, params=params)
45
+ if response.status_code == 429: # L铆mite alcanzado
46
+ token = cambiar_api_key()
47
+ response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
48
+ playlists.extend(response.json().get('playlists', {}).get('items', []))
49
+ limit -= min(50, limit)
50
+ offset += 50
51
+ except Exception as e:
52
+ print(f"Error al buscar playlists: {e}")
53
+
54
+ return [{'playlist_id': playlist['id'], 'playlist_name': playlist['name']} for playlist in playlists]
55
+
56
+ def obtener_canciones_playlist_spotify(token, playlist_id):
57
+ print(f"Obteniendo canciones de la playlist {playlist_id} de Spotify...")
58
+ url = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'
59
+ headers = {'Authorization': f'Bearer {token}'}
60
+ canciones = []
61
+
62
+ try:
63
+ response = requests.get(url, headers=headers)
64
+ if response.status_code == 429: # L铆mite alcanzado
65
+ token = cambiar_api_key()
66
+ response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
67
+ if response.status_code == 200:
68
+ tracks = response.json().get('items')
69
+ for item in tracks:
70
+ track = item.get('track')
71
+ if track:
72
+ audio_features = obtener_caracteristicas_audio(token, track['id'])
73
+ canciones.append({
74
+ 'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
75
+ 'titulo': track['name'],
76
+ 'isrc': track['external_ids'].get('isrc', 'No disponible'),
77
+ 'popularity': track.get('popularity', 'No disponible'),
78
+ 'valence': audio_features.get('valence', 'No disponible'),
79
+ 'danceability': audio_features.get('danceability', 'No disponible'),
80
+ 'energy': audio_features.get('energy', 'No disponible'),
81
+ 'tempo': audio_features.get('tempo', 'No disponible'),
82
+ 'speechiness': audio_features.get('speechiness', 'No disponible'),
83
+ 'instrumentalness': audio_features.get('instrumentalness', 'No disponible'),
84
+ 'link': track['external_urls']['spotify'],
85
+ 'record_label': obtener_record_label_spotify(track['album']['id'], token),
86
+ 'source': 'Spotify'
87
+ })
88
+ except Exception as e:
89
+ print(f"Error al obtener canciones de la playlist: {e}")
90
+
91
+ return canciones
92
+
93
+ def obtener_caracteristicas_audio(token, track_id):
94
+ url = f'https://api.spotify.com/v1/audio-features/{track_id}'
95
+ headers = {'Authorization': f'Bearer {token}'}
96
+ response = requests.get(url, headers=headers)
97
+ if response.status_code == 429: # L铆mite alcanzado
98
+ token = cambiar_api_key()
99
+ response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
100
+ return response.json() if response.status_code == 200 else {}
101
+
102
+ def obtener_record_label_spotify(album_id, token):
103
+ url = f'https://api.spotify.com/v1/albums/{album_id}'
104
+ headers = {'Authorization': f'Bearer {token}'}
105
+ response = requests.get(url, headers=headers)
106
+ if response.status_code == 429: # L铆mite alcanzado
107
+ token = cambiar_api_key()
108
+ response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
109
+ album_info = response.json() if response.status_code == 200 else {}
110
+ return album_info.get('label', 'No disponible')
111
+
112
+ # Funci贸n principal de la interfaz
113
+ def interface(query, num_spotify_playlists=50):
114
+ # Obtener tokens y claves
115
+ token_spotify = obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
116
+ playlists_spotify = buscar_playlists_spotify(token_spotify, query, num_spotify_playlists)
117
+ canciones_spotify = []
118
+ for playlist in playlists_spotify:
119
+ songs = obtener_canciones_playlist_spotify(token_spotify, playlist['playlist_id'])
120
+ canciones_spotify.extend(songs)
121
+
122
+ # Crear DataFrame
123
+ df = pd.DataFrame(canciones_spotify)
124
+ df.rename(columns={'isrc': 'ISRCs'}, inplace=True)
125
+
126
+ # Ordenar por popularidad
127
+ df.sort_values(by=['popularity'], ascending=False, inplace=True)
128
+
129
+ with NamedTemporaryFile(delete=False, suffix='.xlsx') as tmpfile:
130
+ df.to_excel(tmpfile.name, index=False)
131
+ return df, tmpfile.name # Devuelve el DataFrame y el enlace al archivo Excel
132
+
133
+ # Configuraci贸n de Gradio
134
+ iface = gr.Interface(
135
+ fn=interface,
136
+ inputs=[
137
+ gr.Textbox(label="Search Query"),
138
+ gr.Number(label="Number of Spotify Playlists", value=50, minimum=1, maximum=1000)
139
+ ],
140
+ outputs=[gr.Dataframe(), gr.File(label="Download Excel")],
141
+ title="Spotify Playlist Fetcher",
142
+ description="Enter a search query to fetch playlists and their songs from Spotify. Client credentials are pre-configured."
143
+ )
144
+ iface.launch()