saemstunes commited on
Commit
38ccc97
·
verified ·
1 Parent(s): 96cdd4a

Update src/supabase_integration.py

Browse files
Files changed (1) hide show
  1. src/supabase_integration.py +55 -18
src/supabase_integration.py CHANGED
@@ -28,6 +28,9 @@ class AdvancedSupabaseIntegration:
28
  self.connection_timeout = 30
29
  self.max_retries = 3
30
  self.retry_delay = 1
 
 
 
31
  self.setup_logging()
32
 
33
  def setup_logging(self):
@@ -56,8 +59,10 @@ class AdvancedSupabaseIntegration:
56
  cache_key = f"context_{hash(query)}_{user_id}"
57
  cached = self.get_cached(cache_key)
58
  if cached:
 
59
  return cached
60
 
 
61
  try:
62
  context = {
63
  "tracks": [],
@@ -133,6 +138,7 @@ class AdvancedSupabaseIntegration:
133
 
134
  for table_name, stat_key in tables_to_check:
135
  try:
 
136
  response = requests.get(
137
  f"{self.supabase_url}/rest/v1/{table_name}",
138
  headers=self.headers,
@@ -142,13 +148,20 @@ class AdvancedSupabaseIntegration:
142
  },
143
  timeout=10
144
  )
 
 
145
 
146
  if response.status_code == 200:
147
  content_range = response.headers.get('content-range')
148
  if content_range and '/' in content_range:
149
- count = int(content_range.split('/')[-1])
150
- stats[stat_key] = count
151
- self.logger.debug(f"Retrieved {stat_key}: {count}")
 
 
 
 
 
152
 
153
  except Exception as e:
154
  self.logger.warning(f"Could not get count for {table_name}: {e}")
@@ -188,28 +201,33 @@ class AdvancedSupabaseIntegration:
188
  }
189
 
190
  try:
 
191
  response = requests.get(
192
  f"{self.supabase_url}/rest/v1/profiles?id=eq.{user_id}",
193
  headers=self.headers,
194
  timeout=10
195
  )
 
196
 
197
  if response.status_code == 200 and response.json():
198
  profile_data = response.json()[0]
199
  user_context["is_premium"] = profile_data.get("subscription_tier") in ["premium", "pro", "enterprise"]
200
  user_context["account_created"] = profile_data.get("created_at")
201
 
 
202
  response = requests.get(
203
  f"{self.supabase_url}/rest/v1/user_preferences?user_id=eq.{user_id}",
204
  headers=self.headers,
205
  timeout=10
206
  )
 
207
 
208
  if response.status_code == 200 and response.json():
209
  preferences = response.json()[0]
210
  if preferences.get("favorite_genres"):
211
  user_context["favorite_genres"] = preferences["favorite_genres"][:5]
212
 
 
213
  response = requests.get(
214
  f"{self.supabase_url}/rest/v1/user_activity?user_id=eq.{user_id}",
215
  headers=self.headers,
@@ -220,6 +238,7 @@ class AdvancedSupabaseIntegration:
220
  },
221
  timeout=10
222
  )
 
223
 
224
  if response.status_code == 200 and response.json():
225
  activities = response.json()
@@ -228,11 +247,13 @@ class AdvancedSupabaseIntegration:
228
  for act in activities
229
  ]
230
 
 
231
  response = requests.get(
232
  f"{self.supabase_url}/rest/v1/learning_progress?user_id=eq.{user_id}",
233
  headers=self.headers,
234
  timeout=10
235
  )
 
236
 
237
  if response.status_code == 200 and response.json():
238
  progress_data = response.json()[0]
@@ -251,6 +272,7 @@ class AdvancedSupabaseIntegration:
251
  def get_popular_tracks(self, limit: int = 5) -> List[Dict[str, Any]]:
252
  """Get popular tracks from tracks table"""
253
  try:
 
