chenemii commited on
Commit
0a3ecfc
·
1 Parent(s): dd3f6cd
Files changed (2) hide show
  1. app/models/llm_analyzer.py +59 -56
  2. app/streamlit_app.py +18 -93
app/models/llm_analyzer.py CHANGED
@@ -523,60 +523,70 @@ Use these professional standards as your 100% reference for scoring. These repre
523
 
524
  ## ANALYSIS INSTRUCTIONS
525
 
526
- Using the professional benchmarks and amateur examples above as your calibration reference, provide your analysis in the following EXACT structured format:
527
 
528
  **PERFORMANCE_CLASSIFICATION:** [XX%] (where XX is a percentage from 10% to 100%)
529
 
530
  **STRENGTHS:**
531
- • [Specific strength with direct comparison to professional/amateur benchmarks - e.g. "Hip rotation of 45° approaches professional range (60-90°) and exceeds most amateur examples (23-90°)"]
532
- • [Another strength with benchmark comparison - e.g. "Energy transfer efficiency of 88% meets professional standards (88-96%) and surpasses amateur range (56.8-96.7%)"]
533
- • [Third strength with specific metric comparison to benchmarks]
534
 
535
  **WEAKNESSES:**
536
- • [Specific weakness with gap from professional standard - e.g. "Wrist hinge of 35° falls significantly below professional range (95-120°) and amateur compensation patterns (116.6°)"]
537
- • [Another weakness with professional/amateur comparison - e.g. "Head movement of 12 inches exceeds both professional (2-8in) and amateur examples (3-8in)"]
538
- • [Third weakness with benchmark gap analysis]
539
 
540
  **PRIORITY_IMPROVEMENTS:**
541
- 1. [Most Critical] Topic Name - Current metric vs professional benchmark vs amateur examples, specific target improvement to reach next level
542
- 2. [Important] Topic Name - Current performance vs benchmarks, actionable steps to improve toward professional standards
543
- 3. [Focus Area] Topic Name - Current state vs benchmark ranges, realistic improvement goals based on amateur progression examples
544
 
545
  **MANDATORY REQUIREMENTS FOR EACH SECTION:**
546
 
547
  **For STRENGTHS** - Must include:
548
- - Specific metric values from current analysis
549
- - Direct comparison to professional benchmarks (60-90° hip rotation, 95-120° wrist hinge, 88-96% energy transfer, etc.)
550
- - Comparison to amateur examples where relevant
551
- - Recognition when metrics meet or exceed professional standards
552
- - Acknowledgment when metrics surpass typical amateur performance
 
 
553
 
554
  **For WEAKNESSES** - Must include:
555
- - Specific metric gaps from professional standards
556
- - Comparison to amateur examples to show relative standing
557
- - Quantified differences (e.g., "15° below professional minimum," "20% gap from professional range")
558
- - Impact on overall performance potential
 
 
 
559
 
560
  **For PRIORITY_IMPROVEMENTS** - Must include:
561
- - Current metric value vs professional benchmark range
562
- - Reference to amateur examples showing improvement potential
563
- - Specific target values based on professional standards
564
- - Realistic progression steps based on amateur improvement patterns
565
- - Clear explanation of why this improvement would impact overall performance
 
 
566
 
567
  **EXAMPLE ANALYSIS STRUCTURE:**
568
 
569
  **STRENGTHS:**
570
- Shoulder rotation of 118° nearly matches professional standard (120°) and exceeds many amateur examples (60-120° range)
571
- Weight shift of 85% falls within professional range (70-88%) and surpasses amateur struggles (50-90% range)
 
572
 
573
  **WEAKNESSES:**
574
- Hip rotation of 28° falls significantly below professional minimum (60°) and amateur body-dominant examples (90°)
575
- Energy transfer of 62% below professional range (88-96%) and some amateur achievements (96.7%)
 
576
 
577
  **PRIORITY_IMPROVEMENTS:**
