Mthrfkr commited on
Commit
b1efe12
·
verified ·
1 Parent(s): 002474b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -12
app.py CHANGED
@@ -3,10 +3,8 @@ import requests
3
  import pandas as pd
4
  import time
5
  import shutil
6
- import numpy as np
7
  import os
8
  from tempfile import NamedTemporaryFile
9
- from openpyxl import Workbook
10
 
11
  # Spotify API credentials from environment variables
12
  client_ids = os.getenv("SPOTIFY_CLIENT_IDS")
@@ -73,7 +71,7 @@ def get_audio_features(token, track_ids):
73
 
74
  def get_tracks_and_features(token, url):
75
  headers = {'Authorization': f'Bearer {token}'}
76
- track_ids = None
77
 
78
  if "track" in url:
79
  track_id = url.split("/")[-1].split("?")[0]
@@ -83,7 +81,7 @@ def get_tracks_and_features(token, url):
83
  tracks_url = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'
84
  response = make_request_with_retry(tracks_url, headers)
85
  if response:
86
- track_ids = [item['track']['id'] for item in response.json().get('items', []) if item['track']]
87
 
88
  if not track_ids:
89
  return None, None
@@ -141,13 +139,28 @@ def get_track_information(token, track_ids):
141
 
142
  # Main Interface Function
143
  def interface(project_name, spotify_url, num_similar_songs=10):
 
 
 
 
 
 
144
  token_spotify = get_token(client_ids[current_api_index], client_secrets[current_api_index])
 
 
 
 
145
  track_ids, audio_features = get_tracks_and_features(token_spotify, spotify_url)
146
  if not track_ids or not audio_features:
147
- return "Invalid URL or no songs found.", None
 
148
 
149
  similar_tracks_info = find_similar_tracks(token_spotify, audio_features, num_similar_songs)
150
 
 
 
 
 
151
  # Create DataFrame
152
  df = pd.DataFrame(similar_tracks_info)
153
 
@@ -156,7 +169,7 @@ def interface(project_name, spotify_url, num_similar_songs=10):
156
  df.to_excel(tmpfile.name, index=False)
157
 
158
  # Rename the file with the project name
159
- project_file_name = f"{project_name}.xlsx"
160
  shutil.move(tmpfile.name, project_file_name)
161
 
162
  return df, project_file_name # Returns the DataFrame and the link to the Excel file
@@ -165,12 +178,22 @@ def interface(project_name, spotify_url, num_similar_songs=10):
165
  iface = gr.Interface(
166
  fn=interface,
167
  inputs=[
168
- gr.Textbox(label="Project Name"),
169
- gr.Textbox(label="Spotify URL (Track or Playlist)"),
170
- gr.Number(label="Number of Similar Songs", value=10, minimum=1, maximum=100)
 
 
 
 
171
  ],
172
- outputs=[gr.Dataframe(), gr.File(label="Download Excel")],
173
  title="Spotify Similar Track Finder",
174
- description="Enter a Spotify URL to find similar songs based on their features."
 
 
 
 
 
175
  )
176
- iface.launch()
 
 
 
3
  import pandas as pd
4
  import time
5
  import shutil
 
6
  import os
7
  from tempfile import NamedTemporaryFile
 
8
 
9
  # Spotify API credentials from environment variables
10
  client_ids = os.getenv("SPOTIFY_CLIENT_IDS")
 
71
 
72
  def get_tracks_and_features(token, url):
73
  headers = {'Authorization': f'Bearer {token}'}
74
+ track_ids = []
75
 
76
  if "track" in url:
77
  track_id = url.split("/")[-1].split("?")[0]
 
81
  tracks_url = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'
82
  response = make_request_with_retry(tracks_url, headers)
83
  if response:
84
+ track_ids = [item['track']['id'] for item in response.json().get('items', []) if item.get('track')]
85
 
86
  if not track_ids:
87
  return None, None
 
139
 
140
  # Main Interface Function
141
  def interface(project_name, spotify_url, num_similar_songs=10):
142
+ # Input validation
143
+ if not spotify_url or not ("spotify.com" in spotify_url and ("track" in spotify_url or "playlist" in spotify_url)):
144
+ error_message = "Invalid URL format. Please enter a valid Spotify track or playlist URL."
145
+ # Return empty DataFrame with error message and None for file
146
+ return gr.Dataframe(value=pd.DataFrame({"Error": [error_message]})), None
147
+
148
  token_spotify = get_token(client_ids[current_api_index], client_secrets[current_api_index])
149
+ if not token_spotify:
150
+ error_message = "Failed to authenticate with Spotify API. Please try again later."
151
+ return gr.Dataframe(value=pd.DataFrame({"Error": [error_message]})), None
152
+
153
  track_ids, audio_features = get_tracks_and_features(token_spotify, spotify_url)
154
  if not track_ids or not audio_features:
155
+ error_message = "No valid tracks found for the provided URL."
156
+ return gr.Dataframe(value=pd.DataFrame({"Error": [error_message]})), None
157
 
158
  similar_tracks_info = find_similar_tracks(token_spotify, audio_features, num_similar_songs)
159
 
160
+ if not similar_tracks_info:
161
+ error_message = "Could not find similar tracks. Please try with a different track or playlist."
162
+ return gr.Dataframe(value=pd.DataFrame({"Error": [error_message]})), None
163
+
164
  # Create DataFrame
165
  df = pd.DataFrame(similar_tracks_info)
166
 
 
169
  df.to_excel(tmpfile.name, index=False)
170
 
171
  # Rename the file with the project name
172
+ project_file_name = f"{project_name if project_name else 'spotify_similar_tracks'}.xlsx"
173
  shutil.move(tmpfile.name, project_file_name)
174
 
175
  return df, project_file_name # Returns the DataFrame and the link to the Excel file
 
178
  iface = gr.Interface(
179
  fn=interface,
180
  inputs=[
181
+ gr.Textbox(label="Project Name", placeholder="Enter a name for your project"),
182
+ gr.Textbox(label="Spotify URL (Track or Playlist)", placeholder="https://open.spotify.com/track/... or https://open.spotify.com/playlist/..."),
183
+ gr.Slider(label="Number of Similar Songs", minimum=1, maximum=100, value=10, step=1)
184
+ ],
185
+ outputs=[
186
+ gr.Dataframe(),
187
+ gr.File(label="Download Excel")
188
  ],
 
189
  title="Spotify Similar Track Finder",
190
+ description="Enter a Spotify URL to find similar songs based on their audio features.",
191
+ examples=[
192
+ ["Pop Hits", "https://open.spotify.com/track/1mWdTewIgB3gtBM3TOSFhB", 10],
193
+ ["Rock Classics", "https://open.spotify.com/playlist/37i9dQZF1DWXRqgorJj26U", 15]
194
+ ],
195
+ allow_flagging="never"
196
  )
197
+
198
+ if __name__ == "__main__":
199
+ iface.launch()