Mthrfkr commited on
Commit
82771af
verified
1 Parent(s): f8c8cb5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -369
app.py CHANGED
@@ -175,374 +175,6 @@ def interface(project_name, query, num_spotify_playlists=50):
175
 
176
  return df, project_file_name # Devuelve el DataFrame y el enlace al archivo Excel
177
 
178
- # Configuraci贸n de Gradio
179
- iface = gr.Interface(
180
- fn=interface,
181
- inputs=[
182
- gr.Textbox(label="Nombre del Proyecto"),
183
- gr.Textbox(label="Keywords - Palabras Clave para tu b煤squeda"),
184
- gr.Number
185
- import gradio as gr
186
- import requests
187
- import pandas as pd
188
- from tempfile import NamedTemporaryFile
189
- from openpyxl import Workbook
190
- import shutil
191
-
192
- # Lista de credenciales de API de Spotify
193
- client_ids = ['b4a2add66ffb4f1198b94b087b365c65', '9df51caba5d247dc921b21de35a47c44']
194
- client_secrets = ['8045eacf956a477299d2bc41752f1f73', '0e39502ec7e74fe99bb74245678d5f0d']
195
- current_api_index = 0
196
-
197
- # Funciones para Spotify
198
- def obtener_token(client_id, client_secret):
199
- print(f"Obteniendo token de Spotify con client_id {client_id}...")
200
- url = 'https://accounts.spotify.com/api/token'
201
- headers = {'Content-Type': 'application/x-www-form-urlencoded'}
202
- payload = {'grant_type': 'client_credentials'}
203
- response = requests.post(url, headers=headers, data=payload, auth=(client_id, client_secret))
204
- return response.json().get('access_token')
205
-
206
- def cambiar_api_key():
207
- global current_api_index
208
- current_api_index = (current_api_index + 1) % len(client_ids)
209
- return obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
210
-
211
- def buscar_playlists_spotify(token, query, limit=50):
212
- print("Buscando playlists en Spotify...")
213
- url = 'https://api.spotify.com/v1/search'
214
- headers = {'Authorization': f'Bearer {token}'}
215
- playlists = []
216
-
217
- try:
218
- if limit <= 50:
219
- params = {'q': query, 'type': 'playlist', 'limit': limit}
220
- response = requests.get(url, headers=headers, params=params)
221
- if response.status_code == 429: # L铆mite alcanzado
222
- token = cambiar_api_key()
223
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
224
- playlists.extend(response.json().get('playlists', {}).get('items', []))
225
- else:
226
- offset = 0
227
- while limit > 0:
228
- params = {'q': query, 'type': 'playlist', 'limit': min(50, limit), 'offset': offset}
229
- response = requests.get(url, headers=headers, params=params)
230
- if response.status_code == 429: # L铆mite alcanzado
231
- token = cambiar_api_key()
232
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
233
- playlists.extend(response.json().get('playlists', {}).get('items', []))
234
- limit -= min(50, limit)
235
- offset += 50
236
- except Exception as e:
237
- print(f"Error al buscar playlists: {e}")
238
-
239
- return [{'playlist_id': playlist['id'], 'playlist_name': playlist['name']} for playlist in playlists]
240
-
241
- def obtener_canciones_playlist_spotify(token, playlist_id, playlist_name):
242
- print(f"Obteniendo canciones de la playlist {playlist_id} ({playlist_name}) de Spotify...")
243
- url = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'
244
- headers = {'Authorization': f'Bearer {token}'}
245
- canciones = []
246
-
247
- try:
248
- response = requests.get(url, headers=headers)
249
- if response.status_code == 429: # L铆mite alcanzado
250
- token = cambiar_api_key()
251
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
252
- if response.status_code == 200:
253
- tracks = response.json().get('items')
254
- for item in tracks:
255
- track = item.get('track')
256
- if track:
257
- audio_features = obtener_caracteristicas_audio(token, track['id'])
258
- audio_analysis = obtener_analisis_audio(token, track['id'])
259
- key = obtener_clave(audio_analysis)
260
- canciones.append({
261
- 'playlist_name': playlist_name,
262
- 'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
263
- 'titulo': track['name'],
264
- 'isrc': track['external_ids'].get('isrc', 'No disponible'),
265
- 'popularity': track.get('popularity', 'No disponible'),
266
- 'valence': audio_features.get('valence', 'No disponible'),
267
- 'danceability': audio_features.get('danceability', 'No disponible'),
268
- 'energy': audio_features.get('energy', 'No disponible'),
269
- 'tempo': audio_features.get('tempo', 'No disponible'),
270
- 'speechiness': audio_features.get('speechiness', 'No disponible'),
271
- 'instrumentalness': audio_features.get('instrumentalness', 'No disponible'),
272
- 'duration': track.get('duration_ms', 'No disponible'),
273
- 'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
274
- 'loudness': audio_analysis.get('track', {}).get('loudness', 'No disponible'),
275
- 'timbre': audio_analysis.get('segments', [{}])[0].get('timbre', 'No disponible'),
276
- 'acousticness': audio_features.get('acousticness', 'No disponible'),
277
- 'liveness': audio_features.get('liveness', 'No disponible'),
278
- 'key': key,
279
- 'link': track['external_urls']['spotify'],
280
- 'record_label': obtener_record_label_spotify(track['album']['id'], token),
281
- 'source': 'Spotify'
282
- })
283
- except Exception as e:
284
- print(f"Error al obtener canciones de la playlist: {e}")
285
-
286
- return canciones
287
-
288
- def obtener_caracteristicas_audio(token, track_id):
289
- url = f'https://api.spotify.com/v1/audio-features/{track_id}'
290
- headers = {'Authorization': f'Bearer {token}'}
291
- response = requests.get(url, headers=headers)
292
- if response.status_code == 429: # L铆mite alcanzado
293
- token = cambiar_api_key()
294
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
295
- return response.json() if response.status_code == 200 else {}
296
-
297
- def obtener_analisis_audio(token, track_id):
298
- url = f'https://api.spotify.com/v1/audio-analysis/{track_id}'
299
- headers = {'Authorization': f'Bearer {token}'}
300
- response = requests.get(url, headers=headers)
301
- if response.status_code == 429: # L铆mite alcanzado
302
- token = cambiar_api_key()
303
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
304
- return response.json() if response.status_code == 200 else {}
305
-
306
- def obtener_clave(audio_analysis):
307
- key_map = {
308
- -1: 'No Key',
309
- 0: 'C',
310
- 1: 'C#/Db',
311
- 2: 'D',
312
- 3: 'D#/Eb',
313
- 4: 'E',
314
- 5: 'F',
315
- 6: 'F#/Gb',
316
- 7: 'G',
317
- 8: 'G#/Ab',
318
- 9: 'A',
319
- 10: 'A#/Bb',
320
- 11: 'B'
321
- }
322
- key = audio_analysis.get('track', {}).get('key', -1)
323
- return key_map.get(key, 'Unknown')
324
-
325
- def obtener_record_label_spotify(album_id, token):
326
- url = f'https://api.spotify.com/v1/albums/{album_id}'
327
- headers = {'Authorization': f'Bearer {token}'}
328
- response = requests.get(url, headers=headers)
329
- if response.status_code == 429: # L铆mite alcanzado
330
- token = cambiar_api_key()
331
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
332
- album_info = response.json() if response.status_code == 200 else {}
333
- return album_info.get('label', 'No disponible')
334
-
335
- # Funci贸n principal de la interfaz
336
- def interface(project_name, query, num_spotify_playlists=50):
337
- # Obtener tokens y claves
338
- token_spotify = obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
339
- playlists_spotify = buscar_playlists_spotify(token_spotify, query, num_spotify_playlists)
340
- canciones_spotify = []
341
- for playlist in playlists_spotify:
342
- songs = obtener_canciones_playlist_spotify(token_spotify, playlist['playlist_id'], playlist['playlist_name'])
343
- canciones_spotify.extend(songs)
344
-
345
- # Crear DataFrame
346
- df = pd.DataFrame(canciones_spotify)
347
- df.rename(columns={'isrc': 'ISRCs'}, inplace=True)
348
-
349
- # Ordenar por popularidad
350
- df.sort_values(by=['popularity'], ascending=False, inplace=True)
351
-
352
- # Guardar DataFrame en un archivo Excel
353
- tmpfile = NamedTemporaryFile(delete=False, suffix='.xlsx')
354
- df.to_excel(tmpfile.name, index=False)
355
-
356
- # Renombrar el archivo con el nombre del proyecto
357
- project_file_name = f"{project_name}.xlsx"
358
- shutil.move(tmpfile.name, project_file_name)
359
-
360
- return df, project_file_name # Devuelve el DataFrame y el enlace al archivo Excel
361
-
362
- # Configuraci贸n de Gradio
363
- iface = gr.Interface(
364
- fn=interface,
365
- inputs=[
366
- gr.Textbox(label="Nombre del Proyecto"),
367
- gr.Textbox(label="Keywords - Palabras Clave para tu b煤squeda"),
368
- gr.Number
369
- import gradio as gr
370
- import requests
371
- import pandas as pd
372
- from tempfile import NamedTemporaryFile
373
- from openpyxl import Workbook
374
- import shutil
375
-
376
- # Lista de credenciales de API de Spotify
377
- client_ids = ['b4a2add66ffb4f1198b94b087b365c65', '9df51caba5d247dc921b21de35a47c44']
378
- client_secrets = ['8045eacf956a477299d2bc41752f1f73', '0e39502ec7e74fe99bb74245678d5f0d']
379
- current_api_index = 0
380
-
381
- # Funciones para Spotify
382
- def obtener_token(client_id, client_secret):
383
- print(f"Obteniendo token de Spotify con client_id {client_id}...")
384
- url = 'https://accounts.spotify.com/api/token'
385
- headers = {'Content-Type': 'application/x-www-form-urlencoded'}
386
- payload = {'grant_type': 'client_credentials'}
387
- response = requests.post(url, headers=headers, data=payload, auth=(client_id, client_secret))
388
- return response.json().get('access_token')
389
-
390
- def cambiar_api_key():
391
- global current_api_index
392
- current_api_index = (current_api_index + 1) % len(client_ids)
393
- return obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
394
-
395
- def buscar_playlists_spotify(token, query, limit=50):
396
- print("Buscando playlists en Spotify...")
397
- url = 'https://api.spotify.com/v1/search'
398
- headers = {'Authorization': f'Bearer {token}'}
399
- playlists = []
400
-
401
- try:
402
- if limit <= 50:
403
- params = {'q': query, 'type': 'playlist', 'limit': limit}
404
- response = requests.get(url, headers=headers, params=params)
405
- if response.status_code == 429: # L铆mite alcanzado
406
- token = cambiar_api_key()
407
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
408
- playlists.extend(response.json().get('playlists', {}).get('items', []))
409
- else:
410
- offset = 0
411
- while limit > 0:
412
- params = {'q': query, 'type': 'playlist', 'limit': min(50, limit), 'offset': offset}
413
- response = requests.get(url, headers=headers, params=params)
414
- if response.status_code == 429: # L铆mite alcanzado
415
- token = cambiar_api_key()
416
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'}, params=params)
417
- playlists.extend(response.json().get('playlists', {}).get('items', []))
418
- limit -= min(50, limit)
419
- offset += 50
420
- except Exception as e:
421
- print(f"Error al buscar playlists: {e}")
422
-
423
- return [{'playlist_id': playlist['id'], 'playlist_name': playlist['name']} for playlist in playlists]
424
-
425
- def obtener_canciones_playlist_spotify(token, playlist_id, playlist_name):
426
- print(f"Obteniendo canciones de la playlist {playlist_id} ({playlist_name}) de Spotify...")
427
- url = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'
428
- headers = {'Authorization': f'Bearer {token}'}
429
- canciones = []
430
-
431
- try:
432
- response = requests.get(url, headers=headers)
433
- if response.status_code == 429: # L铆mite alcanzado
434
- token = cambiar_api_key()
435
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
436
- if response.status_code == 200:
437
- tracks = response.json().get('items')
438
- for item in tracks:
439
- track = item.get('track')
440
- if track:
441
- audio_features = obtener_caracteristicas_audio(token, track['id'])
442
- audio_analysis = obtener_analisis_audio(token, track['id'])
443
- key = obtener_clave(audio_analysis)
444
- canciones.append({
445
- 'playlist_name': playlist_name,
446
- 'artista': track['artists'][0]['name'] if track['artists'] else 'Desconocido',
447
- 'titulo': track['name'],
448
- 'isrc': track['external_ids'].get('isrc', 'No disponible'),
449
- 'popularity': track.get('popularity', 'No disponible'),
450
- 'valence': audio_features.get('valence', 'No disponible'),
451
- 'danceability': audio_features.get('danceability', 'No disponible'),
452
- 'energy': audio_features.get('energy', 'No disponible'),
453
- 'tempo': audio_features.get('tempo', 'No disponible'),
454
- 'speechiness': audio_features.get('speechiness', 'No disponible'),
455
- 'instrumentalness': audio_features.get('instrumentalness', 'No disponible'),
456
- 'duration': track.get('duration_ms', 'No disponible'),
457
- 'release_year': track.get('album', {}).get('release_date', 'No disponible').split('-')[0] if track.get('album', {}).get('release_date') else 'No disponible',
458
- 'loudness': audio_analysis.get('track', {}).get('loudness', 'No disponible'),
459
- 'timbre': audio_analysis.get('segments', [{}])[0].get('timbre', 'No disponible'),
460
- 'acousticness': audio_features.get('acousticness', 'No disponible'),
461
- 'liveness': audio_features.get('liveness', 'No disponible'),
462
- 'key': key,
463
- 'link': track['external_urls']['spotify'],
464
- 'record_label': obtener_record_label_spotify(track['album']['id'], token),
465
- 'source': 'Spotify'
466
- })
467
- except Exception as e:
468
- print(f"Error al obtener canciones de la playlist: {e}")
469
-
470
- return canciones
471
-
472
- def obtener_caracteristicas_audio(token, track_id):
473
- url = f'https://api.spotify.com/v1/audio-features/{track_id}'
474
- headers = {'Authorization': f'Bearer {token}'}
475
- response = requests.get(url, headers=headers)
476
- if response.status_code == 429: # L铆mite alcanzado
477
- token = cambiar_api_key()
478
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
479
- return response.json() if response.status_code == 200 else {}
480
-
481
- def obtener_analisis_audio(token, track_id):
482
- url = f'https://api.spotify.com/v1/audio-analysis/{track_id}'
483
- headers = {'Authorization': f'Bearer {token}'}
484
- response = requests.get(url, headers=headers)
485
- if response.status_code == 429: # L铆mite alcanzado
486
- token = cambiar_api_key()
487
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
488
- return response.json() if response.status_code == 200 else {}
489
-
490
- def obtener_clave(audio_analysis):
491
- key_map = {
492
- -1: 'No Key',
493
- 0: 'C',
494
- 1: 'C#/Db',
495
- 2: 'D',
496
- 3: 'D#/Eb',
497
- 4: 'E',
498
- 5: 'F',
499
- 6: 'F#/Gb',
500
- 7: 'G',
501
- 8: 'G#/Ab',
502
- 9: 'A',
503
- 10: 'A#/Bb',
504
- 11: 'B'
505
- }
506
- key = audio_analysis.get('track', {}).get('key', -1)
507
- return key_map.get(key, 'Unknown')
508
-
509
- def obtener_record_label_spotify(album_id, token):
510
- url = f'https://api.spotify.com/v1/albums/{album_id}'
511
- headers = {'Authorization': f'Bearer {token}'}
512
- response = requests.get(url, headers=headers)
513
- if response.status_code == 429: # L铆mite alcanzado
514
- token = cambiar_api_key()
515
- response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
516
- album_info = response.json() if response.status_code == 200 else {}
517
- return album_info.get('label', 'No disponible')
518
-
519
- # Funci贸n principal de la interfaz
520
- def interface(project_name, query, num_spotify_playlists=50):
521
- # Obtener tokens y claves
522
- token_spotify = obtener_token(client_ids[current_api_index], client_secrets[current_api_index])
523
- playlists_spotify = buscar_playlists_spotify(token_spotify, query, num_spotify_playlists)
524
- canciones_spotify = []
525
- for playlist in playlists_spotify:
526
- songs = obtener_canciones_playlist_spotify(token_spotify, playlist['playlist_id'], playlist['playlist_name'])
527
- canciones_spotify.extend(songs)
528
-
529
- # Crear DataFrame
530
- df = pd.DataFrame(canciones_spotify)
531
- df.rename(columns={'isrc': 'ISRCs'}, inplace=True)
532
-
533
- # Ordenar por popularidad
534
- df.sort_values(by=['popularity'], ascending=False, inplace=True)
535
-
536
- # Guardar DataFrame en un archivo Excel
537
- tmpfile = NamedTemporaryFile(delete=False, suffix='.xlsx')
538
- df.to_excel(tmpfile.name, index=False)
539
-
540
- # Renombrar el archivo con el nombre del proyecto
541
- project_file_name = f"{project_name}.xlsx"
542
- shutil.move(tmpfile.name, project_file_name)
543
-
544
- return df, project_file_name # Devuelve el DataFrame y el enlace al archivo Excel
545
-
546
  # Configuraci贸n de Gradio
547
  iface = gr.Interface(
548
  fn=interface,
@@ -555,4 +187,4 @@ iface = gr.Interface(
555
  title="Spotify Playlist Fetcher",
556
  description="Enter a search query to fetch playlists and their songs from Spotify. Client credentials are pre-configured."
557
  )
558
- iface.launch()
 
175
 
176
  return df, project_file_name # Devuelve el DataFrame y el enlace al archivo Excel
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  # Configuraci贸n de Gradio
179
  iface = gr.Interface(
180
  fn=interface,
 
187
  title="Spotify Playlist Fetcher",
188
  description="Enter a search query to fetch playlists and their songs from Spotify. Client credentials are pre-configured."
189
  )
190
+ iface.launch()