krishnendughosh commited on
Commit
9a905fd
·
verified ·
1 Parent(s): 9a54d17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -46
app.py CHANGED
@@ -2,7 +2,6 @@ import gradio as gr
2
  import spotipy
3
  from spotipy.oauth2 import SpotifyOAuth
4
  import toml
5
- import os
6
  from urllib.parse import urlparse, parse_qs
7
  import logging
8
 
@@ -44,7 +43,6 @@ def exchange_code_for_token(code):
44
  if not token_info:
45
  raise ValueError("Failed to retrieve token info.")
46
  return token_info['access_token']
47
- print(token_info)
48
 
49
  def search_song(query, access_token):
50
  sp = spotipy.Spotify(auth=access_token)
@@ -68,66 +66,35 @@ def get_recommendations(seed_track_ids, access_token):
68
  global nor
69
  sp = spotipy.Spotify(auth=access_token)
70
 
71
- # Log the input parameters (ensure access_token is masked)
72
- logging.debug(f"Input seed_track_ids: {seed_track_ids[:5]}") # Only log the first 5 tracks
73
- logging.debug(f"Access token: {'*' * 10}...") # Mask token for security
74
-
75
  seed_track_ids = seed_track_ids[:5]
76
 
77
  try:
78
  logging.debug(f"Fetching recommendations based on {len(seed_track_ids)} seed tracks.")
79
-
80
- # Logging the actual API call
81
- logging.debug(f"Calling Spotify API with seed_track_ids: {seed_track_ids} and limit: {nor}")
82
-
83
  recommendations = sp.recommendations(seed_tracks=seed_track_ids, limit=nor)
84
 
85
- # Log the full response to see if the data is returned as expected
86
- logging.debug(f"Recommendations data: {recommendations}")
87
-
88
- except spotipy.exceptions.SpotifyException as e:
89
- logging.error(f"SpotifyException: {e}")
90
- logging.debug("Error occurred while fetching recommendations. Returning default empty values.")
91
- return f"Error fetching recommendations: {e}", [], [], [], [] # Ensure 5 values
92
- except Exception as e:
93
- logging.error(f"Exception: {e}")
94
- logging.debug("General error occurred while fetching recommendations. Returning default empty values.")
95
- return f"Error fetching recommendations: {e}", [], [], [], [] # Ensure 5 values
96
-
97
- # If recommendations are fetched successfully, log the structure of the response
98
- try:
99
  recommended_tracks = [track for track in recommendations['tracks']]
100
  recommended_track_ids = [track['id'] for track in recommended_tracks]
101
  recommended_tracks_names = [track['name'] for track in recommended_tracks]
102
 
103
- # Log the recommended tracks
104
- logging.debug(f"Recommended track IDs: {recommended_track_ids}")
105
- logging.debug(f"Recommended track names: {recommended_tracks_names}")
106
-
107
- # Create Spotify embeds
108
  spotify_embeds = [
109
  f'<iframe src="https://open.spotify.com/embed/track/{track["id"]}" width="300" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>'
110
  for track in recommended_tracks
111
  ]
112
 
113
- logging.debug(f"Generated Spotify embeds: {spotify_embeds}")
114
-
115
  return recommended_tracks, recommended_tracks_names, spotify_embeds, recommended_track_ids, recommended_tracks
116
 
117
- except KeyError as e:
118
- logging.error(f"KeyError: Missing expected key in API response: {e}")
119
- logging.debug(f"API response structure: {recommendations}")
120
- return "Error: Missing key in API response", [], [], [], [] # Ensure 5 values
121
  except Exception as e:
122
- logging.error(f"Exception while processing recommendations data: {e}")
123
- return f"Error processing recommendations: {e}", [], [], [], [] # Ensure 5 values
124
 
125
  def create_playlist(access_token, playlist_name):
126
  sp = spotipy.Spotify(auth=access_token)
127
  try:
128
  user_id = sp.current_user()['id']
129
  playlist = sp.user_playlist_create(user=user_id, name=playlist_name, public=True)
130
- logging.info(f"Playlist '{playlist_name}' created successfully.")
131
  return playlist['id'], None
132
  except spotipy.exceptions.SpotifyException as e:
133
  logging.error(f"Failed to create playlist '{playlist_name}': {e}")
@@ -197,18 +164,16 @@ def gradio_interface():
197
  outputs=[access_token_state, login_section, app_section]
198
  )
199
 
200
- # Updated add_song function
201
  def add_song(name, track_list, access_token):
202
  track = search_song(name, access_token)
203
  if track:
204
- track_list.append(track) # Add song to track list
205
  song_list_text = "\n".join(
206
  [f'<div>{t["name"]}</div><iframe src="https://open.spotify.com/embed/track/{t["id"]}" width="300" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>' for t in track_list]
207
  )