254
  response = requests.get(
255
  f"{self.supabase_url}/rest/v1/tracks",
256
  headers=self.headers,
@@ -261,6 +283,7 @@ class AdvancedSupabaseIntegration:
261
  },
262
  timeout=15
263
  )
 
264
 
265
  if response.status_code == 200:
266
  tracks = response.json()
@@ -288,6 +311,7 @@ class AdvancedSupabaseIntegration:
288
  def get_popular_artists(self, limit: int = 5) -> List[Dict[str, Any]]:
289
  """Get popular artists from artists table"""
290
  try:
 
291
  response = requests.get(
292
  f"{self.supabase_url}/rest/v1/artists",
293
  headers=self.headers,
@@ -298,6 +322,7 @@ class AdvancedSupabaseIntegration:
298
  },
299
  timeout=15
300
  )
 
301
 
302
  if response.status_code == 200:
303
  artists = response.json()
@@ -324,6 +349,7 @@ class AdvancedSupabaseIntegration:
324
  def get_recent_courses(self, limit: int = 5) -> List[Dict[str, Any]]:
325
  """Get recent courses from courses table"""
326
  try:
 
327
  response = requests.get(
328
  f"{self.supabase_url}/rest/v1/courses",
329
  headers=self.headers,
@@ -334,6 +360,7 @@ class AdvancedSupabaseIntegration:
334
  },
335
  timeout=15
336
  )
 
337
 
338
  if response.status_code == 200:
339
  courses = response.json()
@@ -361,6 +388,7 @@ class AdvancedSupabaseIntegration:
361
  def get_featured_artists(self, limit: int = 5) -> List[Dict[str, Any]]:
362
  """Get featured artists (verified artists)"""
363
  try:
 
364
  response = requests.get(
365
  f"{self.supabase_url}/rest/v1/artists",
366
  headers=self.headers,
@@ -372,6 +400,7 @@ class AdvancedSupabaseIntegration:
372
  },
373
  timeout=15
374
  )
 
375
 
376
  if response.status_code == 200:
377
  artists = response.json()
@@ -395,6 +424,7 @@ class AdvancedSupabaseIntegration:
395
  def get_featured_playlists(self, limit: int = 3) -> List[Dict[str, Any]]:
396
  """Get featured playlists"""
397
  try:
 
398
  response = requests.get(
399
  f"{self.supabase_url}/rest/v1/playlists",
400
  headers=self.headers,
@@ -405,6 +435,7 @@ class AdvancedSupabaseIntegration:
405
  },
406
  timeout=15
407
  )
 
408
 
409
  if response.status_code == 200:
410
  playlists = response.json()
@@ -429,6 +460,7 @@ class AdvancedSupabaseIntegration:
429
  def get_top_genres(self, limit: int = 5) -> List[Dict[str, Any]]:
430
  """Get top genres"""
431
  try:
 
432
  response = requests.get(
433
  f"{self.supabase_url}/rest/v1/genres",
434
  headers=self.headers,
@@ -439,6 +471,7 @@ class AdvancedSupabaseIntegration:
439
  },
440
  timeout=15
441
  )
 
442
 
443
  if response.status_code == 200:
444
  genres = response.json()
@@ -742,8 +775,9 @@ class AdvancedSupabaseIntegration:
742
  timeout=10
743
  )
744
  response_time = time.time() - start_time
 
745
 