578
- 1. [Most Critical] Hip Mobility Development - Current 28° vs professional 60-90° and amateur body-dominant 90°. Target 45° as next milestone toward professional range.
579
- 2. [Important] Kinematic Sequence Optimization - Current 70% vs professional 100% and amateur range 66.8-100%. Improve to 85% through better hip-shoulder coordination.
 
580
 
581
  PERFORMANCE CLASSIFICATION SCALE:
582
  - **90-100%**: Professional/Tour level - Consistently meets or exceeds professional benchmarks across all metrics
@@ -611,26 +621,27 @@ IMPORTANT ANALYSIS PRIORITIES (Based on Real Professional Data):
611
  4. **DE-EMPHASIZE - Timing Variables**: Frame counts, tempo ratios, and duration metrics vary significantly based on video capture rates and personal style preferences
612
 
613
  **SCORING CALIBRATION GUIDELINES:**
614
- - **Hip/Shoulder Rotation Analysis**: Compare to professional minimums (60° hip, 120° shoulder) and amateur ranges
615
- - **Energy Transfer <70%**: Score below 60%, compare to amateur range (56.8-96.7%)
616
- - **Sequential Kinematic <80%**: Score below 70%, reference amateur examples (66.8-100%)
617
- - **Power Accumulation <90%**: Score below 80%, compare to amateur achievements (82.1-100%)
618
- - **Head Movement >10 inches**: Major limitation, compare to professional (2-8in) and amateur (3-8in) ranges
619
- - **Weight Shift <60%**: Significant weakness, reference amateur struggles (50%) vs successes (90%)
620
 
621
  IMPORTANT FORMATTING RULES:
622
  - Use the exact headers shown above (PERFORMANCE_CLASSIFICATION, STRENGTHS, WEAKNESSES, PRIORITY_IMPROVEMENTS)
623
  - For performance classification, use format: [XX%] where XX is the percentage (10-100)
624
  - For strengths and weaknesses, use bullet points (•)
625
  - For priority improvements, use numbered format (1., 2., 3.) with priority level in brackets
626
- - Each priority improvement must have: [Priority Level] Topic Name - Full description with benchmark comparisons
627
- - **MANDATORY**: Include specific metric values and benchmark comparisons in every strength, weakness, and improvement
628
- - **MANDATORY**: Reference professional standards and amateur examples in analysis content
629
- - Provide complete sentences with quantified comparisons - no generic statements
630
  - Focus analysis on biomechanical consistency rather than timing variations
631
- - **CRITICAL**: Every analysis point must tie back to the professional benchmarks and amateur examples provided
 
632
 