208
- return track_list, song_list_text # Return updated track list and HTML for the list
209
  return track_list, "Song not found."
210
 
211
- # Trigger the add_song function when the Add Song button is clicked
212
  add_song_button.click(
213
  fn=add_song,
214
  inputs=[song_name, track_list_state, access_token_state],
@@ -220,16 +185,12 @@ def gradio_interface():
220
  track_ids = [t['id'] for t in track_list]
221
  recommended_tracks, recommended_track_names, spotify_embeds, _, _ = get_recommendations(track_ids, access_token)
222
  if recommended_tracks:
223
- # Store the recommended tracks in the state
224
  recommended_tracks_state.value = recommended_tracks
225
-
226
- # Generate HTML with song names above their embeds
227
  recommendations_text = "\n".join(
228
  [f'<div>{name}</div><iframe src="https://open.spotify.com/embed/track/{track_id}" width="300" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>'
229
  for name, track_id in zip(recommended_track_names, [track['id'] for track in recommended_tracks])]
230
  )
231
  return recommendations_text
232
- print(recommendations_text)
233
  return "No recommendations found."
234
  return "Please add at least one song."
235
 
 
2
  import spotipy
3
  from spotipy.oauth2 import SpotifyOAuth
4
  import toml
 
5
  from urllib.parse import urlparse, parse_qs
6
  import logging
7
 
 
43
  if not token_info:
44
  raise ValueError("Failed to retrieve token info.")
45
  return token_info['access_token']
 
46
 
47
  def search_song(query, access_token):
48
  sp = spotipy.Spotify(auth=access_token)
 
66
  global nor
67
  sp = spotipy.Spotify(auth=access_token)
68
 
 
 
 
 
69
  seed_track_ids = seed_track_ids[:5]
70
 
71
  try:
72
  logging.debug(f"Fetching recommendations based on {len(seed_track_ids)} seed tracks.")
 
 
 
 
73
  recommendations = sp.recommendations(seed_tracks=seed_track_ids, limit=nor)
74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  recommended_tracks = [track for track in recommendations['tracks']]
76
  recommended_track_ids = [track['id'] for track in recommended_tracks]
77
  recommended_tracks_names = [track['name'] for track in recommended_tracks]
78
 
 
 
 
 
 
79
  spotify_embeds = [
80
  f'<iframe src="https://open.spotify.com/embed/track/{track["id"]}" width="300" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>'
81
  for track in recommended_tracks
82
  ]
83
 
 
 
84
  return recommended_tracks, recommended_tracks_names, spotify_embeds, recommended_track_ids, recommended_tracks
85
 
86
+ except spotipy.exceptions.SpotifyException as e:
87
+ logging.error(f"SpotifyException: {e}")
88
+ return f"Error fetching recommendations: {e}", [], [], [], [] # Ensure 5 values
 
89
  except Exception as e:
90
+ logging.error(f"Exception: {e}")
91
+ return f"Error fetching recommendations: {e}", [], [], [], [] # Ensure 5 values
92
 
93
  def create_playlist(access_token, playlist_name):
94
  sp = spotipy.Spotify(auth=access_token)
95
  try:
96
  user_id = sp.current_user()['id']
97
  playlist = sp.user_playlist_create(user=user_id, name=playlist_name, public=True)
 
98
  return playlist['id'], None
99
  except spotipy.exceptions.SpotifyException as e:
100
  logging.error(f"Failed to create playlist '{playlist_name}': {e}")
 
164
  outputs=[access_token_state, login_section, app_section]
165
  )
166
 
 
167
  def add_song(name, track_list, access_token):
168
  track = search_song(name, access_token)
169
  if track:
170
+ track_list.append(track)
171
  song_list_text = "\n".join(
172
  [f'<div>{t["name"]}</div><iframe src="https://open.spotify.com/embed/track/{t["id"]}" width="300" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>' for t in track_list]
173
  )
174
+ return track_list, song_list_text
175
  return track_list, "Song not found."
176
 
 
177
  add_song_button.click(
178
  fn=add_song,
179
  inputs=[song_name, track_list_state, access_token_state],
 
185
  track_ids = [t['id'] for t in track_list]
186
  recommended_tracks, recommended_track_names, spotify_embeds, _, _ = get_recommendations(track_ids, access_token)
187
  if recommended_tracks:
 
188
  recommended_tracks_state.value = recommended_tracks
 
 
189
  recommendations_text = "\n".join(
190
  [f'<div>{name}</div><iframe src="https://open.spotify.com/embed/track/{track_id}" width="300" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>'
191
  for name, track_id in zip(recommended_track_names, [track['id'] for track in recommended_tracks])]
192
  )
193
  return recommendations_text
 
194
  return "No recommendations found."
195
  return "Please add at least one song."
196