746
- results["tables"][table] = {
747
  "accessible": response.status_code == 200,
748
  "status_code": response.status_code,
749
  "response_time_ms": round(response_time * 1000, 2)
@@ -752,7 +786,14 @@ class AdvancedSupabaseIntegration:
752
  if response.status_code == 200:
753
  content_range = response.headers.get('content-range')
754
  if content_range and '/' in content_range:
755
- results["tables"][table]["record_count"] = int(content_range.split('/')[-1])
 
 
 
 
 
 
 
756
 
757
  except Exception as e:
758
  results["tables"][table] = {
@@ -786,6 +827,7 @@ class AdvancedSupabaseIntegration:
786
  def get_tracks_by_popularity(self) -> List[Dict[str, Any]]:
787
  """Get tracks grouped by popularity"""
788
  try:
 
789
  response = requests.get(
790
  f"{self.supabase_url}/rest/v1/tracks",
791
  headers=self.headers,
@@ -796,6 +838,7 @@ class AdvancedSupabaseIntegration:
796
  },
797
  timeout=15
798
  )
 
799
 
800
  if response.status_code == 200:
801
  tracks = response.json()
@@ -817,6 +860,7 @@ class AdvancedSupabaseIntegration:
817
  def get_artists_by_followers(self) -> List[Dict[str, Any]]:
818
  """Get artists grouped by follower count"""
819
  try:
 
820
  response = requests.get(
821
  f"{self.supabase_url}/rest/v1/artists",
822
  headers=self.headers,
@@ -827,6 +871,7 @@ class AdvancedSupabaseIntegration:
827
  },
828
  timeout=15
829
  )
 
830
 
831
  if response.status_code == 200:
832
  artists = response.json()
@@ -848,6 +893,7 @@ class AdvancedSupabaseIntegration:
848
  def get_courses_by_rating(self) -> List[Dict[str, Any]]:
849
  """Get courses grouped by rating"""
850
  try:
 
851
  response = requests.get(
852
  f"{self.supabase_url}/rest/v1/courses",
853
  headers=self.headers,
@@ -858,6 +904,7 @@ class AdvancedSupabaseIntegration:
858
  },
859
  timeout=15
860
  )
 
861
 
862
  if response.status_code == 200:
863
  courses = response.json()
@@ -879,19 +926,9 @@ class AdvancedSupabaseIntegration:
879
 
880
  def calculate_cache_hit_rate(self) -> float:
881
  """Calculate cache hit rate"""
882
- if not hasattr(self, '_cache_access_stats'):
883
- return 0.0
884
-
885
- hits = getattr(self, '_cache_hits', 0)
886
- misses = getattr(self, '_cache_misses', 0)
887
- total = hits + misses
888
-
889
- return (hits / total) * 100 if total > 0 else 0.0
890
 
891
  def calculate_average_response_time(self) -> float:
892
  """Calculate average response time for API calls"""
893
- if not hasattr(self, '_response_times'):
894
- return 0.0
895
-
896
- times = getattr(self, '_response_times', [])
897
- return sum(times) / len(times) if times else 0.0
 
28
  self.connection_timeout = 30
29
  self.max_retries = 3
30
  self.retry_delay = 1
31
+ self._cache_hits = 0
32
+ self._cache_misses = 0
33
+ self._response_times = []
34
  self.setup_logging()
35
 
36
  def setup_logging(self):
 
59
  cache_key = f"context_{hash(query)}_{user_id}"
60
  cached = self.get_cached(cache_key)
61
  if cached:
62
+ self._cache_hits += 1
63
  return cached
64
 
65
+ self._cache_misses += 1
66
  try:
67
  context = {
68
  "tracks": [],
 
138
 
139
  for table_name, stat_key in tables_to_check:
140
  try:
141
+ start_time = time.time()
142
  response = requests.get(
143
  f"{self.supabase_url}/rest/v1/{table_name}",
144
  headers=self.headers,
 
148
  },
149
  timeout=10
150
  )
151
+ response_time = time.time() - start_time
152
+ self._response_times.append(response_time)
153
 
154
  if response.status_code == 200:
155
  content_range = response.headers.get('content-range')
156
  if content_range and '/' in content_range:
157
+ count_str = content_range.split('/')[-1]
158
+ try:
159
+ count = int(count_str)
160
+ stats[stat_key] = count
161
+ self.logger.debug(f"Retrieved {stat_key}: {count}")
162
+ except (ValueError, TypeError):
163
+ self.logger.warning(f"Unexpected count value for {table_name}: {count_str}")
164
+ continue
165
 