633
- Remember: Use the professional benchmarks (Atthaya Thitikul: 63.4° hip, 120° shoulder, 96.1% energy transfer, etc.) and amateur examples (23-90° hip rotation range, 56.8-96.7% energy transfer range, etc.) as the foundation for ALL analysis content, not just the percentage classification. Every strength, weakness, and improvement recommendation must include specific metric comparisons to these established benchmarks.
634
  """
635
 
636
  return prompt
@@ -984,32 +995,24 @@ def display_formatted_analysis(analysis_data):
984
  if not desc or len(desc) < 10:
985
  # Provide a more complete description based on the area
986
  if 'posture' in area.lower():
987
- desc = "Work on maintaining proper spine angle and athletic stance throughout the swing for better consistency and power transfer."
988
  elif 'tempo' in area.lower() or 'timing' in area.lower():
989
  desc = "Focus on developing a smooth, consistent rhythm that allows for proper sequencing of body movements."
990
  elif 'rotation' in area.lower():
991
- desc = "Improve the coordination and range of motion in your body turn to generate more power and accuracy."
992
  elif 'weight' in area.lower() or 'shift' in area.lower():
993
  desc = "Practice transferring weight from back foot to front foot during the swing for better balance and power."
994
  elif 'knee' in area.lower():
995
  desc = "Work on maintaining proper knee flex and stability throughout the swing for better foundation and consistency."
996
  elif 'hip' in area.lower():
997
- desc = "Focus on improving hip mobility and thrust timing to enhance power generation and sequencing."
998
  elif 'chest' in area.lower():
999
- desc = "Improve chest rotation efficiency to better coordinate upper body movement with the swing sequence."
1000
  else:
1001
  desc = description # Use the full description if we can't categorize it
1002
 
1003
- # Display using Streamlit's native components
1004
- if rank == 1:
1005
- st.error(f"**{rank}. MOST CRITICAL: {area}**")
1006
- st.write(desc)
1007
- elif rank == 2:
1008
- st.warning(f"**{rank}. IMPORTANT: {area}**")
1009
- st.write(desc)
1010
- else:
1011
- st.info(f"**{rank}. FOCUS AREA: {area}**")
1012
- st.write(desc)
1013
 
1014
  st.write("") # Add spacing between items
1015
 
 
523
 
524
  ## ANALYSIS INSTRUCTIONS
525
 
526
+ Using the professional benchmarks above as your calibration reference, provide your analysis in the following EXACT structured format:
527
 
528
  **PERFORMANCE_CLASSIFICATION:** [XX%] (where XX is a percentage from 10% to 100%)
529
 
530
  **STRENGTHS:**
531
+ • [Specific strength with direct comparison to professional benchmarks - e.g. "Your shoulder rotation shows great upper body mobility during your backswing, similar to what we see in professional swings"]
532
+ • [Another strength with benchmark comparison - e.g. "Your arm extension at impact is really strong, demonstrating excellent fundamentals"]
533
+ • [Third strength with specific metric comparison to benchmarks - e.g. "Your weight transfer demonstrates solid fundamentals in shifting from back foot to front foot through impact"]
534
 
535
  **WEAKNESSES:**
536
+ • [Specific area describing impact without numbers - e.g. "Your hip rotation is less than optimal, which may be limiting your power generation and overall swing efficiency"]
537
+ • [Another area with impact description - e.g. "Your head movement during the swing is more than ideal, which could be affecting your accuracy and consistency"]
538
+ • [Third area with impact-focused description - e.g. "Your wrist action could use some work, which may be affecting your ability to generate lag and create powerful impact"]
539
 
540
  **PRIORITY_IMPROVEMENTS:**
541
+ 1. Topic Name - Explain what to focus on and when in swing, with encouraging tone and clear benefit explanation
542
+ 2. Topic Name - What to work on with supportive guidance and positive reinforcement about potential improvements
543
+ 3. Topic Name - Area to focus on with gentle direction and realistic goals
544
 
545
  **MANDATORY REQUIREMENTS FOR EACH SECTION:**
546
 
547
  **For STRENGTHS** - Must include:
548
+ - EXACTLY 3 bullet points - no more, no less
549
+ - Use encouraging, positive language
550
+ - NO numbers or statistics - focus on qualitative descriptions
551
+ - Reference professional standards without mentioning specific metrics
552
+ - Recognition when mechanics are working well
553
+ - Explain timing in swing when relevant (during backswing, at impact, etc.)
554
+ - Use supportive tone appropriate for young golfers
555
 
556
  **For WEAKNESSES** - Must include:
557
+ - EXACTLY 3 bullet points - no more, no less
558
+ - NO numbers, degrees, or specific measurements
559
+ - Focus on the IMPACT of the issue (what it's affecting) rather than the measurement
560
+ - Use phrases like "less than optimal" or "more than ideal" instead of specific amounts
561
+ - Explain HOW the weakness affects performance (power, accuracy, consistency, etc.)
562
+ - DO NOT provide improvement suggestions - save those for the Priority Improvements section
563
+ - Frame as areas that may be affecting performance rather than deficiencies
564
 
565
  **For PRIORITY_IMPROVEMENTS** - Must include:
566
+ - EXACTLY 3 numbered items - no more, no less
567
+ - NO header formatting like [Most Critical], [Important], [Focus Area] in the descriptions
568
+ - Use encouraging language like "try increasing" or "focus on" instead of "you need to"
569
+ - When in the swing this should happen (during downswing, backswing, at impact, etc.)
570
+ - Reference professional standards gently without excessive numerical comparisons
571
+ - Clear explanation of benefits and positive outcomes
572
+ - Maintain supportive, coaching tone throughout
573
 
574
  **EXAMPLE ANALYSIS STRUCTURE:**
575
 
576
  **STRENGTHS:**
577
+ Your shoulder rotation shows great upper body mobility during your backswing, matching what we see in professional swings
578
+ Your weight transfer demonstrates excellent fundamentals in shifting from your back foot to your front foot through impact
579
+ • Your posture maintains good stability throughout most of your swing, showing solid foundational mechanics
580
 
581
  **WEAKNESSES:**
582
+ Your hip rotation is less than optimal, which may be limiting your power generation and overall swing efficiency
583
+ Your head movement during the swing is more than ideal, which could be affecting your accuracy and consistency throughout your shots
584
+ • Your wrist action could use some work, which may be affecting your ability to generate lag and create powerful impact
585
 
586
  **PRIORITY_IMPROVEMENTS:**
587
+ 1. Hip Mobility Development - Try increasing your hip rotation during the downswing. This will help you engage your lower body more effectively and unlock substantial power gains in your swing.
588
+ 2. Head Stability Enhancement - Focus on keeping your head more stable throughout your swing. This improvement will help enhance your accuracy and consistency on every shot.
589
+ 3. Wrist Hinge Optimization - Work on creating more wrist angle during your backswing to improve lag and power transfer. This will help add distance and control to your shots.
590
 
591
  PERFORMANCE CLASSIFICATION SCALE:
592
  - **90-100%**: Professional/Tour level - Consistently meets or exceeds professional benchmarks across all metrics
 
621
  4. **DE-EMPHASIZE - Timing Variables**: Frame counts, tempo ratios, and duration metrics vary significantly based on video capture rates and personal style preferences
622
 
623
  **SCORING CALIBRATION GUIDELINES:**
624
+ - **Hip/Shoulder Rotation Analysis**: Compare to professional minimums (60° hip, 120° shoulder)
625
+ - **Energy Transfer <70%**: Score below 60%, reference professional range (88-96%)
626
+ - **Sequential Kinematic <80%**: Score below 70%, reference professional standards (100%)
627
+ - **Power Accumulation <90%**: Score below 80%, compare to professional benchmarks (100%)
628
+ - **Head Movement >10 inches**: Major limitation, compare to professional standards (2-8in)
629
+ - **Weight Shift <60%**: Significant weakness, reference professional range (70-88%)
630
 
631
  IMPORTANT FORMATTING RULES:
632
  - Use the exact headers shown above (PERFORMANCE_CLASSIFICATION, STRENGTHS, WEAKNESSES, PRIORITY_IMPROVEMENTS)
633
  - For performance classification, use format: [XX%] where XX is the percentage (10-100)
634
  - For strengths and weaknesses, use bullet points (•)
635
  - For priority improvements, use numbered format (1., 2., 3.) with priority level in brackets
636
+ - Each priority improvement must have: [Priority Level] Topic Name - Full description with professional benchmark comparisons
637
+ - **MANDATORY**: Include specific metric values and professional benchmark comparisons in every strength, weakness, and improvement
638
+ - **MANDATORY**: Reference professional standards in analysis content
639
+ - Provide clear directional guidance (more/less rotation, when in swing) rather than overly technical numerical comparisons
640
  - Focus analysis on biomechanical consistency rather than timing variations
641
+ - **CRITICAL**: Every analysis point must tie back to the professional benchmarks provided
642
+ - Avoid absolute language like "perfect" or "flawless" - use terms like "very good" or "meets standards"
643
 
644
+ Remember: Use the professional benchmarks (Atthaya Thitikul: 63.4° hip, 120° shoulder, 96.1% energy transfer, etc.) as the foundation for ALL analysis content, not just the percentage classification. Every strength, weakness, and improvement recommendation must include specific comparisons to professional standards with clear, actionable guidance on what needs to improve and when in the swing.
645
  """
