Clonkz commited on
Commit
03e8fb3
·
1 Parent(s): 99eab84

Updated app.py to include logs to debug errors

Browse files
Files changed (1) hide show
  1. app.py +28 -3
app.py CHANGED
@@ -8,8 +8,19 @@ from rapidfuzz import process, fuzz
8
  import spotipy
9
  from spotipy.oauth2 import SpotifyClientCredentials
10
  import os
 
 
11
 
12
 
 
 
 
 
 
 
 
 
 
13
  # Spotify API setup
14
  sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
15
  client_id=os.environ['sp_client_id'],
@@ -21,16 +32,22 @@ features = ['popularity', 'danceability', 'energy', 'loudness', 'speechiness',
21
  default_weights = [1/len(features)] * len(features)
22
 
23
  # Read and preprocess the data
24
- tracks_data = pd.read_csv('filtered_songs.csv')
 
25
  tracks_data = tracks_data[(tracks_data['popularity'] > 40) & (tracks_data['instrumentalness'] <= 0.85)]
 
 
 
26
 
27
  # Function to fetch a song from Spotify
28
  def get_song_from_spotify(song_name, artist_name=None):
29
  try:
30
  search_query = song_name if not artist_name else f"{song_name} artist:{artist_name}"
 
31
  results = sp.search(q=search_query, limit=1, type='track')
32
  if results['tracks']['items']:
33
  track = results['tracks']['items'][0]
 
34
  audio_features = sp.audio_features(track['id'])[0]
35
  song_details = {
36
  'id': track['id'],
@@ -54,13 +71,16 @@ def get_song_from_spotify(song_name, artist_name=None):
54
  }
55
  return song_details
56
  else:
 
57
  return None
58
  except Exception as e:
59
- print(f"Error fetching song from Spotify: {e}")
60
  return None
61
 
62
  # Enhanced Fuzzy Matching Function
63
  def enhanced_fuzzy_matching(song_name, artist_name, df):
 
 
64
  combined_query = f"{song_name} {artist_name}".strip()
65
  df['combined'] = df['name'] + ' ' + df['artists']
66
  matches = process.extractOne(combined_query, df['combined'], scorer=fuzz.token_sort_ratio)
@@ -68,6 +88,7 @@ def enhanced_fuzzy_matching(song_name, artist_name, df):
68
 
69
  # Function to apply the selected scaler and calculate weighted cosine similarity
70
  def calculate_weighted_cosine_similarity(input_song_index, weights, num_songs_to_output, tracks_data, scaler_choice):
 
71
  # Apply the selected scaler
72
  if scaler_choice == 'Standard Scaler':
73
  scaler = StandardScaler()
@@ -97,7 +118,8 @@ def recommend_songs_interface(song_name, artist_name, num_songs_to_output, scale
97
  return pd.DataFrame(columns=['name', 'artists'])
98
 
99
  # Gradio interface setup
100
- description = "Enter a song name and artist name to get song recommendations. Adjust the feature weights using the sliders. The system will automatically normalize the weights. Please note that this database can only recommend songs that have been released up until the year 2020. You can adjust the scaler and tweak the sliders to get the right song for you based on the metrics of your choice"
 
101
 
102
  inputs = [
103
  gr.components.Textbox(label="Song Name", placeholder="Enter a song name..."),
@@ -121,4 +143,7 @@ iface = gr.Interface(
121
 
122
  # Run the Gradio app
123
  if __name__ == "__main__":
 
 
124
  iface.launch()
 
 
8
  import spotipy
9
  from spotipy.oauth2 import SpotifyClientCredentials
10
  import os
11
+ import logging
12
+ import psutil
13
 
14
 
15
+ # Configure logging
16
+ logging.basicConfig(level=logging.INFO)
17
+ logging.info("Application started")
18
+
19
+ def log_memory_usage():
20
+ process = psutil.Process()
21
+ memory_info = process.memory_info()
22
+ logging.info(f"Memory Usage: {memory_info.rss / 1024 ** 2:.2f} MB")
23
+
24
  # Spotify API setup
25
  sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
26
  client_id=os.environ['sp_client_id'],
 
32
  default_weights = [1/len(features)] * len(features)
33
 
34
  # Read and preprocess the data
35
+ logging.info("Reading and preprocessing track data")
36
+ tracks_data = pd.read_csv('iltered_songs.csv')
37
  tracks_data = tracks_data[(tracks_data['popularity'] > 40) & (tracks_data['instrumentalness'] <= 0.85)]
38
+ logging.info("Track data loaded and processed")
39
+ log_memory_usage()
40
+
41
 
42
  # Function to fetch a song from Spotify
43
  def get_song_from_spotify(song_name, artist_name=None):
44
  try:
45
  search_query = song_name if not artist_name else f"{song_name} artist:{artist_name}"
46
+ logging.info(f"Searching Spotify for: {search_query}")
47
  results = sp.search(q=search_query, limit=1, type='track')
48
  if results['tracks']['items']:
49
  track = results['tracks']['items'][0]
50
+ logging.info(f"Found track on Spotify: {track['name']} by {', '.join(artist['name'] for artist in track['artists'])}")
51
  audio_features = sp.audio_features(track['id'])[0]
52
  song_details = {
53
  'id': track['id'],
 
71
  }
72
  return song_details
73
  else:
74
+ logging.warning(f"No results found on Spotify for: {search_query}")
75
  return None
76
  except Exception as e:
77
+ logging.error(f"Error fetching song from Spotify: {e}")
78
  return None
79
 
80
  # Enhanced Fuzzy Matching Function
81
  def enhanced_fuzzy_matching(song_name, artist_name, df):
82
+ logging.info(f"Performing fuzzy matching for: {song_name}, {artist_name}")
83
+ # Existing code
84
  combined_query = f"{song_name} {artist_name}".strip()
85
  df['combined'] = df['name'] + ' ' + df['artists']
86
  matches = process.extractOne(combined_query, df['combined'], scorer=fuzz.token_sort_ratio)
 
88
 
89
  # Function to apply the selected scaler and calculate weighted cosine similarity
90
  def calculate_weighted_cosine_similarity(input_song_index, weights, num_songs_to_output, tracks_data, scaler_choice):
91
+ logging.info("Calculating weighted cosine similarity")
92
  # Apply the selected scaler
93
  if scaler_choice == 'Standard Scaler':
94
  scaler = StandardScaler()
 
118
  return pd.DataFrame(columns=['name', 'artists'])
119
 
120
  # Gradio interface setup
121
+ logging.info("Setting up Gradio interface")
122
+ description = "Enter a song name and artist name (optional) to get song recommendations. Adjust the feature weights using the sliders. The system will automatically normalize the weights."
123
 
124
  inputs = [
125
  gr.components.Textbox(label="Song Name", placeholder="Enter a song name..."),
 
143
 
144
  # Run the Gradio app
145
  if __name__ == "__main__":
146
+ logging.info("Setting up Gradio interface")
147
+ logging.info("Launching Gradio interface")
148
  iface.launch()
149
+ logging.info("Application finished")