akarsh999 commited on
Commit
f7d536c
·
verified ·
1 Parent(s): 7062933

Upload 9 files

Browse files
Files changed (2) hide show
  1. app.py +34 -1
  2. athletic_performance.py +67 -3
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import os
4
- from athletic_performance import analyze_youtube_video, analyze_video_file, get_performance_insights, get_ai_sports_coaching_analysis
5
 
6
  def analyze_jump_from_youtube(youtube_url, user_height_cm, user_weight_kg, progress=gr.Progress()):
7
  """Main analysis function for Gradio interface."""
@@ -268,6 +268,18 @@ def get_ai_coaching_recommendations(youtube_url, video_file, user_height_cm, use
268
  except Exception as e:
269
  return f"❌ Unexpected error: {str(e)}", None, None
270
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  # Create Gradio interface
272
  def create_interface():
273
  with gr.Blocks(title="🏃‍♂️ Athletic Ability Analysis") as app:
@@ -353,6 +365,16 @@ def create_interface():
353
  type="password",
354
  value=default_api_key
355
  )
 
 
 
 
 
 
 
 
 
 
356
  gr.Markdown("""
357
  💡 **Get your free API key**: [Google AI Studio](https://aistudio.google.com/app/apikey)
358
 
@@ -433,6 +455,17 @@ def create_interface():
433
  outputs=[results_text, results_table, status_message]
434
  )
435
 
 
 
 
 
 
 
 
 
 
 
 
436
  # Example section
437
  gr.Examples(
438
  examples=[
 
1
  import gradio as gr
2
  import pandas as pd
3
  import os
4
+ from athletic_performance import analyze_youtube_video, analyze_video_file, get_performance_insights, get_ai_sports_coaching_analysis, test_gemini_api_connection
5
 
6
  def analyze_jump_from_youtube(youtube_url, user_height_cm, user_weight_kg, progress=gr.Progress()):
7
  """Main analysis function for Gradio interface."""
 
268
  except Exception as e:
269
  return f"❌ Unexpected error: {str(e)}", None, None
270
 
271
+ def test_api_key(api_key):
272
+ """Test the API key connection."""
273
+ if not api_key or not api_key.strip():
274
+ return "❌ Please provide an API key to test"
275
+
276
+ result = test_gemini_api_connection(api_key.strip())
277
+
278
+ if result["success"]:
279
+ return f"✅ API Key is working! Status: {result['status_code']}\n\nResponse preview: {result['response_text'][:100]}..."
280
+ else:
281
+ return f"❌ API Key test failed!\n\nStatus Code: {result['status_code']}\nError: {result['error']}\n\nResponse: {result['response_text']}"
282
+
283
  # Create Gradio interface
284
  def create_interface():
285
  with gr.Blocks(title="🏃‍♂️ Athletic Ability Analysis") as app:
 
365
  type="password",
366
  value=default_api_key
367
  )
368
+ with gr.Row():
369
+ test_api_btn = gr.Button("🧪 Test API Key", size="sm")
370
+
371
+ api_test_result = gr.Textbox(
372
+ label="API Test Result",
373
+ lines=3,
374
+ interactive=False,
375
+ visible=False
376
+ )
377
+
378
  gr.Markdown("""
379
  💡 **Get your free API key**: [Google AI Studio](https://aistudio.google.com/app/apikey)
380
 
 
455
  outputs=[results_text, results_table, status_message]
456
  )
457
 
458
+ # API key test handler
459
+ def test_and_show_result(api_key):
460
+ result = test_api_key(api_key)
461
+ return gr.update(value=result, visible=True)
462
+
463
+ test_api_btn.click(
464
+ fn=test_and_show_result,
465
+ inputs=[ai_gemini_key],
466
+ outputs=[api_test_result]
467
+ )
468
+
469
  # Example section
470
  gr.Examples(
471
  examples=[
athletic_performance.py CHANGED
@@ -469,6 +469,54 @@ def get_performance_insights(result_dict):
469
  return insights
470
 
471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  def get_ai_sports_coaching_analysis(jump_height_cm, user_height_cm, gender, peak_power_watts=None,
473
  flight_time_s=None, rfd=None, api_key=None):
474
  """Get AI-powered sports coaching analysis using Google Gemini API.
@@ -519,8 +567,8 @@ Analyze potential areas for improvement in their jumping technique. Consider pos
519
 
520
  Please format your response clearly with these two distinct sections and provide practical, evidence-based recommendations."""
521
 
522
- # Prepare the API request
523
- url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
524
 
525
  headers = {
526
  'Content-Type': 'application/json',
@@ -547,6 +595,22 @@ Please format your response clearly with these two distinct sections and provide
547
 
548
  try:
549
  response = requests.post(url, headers=headers, json=data, timeout=30)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  response.raise_for_status()
551
 
552
  result = response.json()
@@ -568,7 +632,7 @@ Please format your response clearly with these two distinct sections and provide
568
  }
569
  }
570
  else:
571
- return {"error": "No response generated from AI"}
572
 
573
  except requests.exceptions.RequestException as e:
574
  return {"error": f"API request failed: {str(e)}"}
 
469
  return insights
470
 
471
 
472
+ def test_gemini_api_connection(api_key):
473
+ """Test the Gemini API connection with a simple request."""
474
+ if not api_key:
475
+ return {"error": "No API key provided"}
476
+
477
+ url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent"
478
+
479
+ headers = {
480
+ 'Content-Type': 'application/json',
481
+ 'X-goog-api-key': api_key.strip()
482
+ }
483
+
484
+ # Simple test data
485
+ test_data = {
486
+ "contents": [
487
+ {
488
+ "parts": [
489
+ {
490
+ "text": "Say hello in exactly 5 words."
491
+ }
492
+ ]
493
+ }
494
+ ],
495
+ "generationConfig": {
496
+ "temperature": 0.1,
497
+ "maxOutputTokens": 20
498
+ }
499
+ }
500
+
501
+ try:
502
+ response = requests.post(url, headers=headers, json=test_data, timeout=10)
503
+
504
+ return {
505
+ "status_code": response.status_code,
506
+ "response_text": response.text[:500],
507
+ "success": response.status_code == 200,
508
+ "error": None if response.status_code == 200 else f"HTTP {response.status_code}"
509
+ }
510
+
511
+ except Exception as e:
512
+ return {
513
+ "status_code": None,
514
+ "response_text": str(e),
515
+ "success": False,
516
+ "error": str(e)
517
+ }
518
+
519
+
520
  def get_ai_sports_coaching_analysis(jump_height_cm, user_height_cm, gender, peak_power_watts=None,
521
  flight_time_s=None, rfd=None, api_key=None):
522
  """Get AI-powered sports coaching analysis using Google Gemini API.
 
567
 
568
  Please format your response clearly with these two distinct sections and provide practical, evidence-based recommendations."""
569
 
570
+ # Prepare the API request - try Gemini 1.5 Pro as fallback
571
+ url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent"
572
 
573
  headers = {
574
  'Content-Type': 'application/json',
 
595
 
596
  try:
597
  response = requests.post(url, headers=headers, json=data, timeout=30)
598
+
599
+ # Enhanced error handling for debugging
600
+ if response.status_code == 403:
601
+ return {
602
+ "error": f"API key authentication failed (403). Please verify:\n"
603
+ f"1. API key is correct and active\n"
604
+ f"2. Generative AI API is enabled in Google Cloud Console\n"
605
+ f"3. Billing is set up for your Google Cloud project\n"
606
+ f"4. API key has proper permissions\n"
607
+ f"Response: {response.text[:200]}..."
608
+ }
609
+ elif response.status_code == 429:
610
+ return {"error": "Rate limit exceeded. Please try again later."}
611
+ elif response.status_code == 400:
612
+ return {"error": f"Bad request (400). Response: {response.text[:200]}..."}
613
+
614
  response.raise_for_status()
615
 
616
  result = response.json()
 
632
  }
633
  }
634
  else:
635
+ return {"error": f"No response generated from AI. Response: {result}"}
636
 
637
  except requests.exceptions.RequestException as e:
638
  return {"error": f"API request failed: {str(e)}"}