Mthrfkr commited on
Commit
a790389
·
verified ·
1 Parent(s): ccf996d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -13
app.py CHANGED
@@ -1,4 +1,51 @@
1
- import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import requests
3
  import pandas as pd
4
  import time
@@ -57,15 +104,23 @@ def make_request_with_retry(url, headers, params=None, max_retries=5):
57
  return None
58
 
59
  def extract_id_from_url(url, type_keyword):
60
- """Extract Spotify ID from URL for either track or playlist."""
61
- parts = url.split("/")
62
- for i, part in enumerate(parts):
63
- if type_keyword in part and i + 1 < len(parts):
64
- potential_id = parts[i + 1].split("?")[0]
65
- if potential_id:
66
- return potential_id
 
67
 
 
 
 
 
 
 
68
  # If above fails, try to find ID in the last part of the URL
 
69
  last_part = parts[-1]
70
  if "?" in last_part:
71
  return last_part.split("?")[0]
@@ -200,7 +255,7 @@ def interface(project_name, spotify_urls, include_all_info=True):
200
  # Validate URLs
201
  valid_urls = []
202
  for url in urls_list:
203
- if "spotify.com" in url and ("track" in url or "playlist" in url):
204
  valid_urls.append(url)
205
  else:
206
  print(f"Invalid URL format, skipping: {url}")
@@ -234,6 +289,9 @@ def interface(project_name, spotify_urls, include_all_info=True):
234
  if track:
235
  track[0]['playlist_source'] = url
236
  all_tracks.extend(track)
 
 
 
237
  except Exception as e:
238
  print(f"Error processing URL {url}: {str(e)}")
239
  continue
@@ -281,8 +339,8 @@ iface = gr.Interface(
281
  inputs=[
282
  gr.Textbox(label="Project Name", placeholder="Enter a name for your export"),
283
  gr.Textbox(
284
- label="Spotify URLs (Tracks or Playlists)",
285
- placeholder="Enter one Spotify URL per line (tracks or playlists)",
286
  lines=5
287
  ),
288
  gr.Checkbox(label="Include All Track Information", value=True)
@@ -292,10 +350,11 @@ iface = gr.Interface(
292
  gr.File(label="Download Excel")
293
  ],
294
  title="Spotify Track Collector",
295
- description="Extract tracks from multiple Spotify playlists and tracks into a single Excel file.",
296
  examples=[
297
  ["Pop Collection", "https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M\nhttps://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT", True],
298
- ["Rock Collection", "https://open.spotify.com/playlist/37i9dQZF1DWXRqgorJj26U", False]
 
299
  ],
300
  allow_flagging="never"
301
  )
 
1
+ def get_album_tracks(token, album_url):
2
+ """Get all tracks from an album URL."""
3
+ album_id = extract_id_from_url(album_url, "album")
4
+ print(f"Extracted album ID: {album_id}")
5
+
6
+ headers = {'Authorization': f'Bearer {token}'}
7
+ tracks_url = f'https://api.spotify.com/v1/albums/{album_id}/tracks'
8
+
9
+ all_tracks = []
10
+ next_url = tracks_url
11
+
12
+ while next_url:
13
+ print(f"Fetching tracks from: {next_url}")
14
+ response = make_request_with_retry(next_url, headers)
15
+ if not response:
16
+ break
17
+
18
+ data = response.json()
19
+ items = data.get('items', [])
20
+
21
+ # Get album details for additional info
22
+ album_info = None
23
+ if len(all_tracks) == 0: # Only need to get album info once
24
+ album_response = make_request_with_retry(f'https://api.spotify.com/v1/albums/{album_id}', headers)
25
+ if album_response:
26
+ album_info = album_response.json()
27
+
28
+ for item in items:
29
+ if item:
30
+ # For album tracks, we need to add some missing information that's in the album
31
+ if album_info:
32
+ item['album'] = {
33
+ 'name': album_info.get('name', 'Unknown'),
34
+ 'release_date': album_info.get('release_date', 'Not available'),
35
+ 'id': album_id
36
+ }
37
+
38
+ all_tracks.append(item)
39
+
40
+ next_url = data.get('next')
41
+
42
+ print(f"Found {len(all_tracks)} tracks in album")
43
+
44
+ # Mark the source
45
+ for track in all_tracks:
46
+ track['playlist_source'] = album_url
47
+
48
+ return all_tracksimport gradio as gr
49
  import requests
50
  import pandas as pd
51
  import time
 
104
  return None
105
 
106
  def extract_id_from_url(url, type_keyword):
107
+ """Extract Spotify ID from URL for track, playlist or album."""
108
+ if type_keyword in url:
109
+ parts = url.split("/")
110
+ for i, part in enumerate(parts):
111
+ if type_keyword in part and i + 1 < len(parts):
112
+ potential_id = parts[i + 1].split("?")[0]
113
+ if potential_id:
114
+ return potential_id
115
 
116
+ # Special handling for spotify.com/intl-xx/album type URLs
117
+ if "intl-" in url and "/album/" in url:
118
+ parts = url.split("/album/")
119
+ if len(parts) > 1:
120
+ return parts[1].split("?")[0].split("/")[0]
121
+
122
  # If above fails, try to find ID in the last part of the URL
123
+ parts = url.split("/")
124
  last_part = parts[-1]
125
  if "?" in last_part:
126
  return last_part.split("?")[0]
 
255
  # Validate URLs
256
  valid_urls = []
257
  for url in urls_list:
258
+ if "spotify.com" in url and ("track" in url or "playlist" in url or "album" in url):
259
  valid_urls.append(url)
260
  else:
261
  print(f"Invalid URL format, skipping: {url}")
 
289
  if track:
290
  track[0]['playlist_source'] = url
291
  all_tracks.extend(track)
292
+ elif "album" in url:
293
+ album_tracks = get_album_tracks(token_spotify, url)
294
+ all_tracks.extend(album_tracks)
295
  except Exception as e:
296
  print(f"Error processing URL {url}: {str(e)}")
297
  continue
 
339
  inputs=[
340
  gr.Textbox(label="Project Name", placeholder="Enter a name for your export"),
341
  gr.Textbox(
342
+ label="Spotify URLs (Tracks, Albums or Playlists)",
343
+ placeholder="Enter one Spotify URL per line (tracks, albums or playlists)",
344
  lines=5
345
  ),
346
  gr.Checkbox(label="Include All Track Information", value=True)
 
350
  gr.File(label="Download Excel")
351
  ],
352
  title="Spotify Track Collector",
353
+ description="Extract tracks from multiple Spotify playlists, albums, and tracks into a single Excel file.",
354
  examples=[
355
  ["Pop Collection", "https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M\nhttps://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT", True],
356
+ ["Rock Collection", "https://open.spotify.com/playlist/37i9dQZF1DWXRqgorJj26U", False],
357
+ ["Album Tracks", "https://open.spotify.com/album/1R5BORZZxNUg8QMgbqt0nd", True]
358
  ],
359
  allow_flagging="never"
360
  )