166
  except Exception as e:
167
  self.logger.warning(f"Could not get count for {table_name}: {e}")
 
201
  }
202
 
203
  try:
204
+ start_time = time.time()
205
  response = requests.get(
206
  f"{self.supabase_url}/rest/v1/profiles?id=eq.{user_id}",
207
  headers=self.headers,
208
  timeout=10
209
  )
210
+ self._response_times.append(time.time() - start_time)
211
 
212
  if response.status_code == 200 and response.json():
213
  profile_data = response.json()[0]
214
  user_context["is_premium"] = profile_data.get("subscription_tier") in ["premium", "pro", "enterprise"]
215
  user_context["account_created"] = profile_data.get("created_at")
216
 
217
+ start_time = time.time()
218
  response = requests.get(
219
  f"{self.supabase_url}/rest/v1/user_preferences?user_id=eq.{user_id}",
220
  headers=self.headers,
221
  timeout=10
222
  )
223
+ self._response_times.append(time.time() - start_time)
224
 
225
  if response.status_code == 200 and response.json():
226
  preferences = response.json()[0]
227
  if preferences.get("favorite_genres"):
228
  user_context["favorite_genres"] = preferences["favorite_genres"][:5]
229
 
230
+ start_time = time.time()
231
  response = requests.get(
232
  f"{self.supabase_url}/rest/v1/user_activity?user_id=eq.{user_id}",
233
  headers=self.headers,
 
238
  },
239
  timeout=10
240
  )
241
+ self._response_times.append(time.time() - start_time)
242
 
243
  if response.status_code == 200 and response.json():
244
  activities = response.json()
 
247
  for act in activities
248
  ]
249
 
250
+ start_time = time.time()
251
  response = requests.get(
252
  f"{self.supabase_url}/rest/v1/learning_progress?user_id=eq.{user_id}",
253
  headers=self.headers,
254
  timeout=10
255
  )
256
+ self._response_times.append(time.time() - start_time)
257
 
258
  if response.status_code == 200 and response.json():
259
  progress_data = response.json()[0]
 
272
  def get_popular_tracks(self, limit: int = 5) -> List[Dict[str, Any]]:
273
  """Get popular tracks from tracks table"""
274
  try:
275
+ start_time = time.time()
276
  response = requests.get(
277
  f"{self.supabase_url}/rest/v1/tracks",
278
  headers=self.headers,
 
283
  },
284
  timeout=15
285
  )
286
+ self._response_times.append(time.time() - start_time)
287
 
288
  if response.status_code == 200:
289
  tracks = response.json()
 
311
  def get_popular_artists(self, limit: int = 5) -> List[Dict[str, Any]]:
312
  """Get popular artists from artists table"""
313
  try:
314
+ start_time = time.time()
315
  response = requests.get(
316
  f"{self.supabase_url}/rest/v1/artists",
317
  headers=self.headers,
 
322
  },
323
  timeout=15
324
  )
325
+ self._response_times.append(time.time() - start_time)
326
 
327
  if response.status_code == 200:
328
  artists = response.json()
 
349
  def get_recent_courses(self, limit: int = 5) -> List[Dict[str, Any]]:
350
  """Get recent courses from courses table"""
351
  try:
352
+ start_time = time.time()
353
  response = requests.get(
354
  f"{self.supabase_url}/rest/v1/courses",
355
  headers=self.headers,
 
360
  },
361
  timeout=15
362
  )
363
+ self._response_times.append(time.time() - start_time)
364
 
365
  if response.status_code == 200:
366
  courses = response.json()
 
388
  def get_featured_artists(self, limit: int = 5) -> List[Dict[str, Any]]:
389
  """Get featured artists (verified artists)"""
390
  try:
391
+ start_time = time.time()
392
  response = requests.get(
393
  f"{self.supabase_url}/rest/v1/artists",
394
  headers=self.headers,
 
400
  },
401
  timeout=15