646
 
647
  return prompt
 
995
  if not desc or len(desc) < 10:
996
  # Provide a more complete description based on the area
997
  if 'posture' in area.lower():
998
+ desc = "Try working on maintaining proper spine angle and athletic stance throughout the swing for better consistency and power transfer."
999
  elif 'tempo' in area.lower() or 'timing' in area.lower():
1000
  desc = "Focus on developing a smooth, consistent rhythm that allows for proper sequencing of body movements."
1001
  elif 'rotation' in area.lower():
1002
+ desc = "Try improving the coordination and range of motion in your body turn to generate more power and accuracy."
1003
  elif 'weight' in area.lower() or 'shift' in area.lower():
1004
  desc = "Practice transferring weight from back foot to front foot during the swing for better balance and power."
1005
  elif 'knee' in area.lower():
1006
  desc = "Work on maintaining proper knee flex and stability throughout the swing for better foundation and consistency."
1007
  elif 'hip' in area.lower():
1008
+ desc = "Focus on improving hip mobility and rotation during the downswing to enhance power generation and sequencing."
1009
  elif 'chest' in area.lower():
1010
+ desc = "Try improving chest rotation efficiency to better coordinate upper body movement with the swing sequence."
1011
  else:
1012
  desc = description # Use the full description if we can't categorize it
