rairo commited on
Commit
68a22ab
·
verified ·
1 Parent(s): d471b8f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +29 -33
main.py CHANGED
@@ -1272,24 +1272,25 @@ def view_quizzes():
1272
  @app.route('/api/user/performance', methods=['GET'])
1273
  def get_user_performance():
1274
  """Retrieves user's quiz performance and provides simple suggestions."""
1275
- user, error = verify_token(request.headers.get('Authorization'))
1276
- if error: return jsonify({'error': error['error']}), error['status']
1277
- if not supabase: return jsonify({'error': 'Backend service unavailable'}), 503
1278
-
1279
  try:
1280
- # --- Fetch recent quiz attempts ---
1281
- attempts_res = supabase.table('quiz_attempts')\
1282
- .select('id, quiz_id, score, submitted_at, quizzes(difficulty, notes(material_id, study_materials(type, title))))')\
1283
- .eq('user_id', user.id)\
1284
- .order('submitted_at', desc=True)\
1285
- .limit(20)\
1286
- .execute() # Join to get context
1287
-
1288
- if attempts_res.error:
1289
- raise Exception(f"Failed to fetch quiz attempts: {attempts_res.error}")
1290
-
1291
- attempts_data = attempts_res.data
1292
-
 
 
 
 
 
1293
  # --- Basic Analysis ---
1294
  average_score = 0.0
1295
  suggestions = []
@@ -1303,33 +1304,28 @@ def get_user_performance():
1303
  # Suggest reviewing specific materials from recent low scores
1304
  low_score_attempts = sorted([a for a in attempts_data if a['score'] < 60], key=lambda x: x['submitted_at'], reverse=True)
1305
  if low_score_attempts:
1306
- # Safely access nested data
1307
  quiz_info = low_score_attempts[0].get('quizzes')
1308
- if quiz_info:
1309
- notes_info = quiz_info.get('notes')
1310
- if notes_info:
1311
- material_info = notes_info.get('study_materials')
1312
- if material_info and material_info.get('title'):
1313
- suggestions.append(f"Focus on reviewing the material titled: '{material_info['title']}'.")
1314
-
1315
-
1316
  elif average_score > 85:
1317
  suggestions.append("Great job on your recent quizzes! Consider trying 'hard' difficulty quizzes or exploring new topics.")
1318
  else:
1319
- suggestions.append("You're making good progress! Keep practicing to solidify your understanding.")
1320
-
1321
- # Add more sophisticated analysis here (e.g., performance by topic/difficulty)
1322
 
1323
  return jsonify({
1324
  'success': True,
1325
  'average_score': round(average_score, 2) if attempts_data else None,
1326
- 'recent_attempts': attempts_data, # Return structured attempt data
1327
  'suggestions': suggestions
1328
  })
1329
-
1330
  except Exception as e:
1331
- logging.error(f"Unexpected error fetching performance for user {user.id}: {traceback.format_exc()}")
1332
- return jsonify({'error': f'An unexpected error occurred: {e}'}), 500
 
 
1333
 
1334
 
1335
  # === Admin Endpoints (Adapted for Supabase) ===
 
1272
  @app.route('/api/user/performance', methods=['GET'])
1273
  def get_user_performance():
1274
  """Retrieves user's quiz performance and provides simple suggestions."""
 
 
 
 
1275
  try:
1276
+ # Authentication
1277
+ user, error = verify_token(request.headers.get('Authorization'))
1278
+ if error: return jsonify({'error': error['error']}), error['status']
1279
+
1280
+ # Query with proper error handling
1281
+ attempts_res = supabase.table('quiz_attempts') \
1282
+ .select('id, quiz_id, score, submitted_at, quizzes(difficulty, notes(study_materials(title, type)))') \
1283
+ .eq('user_id', user.id) \
1284
+ .order('submitted_at', desc=True) \
1285
+ .limit(20)
1286
+
1287
+ result = attempts_res.execute()
1288
+
1289
+ if hasattr(result, 'error') and result.error:
1290
+ raise Exception(result.error.message)
1291
+
1292
+ attempts_data = result.data
1293
+
1294
  # --- Basic Analysis ---
1295
  average_score = 0.0
1296
  suggestions = []
 
1304
  # Suggest reviewing specific materials from recent low scores
1305
  low_score_attempts = sorted([a for a in attempts_data if a['score'] < 60], key=lambda x: x['submitted_at'], reverse=True)
1306
  if low_score_attempts:
 
1307
  quiz_info = low_score_attempts[0].get('quizzes')
1308
+ if quiz_info and quiz_info.get('notes') and quiz_info['notes'].get('study_materials'):
1309
+ material_info = quiz_info['notes']['study_materials']
1310
+ if material_info.get('title'):
1311
+ suggestions.append(f"Focus on reviewing the material titled: '{material_info['title']}'.")
 
 
 
 
1312
  elif average_score > 85:
1313
  suggestions.append("Great job on your recent quizzes! Consider trying 'hard' difficulty quizzes or exploring new topics.")
1314
  else:
1315
+ suggestions.append("You're making good progress! Keep practicing to solidify your understanding.")
 
 
1316
 
1317
  return jsonify({
1318
  'success': True,
1319
  'average_score': round(average_score, 2) if attempts_data else None,
1320
+ 'recent_attempts': attempts_data,
1321
  'suggestions': suggestions
1322
  })
1323
+
1324
  except Exception as e:
1325
+ print(f"Error in /api/user/performance: {str(e)}") # Debug logging
1326
+ logging.error(f"Performance endpoint error: {str(e)}")
1327
+ logging.error(traceback.format_exc())
1328
+ return jsonify({'error': str(e)}), 500
1329
 
1330
 
1331
  # === Admin Endpoints (Adapted for Supabase) ===