402
  )
403
+ self._response_times.append(time.time() - start_time)
404
 
405
  if response.status_code == 200:
406
  artists = response.json()
 
424
  def get_featured_playlists(self, limit: int = 3) -> List[Dict[str, Any]]:
425
  """Get featured playlists"""
426
  try:
427
+ start_time = time.time()
428
  response = requests.get(
429
  f"{self.supabase_url}/rest/v1/playlists",
430
  headers=self.headers,
 
435
  },
436
  timeout=15
437
  )
438
+ self._response_times.append(time.time() - start_time)
439
 
440
  if response.status_code == 200:
441
  playlists = response.json()
 
460
  def get_top_genres(self, limit: int = 5) -> List[Dict[str, Any]]:
461
  """Get top genres"""
462
  try:
463
+ start_time = time.time()
464
  response = requests.get(
465
  f"{self.supabase_url}/rest/v1/genres",
466
  headers=self.headers,
 
471
  },
472
  timeout=15
473
  )
474
+ self._response_times.append(time.time() - start_time)
475
 
476
  if response.status_code == 200:
477
  genres = response.json()
 
775
  timeout=10
776
  )
777
  response_time = time.time() - start_time
778
+ self._response_times.append(response_time)
779
 
780
+ table_result = {
781
  "accessible": response.status_code == 200,
782
  "status_code": response.status_code,
783
  "response_time_ms": round(response_time * 1000, 2)
 
786
  if response.status_code == 200:
787
  content_range = response.headers.get('content-range')
788
  if content_range and '/' in content_range:
789
+ count_str = content_range.split('/')[-1]
790
+ try:
791
+ table_result["record_count"] = int(count_str)
792
+ except (ValueError, TypeError):
793
+ self.logger.warning(f"Unexpected count value in test_connection for {table}: {count_str}")
794
+ table_result["record_count"] = 0
795
+
796
+ results["tables"][table] = table_result
797
 
798
  except Exception as e:
799
  results["tables"][table] = {
 
827
  def get_tracks_by_popularity(self) -> List[Dict[str, Any]]:
828
  """Get tracks grouped by popularity"""
829
  try:
830
+ start_time = time.time()
831
  response = requests.get(
832
  f"{self.supabase_url}/rest/v1/tracks",
833
  headers=self.headers,
 
838
  },
839
  timeout=15
840
  )
841
+ self._response_times.append(time.time() - start_time)
842
 
843
  if response.status_code == 200:
844
  tracks = response.json()
 
860
  def get_artists_by_followers(self) -> List[Dict[str, Any]]:
861
  """Get artists grouped by follower count"""
862
  try:
863
+ start_time = time.time()
864
  response = requests.get(
865
  f"{self.supabase_url}/rest/v1/artists",
866
  headers=self.headers,
 
871
  },
872
  timeout=15
873
  )
874
+ self._response_times.append(time.time() - start_time)
875
 
876
  if response.status_code == 200:
877
  artists = response.json()
 
893
  def get_courses_by_rating(self) -> List[Dict[str, Any]]:
894
  """Get courses grouped by rating"""
895
  try:
896
+ start_time = time.time()
897
  response = requests.get(
898
  f"{self.supabase_url}/rest/v1/courses",
899
  headers=self.headers,
 
904
  },
905
  timeout=15
906
  )
907
+ self._response_times.append(time.time() - start_time)
908
 
909
  if response.status_code == 200:
910
  courses = response.json()
 
926
 
927
  def calculate_cache_hit_rate(self) -> float:
928
  """Calculate cache hit rate"""
929
+ total = self._cache_hits + self._cache_misses
930
+ return (self._cache_hits / total) * 100 if total > 0 else 0.0
 
 
 
 
 
 
931
 
932
  def calculate_average_response_time(self) -> float:
933
  """Calculate average response time for API calls"""
934
+ return sum(self._response_times) / len(self._response_times) if self._response_times else 0.0