1013
 
1014
+ # Display using simple bullet points instead of colored boxes
1015
+ st.markdown(f"**{rank}. {area}:** {desc}")
 
 
 
 
 
 
 
 
1016
 
1017
  st.write("") # Add spacing between items
1018
 
app/streamlit_app.py CHANGED
@@ -31,7 +31,7 @@ from app.utils.comparison import create_key_frame_comparison, extract_key_swing_
31
  st.set_page_config(page_title="Par-ity Project: Golf Swing Analysis 🏌️‍♀️",
32
  page_icon="🏌️‍♀️",
33
  layout="wide",
34
- initial_sidebar_state="expanded")
35
 
36
 
37
  # Define functions
@@ -106,8 +106,6 @@ def main():
106
  'trajectory_data': None,
107
  'sample_rate': None
108
  }
109
- if 'pro_reference_path' not in st.session_state:
110
- st.session_state.pro_reference_path = None
111
 
112
  # Add session cleanup - clean up old files when starting a new session
113
  if 'session_initialized' not in st.session_state:
@@ -116,99 +114,26 @@ def main():
116
  st.info(f"🗑️ Cleaned up {cleanup_result['files_removed']} old files ({cleanup_result['space_freed_mb']} MB freed)")
117
  st.session_state.session_initialized = True
118
 
119
- # Sidebar for configuration
120
- st.sidebar.title("Configuration")
 
 
 
121
 
122
- # Add Reset Session button
123
- st.sidebar.markdown("---")
124
- if st.sidebar.button("🗑️ Reset Session & Clean Files", help="Clear all session data and remove downloaded files"):
125
- # Clean up downloads directory
126
- cleanup_result = cleanup_downloads_directory(keep_annotated=False) # Remove all files including annotated
127
-
128
- # Clear session state
129
- for key in list(st.session_state.keys()):
130
- del st.session_state[key]
131
-
132
- st.sidebar.success(f"Session reset! Cleaned {cleanup_result.get('files_removed', 0)} files ({cleanup_result.get('space_freed_mb', 0)} MB freed)")
133
- st.rerun()
134
-
135
- st.sidebar.markdown("---")
136
-
137
- # Check available LLM services
138
  llm_services = check_llm_services()
