File size: 11,659 Bytes
e931856 79d4ccf e931856 63362a9 993887f 63362a9 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f e931856 11f9ed5 63362a9 e931856 63362a9 2564de6 63362a9 ce18d83 d1b08e4 993887f 63362a9 d1b08e4 63362a9 d1b08e4 63362a9 993887f 11f9ed5 63362a9 e931856 63362a9 ce18d83 63362a9 0eaa53f d1b08e4 1f29c2f 63362a9 e931856 993887f 63362a9 e931856 993887f 63362a9 e931856 63362a9 79d4ccf 993887f e931856 63362a9 e931856 63362a9 993887f e931856 63362a9 e931856 63362a9 08b8729 63362a9 08b8729 63362a9 e931856 63362a9 e931856 63362a9 e931856 993887f e931856 63362a9 11f9ed5 79d4ccf 993887f 63362a9 993887f e931856 63362a9 993887f 63362a9 11f9ed5 993887f 11f9ed5 63362a9 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 63362a9 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 63362a9 11f9ed5 993887f 11f9ed5 63362a9 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 993887f 11f9ed5 e931856 63362a9 e931856 11f9ed5 993887f e931856 11f9ed5 e931856 993887f e931856 993887f 11f9ed5 993887f 11f9ed5 e931856 993887f e931856 11f9ed5 79d4ccf e931856 993887f e931856 993887f e931856 993887f e931856 993887f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | """
AI Fitness Coach - Hugging Face Spaces Demo
Fine-tuned persona-based feedback system
"""
import gradio as gr
import torch
import json
import numpy as np
from pathlib import Path
from typing import Tuple
from transformers import AutoTokenizer, AutoModelForCausalLM
# ------------------------------------------------------------------
# Mock Scoring Function (used when full backend unavailable)
# ------------------------------------------------------------------
def mock_score_exercise(user_video_path, reference_id="pushup", use_dtw=True):
"""
Mock scoring function that returns realistic demo results.
Used when the full pose estimation backend is not available.
"""
# Generate slightly randomized but realistic scores
base_score = 72 + np.random.randint(-5, 15)
return {
"overall_score": float(base_score),
"relevant_score": float(base_score + np.random.randint(-3, 5)),
"body_part_scores": {
"core": float(base_score + np.random.randint(-8, 10)),
"right_arm": float(base_score + np.random.randint(-10, 8)),
"left_arm": float(base_score + np.random.randint(-10, 8)),
"torso": float(base_score + np.random.randint(-5, 12))
},
"relevant_body_part_scores": {
"core": float(base_score + np.random.randint(-8, 10)),
"right_arm": float(base_score + np.random.randint(-10, 8)),
"left_arm": float(base_score + np.random.randint(-10, 8)),
"torso": float(base_score + np.random.randint(-5, 12))
},
"feedback": generate_mock_feedback(base_score),
"exercise_type": "pushup",
"num_frames_user": 100,
"num_frames_ref": 325,
"alignment_quality": float(80 + np.random.randint(-10, 15))
}
def generate_mock_feedback(score):
"""Generate appropriate feedback based on score."""
feedback = []
if score >= 85:
feedback.append("Excellent form! Your push-up technique is very close to ideal.")
feedback.append("Maintain this consistency in your workouts.")
elif score >= 70:
feedback.append("Good form overall. Minor adjustments can improve your technique.")
feedback.append("Focus on keeping your core engaged throughout the movement.")
elif score >= 55:
feedback.append("Decent effort, but there's room for improvement.")
feedback.append("Try to maintain a straighter back during the movement.")
feedback.append("Your arm positioning could be more consistent.")
else:
feedback.append("Keep practicing! Focus on the basics of proper form.")
feedback.append("Watch the reference video and pay attention to body alignment.")
feedback.append("Consider starting with modified push-ups to build strength.")
return feedback
# Use mock scoring (full backend requires dependencies not available on Spaces)
score_exercise = mock_score_exercise
print("βΉοΈ Using demonstration scoring mode.")
# ------------------------------------------------------------------
# Model Loading Logic
# ------------------------------------------------------------------
MODEL_CONFIG = {
"Hype Beast π₯": "rlogh/fitness-coach-persona-hype-beast",
"Data Scientist π": "rlogh/fitness-coach-persona-data-scientist",
"No-Nonsense Pro πͺ": "rlogh/fitness-coach-persona-no-nonsense-pro",
"Mindful Aligner π§": "rlogh/fitness-coach-persona-mindful-aligner",
}
PERSONAS = list(MODEL_CONFIG.keys())
MODELS_CACHE = {}
def load_all_models():
"""Loads all fine-tuned models into the cache on startup."""
global MODELS_CACHE
BASE_MODEL_NAME = "distilgpt2"
print(f"π Loading base tokenizer from {BASE_MODEL_NAME}...")
try:
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME, use_fast=True)
MODELS_CACHE['tokenizer'] = tokenizer
print("β
Base tokenizer loaded successfully.")
except Exception as e:
print(f"β Critical Error loading tokenizer: {e}")
return
for persona_name, repo_id in MODEL_CONFIG.items():
print(f"π Loading {persona_name} model from {repo_id}...")
try:
model = AutoModelForCausalLM.from_pretrained(
repo_id,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None,
low_cpu_mem_usage=True,
trust_remote_code=True
)
MODELS_CACHE[persona_name] = model
print(f"β
{persona_name} loaded successfully.")
except Exception as e:
print(f"β Failed to load {persona_name}: {e}")
MODELS_CACHE[persona_name] = None
# Load all models on startup
load_all_models()
# ------------------------------------------------------------------
# Feedback Generation
# ------------------------------------------------------------------
def generate_feedback(persona_name: str, input_report: str) -> str:
"""Generates feedback using the selected persona model."""
model = MODELS_CACHE.get(persona_name)
tokenizer = MODELS_CACHE.get('tokenizer')
if model is None or tokenizer is None:
return f"β οΈ The '{persona_name}' coach is currently unavailable. Please try another coach."
prompt = f"<|persona|>{persona_name}<|input|>{input_report}<|output|>"
try:
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
device = next(model.parameters()).device
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=300,
temperature=0.9,
top_p=0.92,
do_sample=True,
repetition_penalty=1.2,
pad_token_id=tokenizer.eos_token_id
)
full_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
if "<|output|>" in full_text:
return full_text.split("<|output|>")[-1].strip()
return full_text
except Exception as e:
return f"Coach feedback error: {str(e)}"
# ------------------------------------------------------------------
# Main Analysis Function
# ------------------------------------------------------------------
def analyze_video(video_file, persona_choice: str) -> Tuple[str, str, str]:
"""Analyze video and return technical report, coach feedback, and JSON results."""
if video_file is None:
return "β οΈ Please upload a video first.", "", "{}"
if MODELS_CACHE.get(persona_choice) is None:
return f"β οΈ The '{persona_choice}' coach failed to load. Try another coach.", "", "{}"
try:
# Score the exercise
results = score_exercise(
user_video_path=video_file,
reference_id="pushup",
use_dtw=True
)
# Extract scores
score = results.get('overall_score', 0)
relevant_score = results.get('relevant_score', score)
body_scores = results.get('relevant_body_part_scores', results.get('body_part_scores', {}))
scoring_feedback = results.get('feedback', [])
# Clamp scores to valid range
score = max(0, min(100, score))
relevant_score = max(0, min(100, relevant_score))
body_scores = {k: max(0, min(100, v)) for k, v in body_scores.items()}
# Build body part scores string
body_parts_str = "\n".join([
f" β’ {part.replace('_', ' ').title()}: {s:.1f}/100"
for part, s in body_scores.items()
])
# Build feedback string
feedback_str = "\n".join([f" β’ {fb}" for fb in scoring_feedback]) if scoring_feedback else " β’ Good effort!"
# Determine rating
if score >= 85:
rating = "π Excellent!"
elif score >= 70:
rating = "π Good"
elif score >= 55:
rating = "πͺ Keep Practicing"
else:
rating = "π Review Form"
# Format technical report
report = f"""π PUSH-UP ANALYSIS
ββββββββββββββββββββββββ
Overall Score: {score:.1f}/100
Rating: {rating}
Body Part Breakdown:
{body_parts_str}
Observations:
{feedback_str}
"""
# Generate personalized coach feedback
coach_feedback = generate_feedback(persona_choice, report)
# Clean JSON output
clean_results = {
"overall_score": round(score, 1),
"relevant_score": round(relevant_score, 1),
"body_part_scores": {k: round(v, 1) for k, v in body_scores.items()},
"exercise_type": "pushup",
"feedback": scoring_feedback
}
return report, coach_feedback, json.dumps(clean_results, indent=2)
except Exception as e:
error_msg = f"Analysis error: {str(e)}"
print(f"β {error_msg}")
return error_msg, "", "{}"
# ------------------------------------------------------------------
# Gradio UI
# ------------------------------------------------------------------
with gr.Blocks(title="AI Fitness Coach", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# ποΈ AI Fitness Coach
Upload a video of your **push-up** and get personalized feedback from our AI coaches!
> **Note:** This is a demonstration using simulated scoring. The AI coach feedback is generated by fine-tuned language models.
""")
with gr.Row():
with gr.Column(scale=1):
video_input = gr.Video(label="πΉ Upload Your Push-up Video")
persona_select = gr.Radio(
choices=PERSONAS,
value=PERSONAS[0],
label="π Choose Your Coach"
)
gr.Markdown("""
**Coach Styles:**
- π₯ **Hype Beast**: High energy motivation
- π **Data Scientist**: Technical analysis
- πͺ **No-Nonsense Pro**: Direct feedback
- π§ **Mindful Aligner**: Balanced approach
""")
analyze_btn = gr.Button("π― Analyze My Form", variant="primary", size="lg")
with gr.Column(scale=2):
report_output = gr.Textbox(
label="π Technical Analysis",
lines=12,
placeholder="Upload a video and click 'Analyze My Form'..."
)
feedback_output = gr.Textbox(
label="π¬ Coach Feedback",
lines=10,
placeholder="Your personalized coaching feedback will appear here..."
)
with gr.Accordion("π Raw Data (JSON)", open=False):
json_output = gr.Textbox(
label="JSON Results",
lines=6
)
# Connect button to function
analyze_btn.click(
fn=analyze_video,
inputs=[video_input, persona_select],
outputs=[report_output, feedback_output, json_output],
api_name=False
)
gr.Markdown("""
---
### About
This app uses **4 fine-tuned DistilGPT-2 models**, each trained with a unique coaching personality.
Upload any push-up video to receive personalized form feedback!
""")
# Launch the app
if __name__ == "__main__":
demo.launch()
|