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 |
+
|
| 3 |
+
|
| 4 |
+
# ==============================================================================
|
| 5 |
+
# ENHANCED APP: AI-Powered Fitness Coach
|
| 6 |
+
# ==============================================================================
|
| 7 |
+
#
|
| 8 |
+
# Author: Your Name (Originally by [Original Author Name])
|
| 9 |
+
# Bootcamp: GenAI Bootcamp
|
| 10 |
+
# Project: Showcase Project
|
| 11 |
+
#
|
| 12 |
+
# Description:
|
| 13 |
+
# This Gradio application serves as a multi-agent AI fitness coach. It provides
|
| 14 |
+
# personalized recommendations for BMI/TDEE, workout plans, and nutrition.
|
| 15 |
+
#
|
| 16 |
+
# Enhancements in this version:
|
| 17 |
+
# 1. **Code Refactoring & Readability:** Improved structure, comments, and type hints.
|
| 18 |
+
# 2. **AI Coach Persona:** A new "persona" layer that delivers advice in a more
|
| 19 |
+
# conversational and encouraging tone, simulating a real coach.
|
| 20 |
+
# 3. **Improved UI/UX:** More polished Markdown outputs for a better user experience.
|
| 21 |
+
# 4. **Modular & Scalable:** Clear separation of concerns between data calculation
|
| 22 |
+
# (helpers), plan generation (agents), and user interface (Gradio).
|
| 23 |
+
# 5. **Educational Comments:** Added comments to explain key concepts and formulas,
|
| 24 |
+
# useful for the project presentation.
|
| 25 |
+
#
|
| 26 |
+
# ==============================================================================
|
| 27 |
+
|
| 28 |
+
import gradio as gr
|
| 29 |
+
from typing import List, Literal, Tuple
|
| 30 |
+
|
| 31 |
+
# ==============================================================================
|
| 32 |
+
# SECTION 1: CONFIGURATION & CONSTANTS
|
| 33 |
+
# ==============================================================================
|
| 34 |
+
|
| 35 |
+
# --- Motivation Banner (JavaScript) ---
|
| 36 |
+
# This JS snippet rotates motivational quotes in the UI to keep users engaged.
|
| 37 |
+
MOTIVATION_JS = """
|
| 38 |
+
<div id="motivation" class="motivation">Let’s begin strong! 🚀</div>
|
| 39 |
+
<script>
|
| 40 |
+
const MOTIVATION = [
|
| 41 |
+
"You’re doing great—one step at a time! 💪",
|
| 42 |
+
"Small habits, big results. Keep going. 🔁",
|
| 43 |
+
"Hydrate and move—your future self thanks you. 💧",
|
| 44 |
+
"Form first, weight second. You’ve got this. 🧠",
|
| 45 |
+
"Consistency beats intensity. Show up today. ✅",
|
| 46 |
+
];
|
| 47 |
+
let i = 0;
|
| 48 |
+
function tick(){
|
| 49 |
+
const el = document.getElementById("motivation");
|
| 50 |
+
if (!el) return;
|
| 51 |
+
el.textContent = MOTIVATION[i % MOTIVATION.length];
|
| 52 |
+
i++;
|
| 53 |
+
}
|
| 54 |
+
tick();
|
| 55 |
+
setInterval(tick, 10000);
|
| 56 |
+
</script>
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
# --- Activity Level Multipliers ---
|
| 60 |
+
# These values are used to calculate TDEE based on the Mifflin-St Jeor formula.
|
| 61 |
+
ACTIVITY_MULTIPLIERS = {
|
| 62 |
+
"Sedentary (office/no exercise)": 1.2,
|
| 63 |
+
"Light (1-3x/wk)": 1.375,
|
| 64 |
+
"Moderate (3-5x/wk)": 1.55,
|
| 65 |
+
"Active (6-7x/wk)": 1.725,
|
| 66 |
+
"Athlete (2x/day)": 1.9,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
# --- Nutrition Constants ---
|
| 70 |
+
PROTEIN_PER_KG = 1.6 # g/kg, a good starting point for muscle synthesis
|
| 71 |
+
FAT_MIN_G_PER_KG = 0.6 # g/kg, essential for hormonal function
|
| 72 |
+
|
| 73 |
+
# --- Default Food Options ---
|
| 74 |
+
# These lists provide a baseline for the meal planner if the user doesn't specify preferences.
|
| 75 |
+
DEFAULT_FOODS = {
|
| 76 |
+
"proteins": ["chicken breast", "eggs", "tuna", "lean beef", "laban protein", "tofu"],
|
| 77 |
+
"carbs": ["rice", "oats", "potatoes", "pasta", "whole-wheat bread", "dates", "fruit"],
|
| 78 |
+
"fats": ["olive oil", "avocado", "nuts", "tahini", "peanut butter"],
|
| 79 |
+
"veggies": ["salad mix", "cucumber", "tomato", "broccoli", "spinach"],
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# ==============================================================================
|
| 83 |
+
# SECTION 2: CORE HELPER FUNCTIONS
|
| 84 |
+
# (These functions perform the core calculations for fitness metrics.)
|
| 85 |
+
# ==============================================================================
|
| 86 |
+
|
| 87 |
+
def calculate_bmi(height_cm: float, weight_kg: float) -> float:
|
| 88 |
+
"""Calculates Body Mass Index (BMI)."""
|
| 89 |
+
if height_cm <= 0 or weight_kg <= 0:
|
| 90 |
+
return 0.0
|
| 91 |
+
height_m = height_cm / 100.0
|
| 92 |
+
return round(weight_kg / (height_m ** 2), 2)
|
| 93 |
+
|
| 94 |
+
def get_bmi_category(bmi: float) -> str:
|
| 95 |
+
"""Returns the BMI category string based on the BMI value."""
|
| 96 |
+
if bmi <= 0: return "Invalid inputs"
|
| 97 |
+
if bmi < 18.5: return "Underweight"
|
| 98 |
+
if bmi < 25: return "Normal"
|
| 99 |
+
if bmi < 30: return "Overweight"
|
| 100 |
+
return "Obese"
|
| 101 |
+
|
| 102 |
+
def calculate_bmr_mifflin(sex: Literal["male", "female"], age: int, height_cm: float, weight_kg: float) -> float:
|
| 103 |
+
"""Calculates Basal Metabolic Rate (BMR) using the Mifflin-St Jeor equation."""
|
| 104 |
+
# The Mifflin-St Jeor equation is considered more accurate than the older Harris-Benedict formula.
|
| 105 |
+
s_offset = 5 if sex == "male" else -161
|
| 106 |
+
return (10 * weight_kg) + (6.25 * height_cm) - (5 * age) + s_offset
|
| 107 |
+
|
| 108 |
+
def calculate_tdee(sex: str, age: int, height_cm: float, weight_kg: float, activity: str) -> Tuple[int, int, int]:
|
| 109 |
+
"""Calculates Total Daily Energy Expenditure (TDEE) and target calories."""
|
| 110 |
+
bmr = calculate_bmr_mifflin(sex, age, height_cm, weight_kg)
|
| 111 |
+
factor = ACTIVITY_MULTIPLIERS.get(activity, 1.2)
|
| 112 |
+
maintenance_calories = round(bmr * factor)
|
| 113 |
+
# Gentle fat loss (-500 kcal) and lean bulk (+300 kcal) are common, sustainable targets.
|
| 114 |
+
cut_calories = maintenance_calories - 500
|
| 115 |
+
bulk_calories = maintenance_calories + 300
|
| 116 |
+
return maintenance_calories, cut_calories, bulk_calories
|
| 117 |
+
|
| 118 |
+
def calculate_water_intake(weight_kg: float) -> int:
|
| 119 |
+
"""Estimates daily water intake based on body weight."""
|
| 120 |
+
# A common guideline is 35 ml of water per kg of body weight.
|
| 121 |
+
return int(weight_kg * 35)
|
| 122 |
+
|
| 123 |
+
def calculate_macros(weight_kg: float, calories: int) -> Tuple[int, int, int]:
|
| 124 |
+
"""Calculates macronutrient split (Protein, Carbs, Fat) for a given calorie target."""
|
| 125 |
+
protein_g = int(round(PROTEIN_PER_KG * weight_kg))
|
| 126 |
+
fat_g = int(round(FAT_MIN_G_PER_KG * weight_kg))
|
| 127 |
+
calories_from_protein = protein_g * 4
|
| 128 |
+
calories_from_fat = fat_g * 9
|
| 129 |
+
remaining_calories = calories - calories_from_protein - calories_from_fat
|
| 130 |
+
carbs_g = max(0, int(round(remaining_calories / 4)))
|
| 131 |
+
return protein_g, carbs_g, fat_g
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def filter_foods(options: List[str], avoid: List[str]) -> List[str]:
|
| 136 |
+
"""Filters a list of food options based on a list of items to avoid."""
|
| 137 |
+
avoid_set = {a.strip().lower() for a in avoid if a.strip()}
|
| 138 |
+
res = []
|
| 139 |
+
for o in options:
|
| 140 |
+
if any(bad in o.lower() for bad in avoid_set):
|
| 141 |
+
continue
|
| 142 |
+
res.append(o)
|
| 143 |
+
return res
|
| 144 |
+
|
| 145 |
+
# --- Workout Split Definitions ---
|
| 146 |
+
# These define the workout routines for different goals and days.
|
| 147 |
+
GOAL_SPLITS = {
|
| 148 |
+
"Lose fat": ["FBW", "FBW", "LISS Cardio", "Mobility"],
|
| 149 |
+
"Maintain": ["Upper", "Lower", "Full Body", "HIIT/Cardio", "Mobility"],
|
| 150 |
+
"Build muscle": ["Push", "Pull", "Legs", "Upper", "Lower", "Mobility"],
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
def session_template(name: str) -> List[str]:
|
| 154 |
+
"""Provides a compact, beginner-friendly template for a given workout session type."""
|
| 155 |
+
# Equipment and level considerations can be added here for more dynamic templates.
|
| 156 |
+
if name == "FBW":
|
| 157 |
+
return [
|
| 158 |
+
"Goblet Squat 3x8-10",
|
| 159 |
+
"Push-ups (incline if needed) 3x6-10",
|
| 160 |
+
"Dumbbell Row 3x10",
|
| 161 |
+
"Hip Hinge (RDL/Good Morning) 3x10",
|
| 162 |
+
"Plank 3x30-45s",
|
| 163 |
+
]
|
| 164 |
+
if name == "Upper":
|
| 165 |
+
return [
|
| 166 |
+
"DB Bench Press 3x8-10",
|
| 167 |
+
"One-arm Row 3x10/side",
|
| 168 |
+
"DB Shoulder Press 3x10",
|
| 169 |
+
"Lat Pulldown or Assisted Pull 3x8-10",
|
| 170 |
+
"Facepull / Band Pull-apart 3x12-15",
|
| 171 |
+
]
|
| 172 |
+
if name == "Lower":
|
| 173 |
+
return [
|
| 174 |
+
"Squat pattern 4x6-10",
|
| 175 |
+
"Hinge pattern 3x8-10",
|
| 176 |
+
"Split Squat/Lunge 3x8/leg",
|
| 177 |
+
"Calf Raise 3x12-15",
|
| 178 |
+
"Core: Deadbug 3x10",
|
| 179 |
+
]
|
| 180 |
+
if name == "Push":
|
| 181 |
+
return [
|
| 182 |
+
"DB Bench Press 4x6-10",
|
| 183 |
+
"Incline Push-ups 3x10",
|
| 184 |
+
"DB Shoulder Press 3x8-10",
|
| 185 |
+
"Lateral Raise 3x12-15",
|
| 186 |
+
"Triceps Extensions 3x10-12",
|
| 187 |
+
]
|
| 188 |
+
if name == "Pull":
|
| 189 |
+
return [
|
| 190 |
+
"Lat Pulldown / Assisted Pull-ups 4x6-10",
|
| 191 |
+
"Seated Row / One-arm Row 3x10",
|
| 192 |
+
"Rear Delt Raise 3x12-15",
|
| 193 |
+
"DB Curl 3x10-12",
|
| 194 |
+
"Back Extension 3x12",
|
| 195 |
+
]
|
| 196 |
+
if name == "Legs":
|
| 197 |
+
return [
|
| 198 |
+
"Back/Front/Goblet Squat 4x6-10",
|
| 199 |
+
"Romanian Deadlift 3x8-10",
|
| 200 |
+
"Leg Press or Step-ups 3x10",
|
| 201 |
+
"Hamstring Curl 3x10-12",
|
| 202 |
+
"Core: Side Plank 3x30s/side",
|
| 203 |
+
]
|
| 204 |
+
if name == "HIIT/Cardio":
|
| 205 |
+
return ["20–25 min intervals (1 fast / 1 easy) OR 30–40 min brisk walk"]
|
| 206 |
+
if name == "LISS Cardio":
|
| 207 |
+
return ["30–45 min easy jog/bike/walk (Zone 2)"]
|
| 208 |
+
if name == "Mobility":
|
| 209 |
+
return ["15–20 min mobility + light stretching & breathing"]
|
| 210 |
+
return ["Rest / Light activity (walk 6–8k steps)"]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# ==============================================================================
|
| 214 |
+
# SECTION 3: AGENT FUNCTIONS
|
| 215 |
+
# (These functions act as specialized "agents" providing fitness advice.)
|
| 216 |
+
# ==============================================================================
|
| 217 |
+
|
| 218 |
+
def agent_bmi_tdee(sex: str, age: int, height_cm: float, weight_kg: float, activity: str, goal: str) -> str:
|
| 219 |
+
"""Agent for calculating BMI, TDEE, and daily calorie targets."""
|
| 220 |
+
bmi = calculate_bmi(height_cm, weight_kg)
|
| 221 |
+
category = get_bmi_category(bmi)
|
| 222 |
+
maintenance_cals, cut_cals, bulk_cals = calculate_tdee(sex, age, height_cm, weight_kg, activity)
|
| 223 |
+
|
| 224 |
+
target_cals = {"Lose fat": cut_cals, "Maintain": maintenance_cals, "Build muscle": bulk_cals}[goal]
|
| 225 |
+
water_ml = calculate_water_intake(weight_kg)
|
| 226 |
+
water_l = round(water_ml / 1000, 1)
|
| 227 |
+
|
| 228 |
+
coach_message = generate_coach_response("bmi_tdee", {
|
| 229 |
+
"bmi": bmi, "category": category, "maintenance_cals": maintenance_cals,
|
| 230 |
+
"target_cals": target_cals, "goal": goal, "water_l": water_l
|
| 231 |
+
})
|
| 232 |
+
return coach_message
|
| 233 |
+
|
| 234 |
+
def agent_workout(level: str, days_per_week: int, goal: str, equipment: str) -> str:
|
| 235 |
+
"""Agent for generating a weekly workout plan."""
|
| 236 |
+
days_per_week = max(2, min(6, int(days_per_week))) # Ensure days are between 2 and 6
|
| 237 |
+
base_split = GOAL_SPLITS[goal]
|
| 238 |
+
workout_plan = []
|
| 239 |
+
|
| 240 |
+
for i in range(days_per_week):
|
| 241 |
+
session_name = base_split[i % len(base_split)]
|
| 242 |
+
exercises = session_template(session_name)
|
| 243 |
+
workout_plan.append((f"Day {i+1} — {session_name}", exercises))
|
| 244 |
+
|
| 245 |
+
coach_message = generate_coach_response("workout", {
|
| 246 |
+
"workout_plan": workout_plan, "goal": goal, "level": level, "equipment": equipment
|
| 247 |
+
})
|
| 248 |
+
return coach_message
|
| 249 |
+
|
| 250 |
+
def agent_nutrition(weight_kg: float, target_kcal: int, liked_csv: str, avoid_csv: str, meals: int) -> str:
|
| 251 |
+
"""Agent for generating a nutrition plan and macronutrient breakdown."""
|
| 252 |
+
liked_foods = [x.strip() for x in liked_csv.split(",") if x.strip()]
|
| 253 |
+
avoid_foods = [x.strip() for x in avoid_csv.split(",") if x.strip()]
|
| 254 |
+
|
| 255 |
+
# Filter default foods based on user preferences and avoidances
|
| 256 |
+
proteins = filter_foods((liked_foods or DEFAULT_FOODS["proteins"]), avoid_foods)
|
| 257 |
+
carbs = filter_foods(DEFAULT_FOODS["carbs"], avoid_foods)
|
| 258 |
+
fats = filter_foods(DEFAULT_FOODS["fats"], avoid_foods)
|
| 259 |
+
veggies = filter_foods(DEFAULT_FOODS["veggies"], avoid_foods)
|
| 260 |
+
|
| 261 |
+
protein_g, carb_g, fat_g = calculate_macros(weight_kg, target_kcal)
|
| 262 |
+
meals_per_day = max(1, meals)
|
| 263 |
+
protein_per_meal, carb_per_meal, fat_per_meal = protein_g // meals_per_day, carb_g // meals_per_day, fat_g // meals_per_day
|
| 264 |
+
|
| 265 |
+
sample_day_meals = [
|
| 266 |
+
f"Meal {i+1}: {proteins[i % len(proteins)]} + {carbs[i % len(carbs)]} "
|
| 267 |
+
f"+ {veggies[i % len(veggies)]} + {fats[i % len(fats)]}"
|
| 268 |
+
for i in range(meals_per_day)
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
coach_message = generate_coach_response("nutrition", {
|
| 272 |
+
"target_kcal": target_kcal, "protein_g": protein_g, "carb_g": carb_g, "fat_g": fat_g,
|
| 273 |
+
"protein_per_meal": protein_per_meal, "carb_per_meal": carb_per_meal, "fat_per_meal": fat_per_meal,
|
| 274 |
+
"sample_day_meals": sample_day_meals, "proteins": proteins, "carbs": carbs, "fats": fats, "veggies": veggies
|
| 275 |
+
})
|
| 276 |
+
return coach_message
|
| 277 |
+
|
| 278 |
+
def coach_all_in_one(
|
| 279 |
+
sex, age, height_cm, weight_kg, activity, goal,
|
| 280 |
+
level, days, equipment,
|
| 281 |
+
liked_csv, avoid_csv, meals
|
| 282 |
+
) -> str:
|
| 283 |
+
"""Combines all agents to provide a comprehensive fitness and nutrition plan."""
|
| 284 |
+
# BMI & TDEE Report
|
| 285 |
+
bmi_tdee_report = agent_bmi_tdee(sex, age, height_cm, weight_kg, activity, goal)
|
| 286 |
+
|
| 287 |
+
# Calculate target calories for nutrition agent
|
| 288 |
+
_, cut_cals, bulk_cals = calculate_tdee(sex, age, height_cm, weight_kg, activity)
|
| 289 |
+
target_kcal_for_nutrition = {"Lose fat": cut_cals, "Maintain": calculate_tdee(sex, age, height_cm, weight_kg, activity)[0], "Build muscle": bulk_cals}[goal]
|
| 290 |
+
|
| 291 |
+
# Workout Plan
|
| 292 |
+
workout_report = agent_workout(level, days, goal, equipment)
|
| 293 |
+
|
| 294 |
+
# Nutrition Plan
|
| 295 |
+
nutrition_report = agent_nutrition(weight_kg, target_kcal_for_nutrition, liked_csv, avoid_csv, meals)
|
| 296 |
+
|
| 297 |
+
return f"{bmi_tdee_report}\n---\n{workout_report}\n---\n{nutrition_report}"
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# ==============================================================================
|
| 301 |
+
# SECTION 4: AI COACH PERSONA - RESPONSE GENERATION
|
| 302 |
+
# (This function adds a conversational layer to the output.)
|
| 303 |
+
# ==============================================================================
|
| 304 |
+
|
| 305 |
+
def generate_coach_response(agent_type: str, data: dict) -> str:
|
| 306 |
+
"""Generates a coach-like, encouraging response based on agent output.
|
| 307 |
+
This adds a 'persona' to the AI, making the interaction more engaging.
|
| 308 |
+
"""
|
| 309 |
+
if agent_type == "bmi_tdee":
|
| 310 |
+
bmi = data["bmi"]
|
| 311 |
+
category = data["category"]
|
| 312 |
+
maintenance_cals = data["maintenance_cals"]
|
| 313 |
+
target_cals = data["target_cals"]
|
| 314 |
+
goal = data["goal"]
|
| 315 |
+
water_l = data["water_l"]
|
| 316 |
+
|
| 317 |
+
response = f"""### 📊 Your Fitness Snapshot, Coach!
|
| 318 |
+
Hey there, future fitness legend! Let's break down your numbers:
|
| 319 |
+
|
| 320 |
+
- **BMI:** `{bmi}` → **{category}**
|
| 321 |
+
*Coach says:* This gives us a baseline, but remember, it's just one piece of the puzzle! We focus on overall health.
|
| 322 |
+
- **Maintenance Calories:** **{maintenance_cals} kcal/day**
|
| 323 |
+
*Coach says:* This is your daily energy sweet spot to stay exactly where you are.
|
| 324 |
+
- **Target for your goal ({goal}):** **{target_cals} kcal/day**
|
| 325 |
+
*Coach says:* To hit your {goal.lower()} goal, we're aiming for this calorie target. Every bite counts towards your success!
|
| 326 |
+
- **Water recommendation:** ~ **{water_l} L/day**
|
| 327 |
+
*Coach says:* Hydration is key for energy, recovery, and overall awesomeness! Keep that water bottle close.
|
| 328 |
+
|
| 329 |
+
Great start! Let's keep this momentum going!"""
|
| 330 |
+
|
| 331 |
+
elif agent_type == "workout":
|
| 332 |
+
workout_plan = data["workout_plan"]
|
| 333 |
+
goal = data["goal"]
|
| 334 |
+
level = data["level"]
|
| 335 |
+
equipment = data["equipment"]
|
| 336 |
+
|
| 337 |
+
plan_md = ""
|
| 338 |
+
for title, items in workout_plan:
|
| 339 |
+
plan_md += f"\n**{title}**\n" + "\n".join([f"- {x}" for x in items]) + "\n"
|
| 340 |
+
|
| 341 |
+
response = f"""### 🏋️ Your Personalized Workout Plan, Champ!
|
| 342 |
+
Alright, {level} athlete! Here’s your custom workout roadmap to {goal.lower()}:
|
| 343 |
+
{plan_md}
|
| 344 |
+
*Coach says:* Remember to warm up, cool down, and listen to your body. Focus on form over weight, and let's crush those goals! Rest 60–90s between sets. Aim for ~2 reps in reserve (RIR 2).
|
| 345 |
+
|
| 346 |
+
Let's get those gains!"""
|
| 347 |
+
|
| 348 |
+
elif agent_type == "nutrition":
|
| 349 |
+
target_kcal = data["target_kcal"]
|
| 350 |
+
protein_g = data["protein_g"]
|
| 351 |
+
carb_g = data["carb_g"]
|
| 352 |
+
fat_g = data["fat_g"]
|
| 353 |
+
protein_per_meal = data["protein_per_meal"]
|
| 354 |
+
carb_per_meal = data["carb_per_meal"]
|
| 355 |
+
fat_per_meal = data["fat_per_meal"]
|
| 356 |
+
sample_day_meals = data["sample_day_meals"]
|
| 357 |
+
proteins = data["proteins"]
|
| 358 |
+
carbs = data["carbs"]
|
| 359 |
+
fats = data["fats"]
|
| 360 |
+
veggies = data["veggies"]
|
| 361 |
+
|
| 362 |
+
sample_meals_md = chr(10).join([f"- {m}" for m in sample_day_meals])
|
| 363 |
+
|
| 364 |
+
response = f"""### 🥗 Fuel Your Success: Your Nutrition Blueprint!
|
| 365 |
+
Nutrition is your secret weapon, and here’s how we’re fueling your body for **{target_kcal} kcal/day**:
|
| 366 |
+
|
| 367 |
+
- **Macros (approx.):** Protein **{protein_g} g**, Carbs **{carb_g} g**, Fat **{fat_g} g**
|
| 368 |
+
*Coach says:* This balance will support your energy and recovery. Per meal, that's roughly **{protein_per_meal}/{carb_per_meal}/{fat_per_meal} g** (P/C/F).
|
| 369 |
+
- **Preferred foods used:** {
|
| 370 |
+
|
| 371 |
+
", ".join(proteins[:3])} …
|
| 372 |
+
|
| 373 |
+
**Sample Day:**
|
| 374 |
+
{sample_meals_md}
|
| 375 |
+
|
| 376 |
+
**Grocery list (starter):**
|
| 377 |
+
- **Protein:** {", ".join(proteins)}
|
| 378 |
+
- **Carbs:** {", ".join(carbs)}
|
| 379 |
+
- **Fats:** {", ".join(fats)}
|
| 380 |
+
- **Veggies:** {", ".join(veggies)}
|
| 381 |
+
|
| 382 |
+
*Coach says:* Aim for 20–30g protein per meal, load up on diverse veggies, and don't forget 1–2 pieces of fruit daily for those vital micronutrients! Let’s nourish that body!"""
|
| 383 |
+
|
| 384 |
+
else:
|
| 385 |
+
response = """### 🤔 Unrecognized Request
|
| 386 |
+
My apologies, coach. I'm not sure how to respond to that request yet. Let's stick to the plan!"""
|
| 387 |
+
|
| 388 |
+
return response
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# ==============================================================================
|
| 392 |
+
# SECTION 5: GRADIO USER INTERFACE
|
| 393 |
+
# (Defines the interactive web interface using Gradio.)
|
| 394 |
+
# ==============================================================================
|
| 395 |
+
|
| 396 |
+
with gr.Blocks(
|
| 397 |
+
title="Beginner Gym Coach — Multi-Agent",
|
| 398 |
+
css="""
|
| 399 |
+
.motivation{
|
| 400 |
+
background:#fff6e5;
|
| 401 |
+
border-left:6px solid #ffa84b;
|
| 402 |
+
padding:10px 14px;
|
| 403 |
+
border-radius:8px;
|
| 404 |
+
font-size:16px;
|
| 405 |
+
margin-bottom:10px;
|
| 406 |
+
}
|
| 407 |
+
h3 { font-size: 1.5em; margin-top: 1em; }
|
| 408 |
+
h4 { font-size: 1.2em; margin-top: 0.8em; }
|
| 409 |
+
strong { color: #2E8B57; } /* A nice green for emphasis */
|
| 410 |
+
/* Further styling can be added here for a more polished look */
|
| 411 |
+
"""
|
| 412 |
+
) as demo:
|
| 413 |
+
gr.Markdown("## 🏋️ Beginner Gym Coach — Multi-Agent\n### Your AI-Powered Guide to a Healthier You!\nGive me your basics and I’ll coach you to success.")
|
| 414 |
+
gr.HTML(MOTIVATION_JS)
|
| 415 |
+
|
| 416 |
+
with gr.Tabs():
|
| 417 |
+
# -------- BMI & TDEE Tab --------
|
| 418 |
+
with gr.Tab("BMI & TDEE"):
|
| 419 |
+
gr.Markdown("#### Understand your body composition and daily energy needs.")
|
| 420 |
+
with gr.Row():
|
| 421 |
+
with gr.Column(scale=1):
|
| 422 |
+
sex = gr.Radio(["male","female"], value="female", label="Sex")
|
| 423 |
+
age = gr.Slider(15, 70, value=24, step=1, label="Age")
|
| 424 |
+
height = gr.Slider(130, 210, value=165, step=1, label="Height (cm)")
|
| 425 |
+
weight = gr.Slider(35, 160, value=60, step=0.5, label="Weight (kg)")
|
| 426 |
+
activity = gr.Dropdown(list(ACTIVITY_MULTIPLIERS.keys()),
|
| 427 |
+
value="Light (1-3x/wk)", label="Activity Level")
|
| 428 |
+
goal = gr.Radio(["Lose fat","Maintain","Build muscle"],
|
| 429 |
+
value="Maintain", label="Fitness Goal")
|
| 430 |
+
btn1 = gr.Button("Calculate BMI & TDEE")
|
| 431 |
+
with gr.Column(scale=1):
|
| 432 |
+
out1 = gr.Markdown()
|
| 433 |
+
btn1.click(agent_bmi_tdee, [sex, age, height, weight, activity, goal], out1)
|
| 434 |
+
|
| 435 |
+
# -------- Workout Plan Tab --------
|
| 436 |
+
with gr.Tab("Workout Plan"):
|
| 437 |
+
gr.Markdown("#### Get a structured weekly workout plan tailored to your goals.")
|
| 438 |
+
with gr.Row():
|
| 439 |
+
with gr.Column(scale=1):
|
| 440 |
+
level = gr.Radio(["Beginner","Intermediate"], value="Beginner", label="Experience Level")
|
| 441 |
+
days = gr.Slider(2, 6, value=4, step=1, label="Training Days per Week")
|
| 442 |
+
goal_w = gr.Radio(["Lose fat","Maintain","Build muscle"],
|
| 443 |
+
value="Build muscle", label="Workout Goal")
|
| 444 |
+
equipment = gr.Dropdown(["Gym (machines/dumbbells)",
|
| 445 |
+
"Home (bands/db)", "Bodyweight only"],
|
| 446 |
+
value="Gym (machines/dumbbells)", label="Available Equipment")
|
| 447 |
+
btn2 = gr.Button("Generate Workout Plan")
|
| 448 |
+
with gr.Column(scale=1):
|
| 449 |
+
out2 = gr.Markdown()
|
| 450 |
+
btn2.click(agent_workout, [level, days, goal_w, equipment], out2)
|
| 451 |
+
|
| 452 |
+
# -------- Nutrition Tab --------
|
| 453 |
+
with gr.Tab("Nutrition"):
|
| 454 |
+
gr.Markdown("#### Discover your macro breakdown and a sample meal plan.")
|
| 455 |
+
with gr.Row():
|
| 456 |
+
with gr.Column(scale=1):
|
| 457 |
+
target_kcal = gr.Number(value=1900, label="Target Calories (kcal/day)")
|
| 458 |
+
weight_n = gr.Number(value=60, label="Current Weight (kg)")
|
| 459 |
+
liked = gr.Textbox(label="Preferred foods (comma-separated)",
|
| 460 |
+
placeholder="e.g., chicken, eggs, rice, oats, salad, laban")
|
| 461 |
+
avoid = gr.Textbox(label="Foods to avoid (allergies, dislikes - comma-separated)",
|
| 462 |
+
placeholder="e.g., nuts, shrimp, gluten")
|
| 463 |
+
meals = gr.Slider(2, 6, value=3, step=1, label="Meals per Day")
|
| 464 |
+
btn3 = gr.Button("Build Meal Plan")
|
| 465 |
+
with gr.Column(scale=1):
|
| 466 |
+
out3 = gr.Markdown()
|
| 467 |
+
btn3.click(agent_nutrition, [weight_n, target_kcal, liked, avoid, meals], out3)
|
| 468 |
+
|
| 469 |
+
# -------- All-in-One Coach Tab --------
|
| 470 |
+
with gr.Tab("All-in-One Coach"):
|
| 471 |
+
gr.Markdown("#### Get a complete, integrated fitness and nutrition strategy.")
|
| 472 |
+
with gr.Row():
|
| 473 |
+
with gr.Column(scale=1):
|
| 474 |
+
sex2 = gr.Radio(["male","female"], value="female", label="Sex")
|
| 475 |
+
age2 = gr.Slider(15, 70, value=24, step=1, label="Age")
|
| 476 |
+
height2 = gr.Slider(130, 210, value=165, step=1, label="Height (cm)")
|
| 477 |
+
weight2 = gr.Slider(35, 160, value=60, step=0.5, label="Weight (kg)")
|
| 478 |
+
activity2 = gr.Dropdown(list(ACTIVITY_MULTIPLIERS.keys()),
|
| 479 |
+
value="Light (1-3x/wk)", label="Activity Level")
|
| 480 |
+
goal2 = gr.Radio(["Lose fat","Maintain","Build muscle"],
|
| 481 |
+
value="Build muscle", label="Overall Goal")
|
| 482 |
+
level2 = gr.Radio(["Beginner","Intermediate"], value="Beginner", label="Experience Level")
|
| 483 |
+
days2 = gr.Slider(2, 6, value=4, step=1, label="Training Days per Week")
|
| 484 |
+
equipment2 = gr.Dropdown(["Gym (machines/dumbbells)",
|
| 485 |
+
"Home (bands/db)", "Bodyweight only"],
|
| 486 |
+
value="Gym (machines/dumbbells)", label="Available Equipment")
|
| 487 |
+
liked2 = gr.Textbox(label="Preferred foods", placeholder="e.g., chicken, eggs, rice, potatoes")
|
| 488 |
+
avoid2 = gr.Textbox(label="Foods to avoid", placeholder="e.g., nuts, shrimp")
|
| 489 |
+
meals2 = gr.Slider(2, 6, value=3, step=1, label="Meals per Day")
|
| 490 |
+
btn4 = gr.Button("Get My Full Plan 🚀")
|
| 491 |
+
with gr.Column(scale=1):
|
| 492 |
+
out4 = gr.Markdown()
|
| 493 |
+
btn4.click(
|
| 494 |
+
coach_all_in_one,
|
| 495 |
+
[sex2, age2, height2, weight2, activity2, goal2,
|
| 496 |
+
level2, days2, equipment2, liked2, avoid2, meals2],
|
| 497 |
+
out4
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
if __name__ == "__main__":
|
| 501 |
+
demo.launch()
|
| 502 |
+
|