139
- any_service_available = llm_services['ollama'][
140
- 'available'] or llm_services['openai']['available']
141
-
142
- # Option to enable/disable GPT analysis with better explanation
143
- st.sidebar.markdown("### LLM Analysis Settings")
144
-
145
- # Show service status
146
- if llm_services['ollama']['available']:
147
- st.sidebar.success(
148
- f"✅ Ollama configured: {llm_services['ollama']['config']['model']}"
149
- )
150
-
151
- if llm_services['openai']['available']:
152
- st.sidebar.success("✅ OpenAI configured")
153
-
154
- if not any_service_available:
155
- st.sidebar.info("ℹ️ No LLM services configured")
156
-
157
- # Automatically enable if services are available, otherwise allow manual control
158
- if any_service_available:
159
- enable_gpt = st.sidebar.checkbox(
160
- "Enable LLM Analysis",
161
- value=True, # Automatically enabled when services are available
162
- help=
163
- "Uses configured LLM services (Ollama/OpenAI) for personalized analysis."
164
- )
165
- else:
166
- enable_gpt = st.sidebar.checkbox(
167
- "Enable LLM Analysis",
168
- value=False, # Disabled by default when no services
169
- help="Configure Ollama or OpenAI in secrets to enable LLM analysis."
170
- )
171
-
172
- if enable_gpt and not any_service_available:
173
- st.sidebar.warning(
174
- "⚠️ No LLM services configured. Configure Ollama or OpenAI in your .streamlit/secrets.toml file."
175
- )
176
- elif enable_gpt:
177
- if llm_services['ollama']['available'] and llm_services['openai'][
178
- 'available']:
179
- st.sidebar.info("🔄 Will try Ollama first, then OpenAI as fallback")
180
- elif llm_services['ollama']['available']:
181
- st.sidebar.info("🦙 Using Ollama for analysis")
182
- elif llm_services['openai']['available']:
183
- st.sidebar.info("🤖 Using OpenAI for analysis")
184
- else:
185
- st.sidebar.info("Using sample analysis mode (no LLM required)")
186
-
187
- # Frame processing rate for YOLO
188
- sample_rate = st.sidebar.slider(
189
- "Frame Processing Rate (YOLO)",
190
- min_value=1,
191
- max_value=10,
192
- value=1,
193
- help=
194
- "Process every Nth frame. 1 = all frames (most accurate), higher values = faster but less accurate.")
195
-
196
- # Pro reference toggle
197
- enable_pro_comparison = st.sidebar.checkbox(
198
- "Enable Pro Comparison",
199
- value=True,
200
- help="Compare your swing with a professional golfer reference"
201
- )
202
 
203
- # Pro reference URL input
204
- if enable_pro_comparison:
205
- pro_url = st.sidebar.text_input(
206
- "Pro Golfer Reference URL",
207
- value="https://www.youtube.com/shorts/geR666LWSHg",
208
- help="YouTube URL of professional golfer swing (default provided)"
209
- )
210
- else:
211
- pro_url = None
212
 
213
  # Video input options
214
  st.header("Video Input")
 
31
  st.set_page_config(page_title="Par-ity Project: Golf Swing Analysis 🏌️‍♀️",
32
  page_icon="🏌️‍♀️",
33
  layout="wide",
34
+ initial_sidebar_state="collapsed")
35
 
36
 
37
  # Define functions
 
106
  'trajectory_data': None,
107
  'sample_rate': None
108
  }
 
 
109
 
110
  # Add session cleanup - clean up old files when starting a new session
111
  if 'session_initialized' not in st.session_state:
 
114
  st.info(f"🗑️ Cleaned up {cleanup_result['files_removed']} old files ({cleanup_result['space_freed_mb']} MB freed)")
115
  st.session_state.session_initialized = True
116
 
117
+ # Automatic cleanup function
118
+ def perform_cleanup():
119
+ """Perform automatic cleanup of temporary files"""
120
+ cleanup_result = cleanup_downloads_directory(keep_annotated=False)
121
+ return cleanup_result
122
 
123
+ # Set automatic defaults (no user configuration needed)
124
+ # Check available LLM services and enable automatically if available
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  llm_services = check_llm_services()
126
+ any_service_available = llm_services['ollama']['available'] or llm_services['openai']['available']
127
+
128
+ # Automatically enable LLM analysis if services are available
129
+ enable_gpt = any_service_available
130
+
131
+ # Set default frame processing rate (1 = all frames for best accuracy)
132
+ sample_rate = 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
+ # Disable pro comparison feature entirely
135
+ enable_pro_comparison = False
136
+ pro_url = None
 
 
 
 
 
 
137
 
138
  # Video input options
139
  st.header("Video Input")