help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
fitness-coach-bot
/
utils
RSK World
fitness-coach-bot
Fitness Coach Bot - Python + Flask + SQLAlchemy + Workout Plans + Exercise Guidance + Health Tracking + AI Fitness Coach
utils
  • __pycache__
  • __init__.py965 B
  • ai_workout_generator.py18 KB
  • analytics_engine.py27.8 KB
  • fitness_coach.py13.3 KB
  • gamification_system.py30.4 KB
  • nutrition_ai.py23.8 KB
  • smart_recovery.py11 KB
  • social_features.py19.4 KB
  • voice_coach.py10 KB
  • wearable_integration.py27 KB
  • workout_buddy_matcher.py9.5 KB
ai_workout_generator.py
utils/ai_workout_generator.py
Raw Download
Find: Go to:
"""
AI Workout Generator - Advanced Personalized Workout Creation
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import random
import json
from datetime import datetime, timedelta
from typing import Dict, List, Any

class AIWorkoutGenerator:
    """Advanced AI-powered workout generator with personalization"""
    
    def __init__(self):
        self.exercise_database = self._load_exercise_database()
        self.workout_templates = self._load_workout_templates()
        
    def _load_exercise_database(self) -> Dict:
        """Load comprehensive exercise database"""
        return {
            "chest": {
                "beginner": ["Push-ups", "Wall Push-ups", "Incline Push-ups", "Chest Press Machine"],
                "intermediate": ["Bench Press", "Dumbbell Flyes", "Incline Dumbbell Press", "Cable Crossovers"],
                "advanced": ["Weighted Dips", "Explosive Push-ups", "One-arm Push-ups", "Chain Bench Press"]
            },
            "back": {
                "beginner": ["Supermans", "Bird Dogs", "Resistance Band Rows", "Lat Pulldown Machine"],
                "intermediate": ["Pull-ups", "Bent-over Rows", "T-bar Rows", "Seated Cable Rows"],
                "advanced": ["Muscle-ups", "Deadlifts", "Weighted Pull-ups", "Kettlebell Swings"]
            },
            "legs": {
                "beginner": ["Bodyweight Squats", "Lunges", "Glute Bridges", "Calf Raises"],
                "intermediate": ["Barbell Squats", "Leg Press", "Romanian Deadlifts", "Bulgarian Split Squats"],
                "advanced": ["Pistol Squats", "Box Jumps", "Weighted Walking Lunges", "Front Squats"]
            },
            "shoulders": {
                "beginner": ["Arm Circles", "Wall Angels", "Resistance Band Press", "Dumbbell Lateral Raises"],
                "intermediate": ["Overhead Press", "Arnold Press", "Upright Rows", "Face Pulls"],
                "advanced": ["Handstand Push-ups", "Barbell Push Press", "Snatch", "Kettlebell Press"]
            },
            "core": {
                "beginner": ["Plank", "Dead Bug", "Bird Dog", "Crunches"],
                "intermediate": ["Hanging Leg Raises", "Russian Twists", "Ab Rollouts", "Dragon Flags"],
                "advanced": ["Front Lever", "Planche", "Human Flag", "Weighted Planks"]
            },
            "cardio": {
                "beginner": ["Walking", "Light Jogging", "Cycling (moderate)", "Elliptical"],
                "intermediate": ["HIIT Running", "Rowing", "Stair Climber", "Jump Rope"],
                "advanced": ["Sprinting Intervals", "Battle Ropes", "Boxing", "CrossFit WODs"]
            }
        }
    
    def _load_workout_templates(self) -> Dict:
        """Load workout templates for different goals"""
        return {
            "weight_loss": {
                "focus": ["cardio", "full_body"],
                "intensity": "moderate_to_high",
                "duration": 45,
                "frequency": 5
            },
            "muscle_gain": {
                "focus": ["strength", "hypertrophy"],
                "intensity": "high",
                "duration": 60,
                "frequency": 4
            },
            "endurance": {
                "focus": ["cardio", "functional"],
                "intensity": "moderate",
                "duration": 50,
                "frequency": 6
            },
            "strength": {
                "focus": ["compound", "heavy"],
                "intensity": "high",
                "duration": 70,
                "frequency": 3
            },
            "general_fitness": {
                "focus": ["balanced", "functional"],
                "intensity": "moderate",
                "duration": 45,
                "frequency": 4
            }
        }
    
    def generate_personalized_workout(self, user_profile: Dict, preferences: Dict = None) -> Dict:
        """Generate AI-powered personalized workout"""
        
        # Extract user information
        fitness_level = user_profile.get('fitness_level', 'beginner')
        goal = user_profile.get('goal', 'general_fitness')
        available_time = user_profile.get('available_time', 45)
        equipment = user_profile.get('equipment', ['bodyweight'])
        limitations = user_profile.get('limitations', [])
        
        # Get workout template
        template = self.workout_templates.get(goal, self.workout_templates['general_fitness'])
        
        # Generate workout structure
        workout = {
            "user_id": user_profile.get('id'),
            "date": datetime.now().isoformat(),
            "goal": goal,
            "fitness_level": fitness_level,
            "estimated_duration": available_time,
            "estimated_calories": self._estimate_calories(goal, fitness_level, available_time),
            "warmup": self._generate_warmup(fitness_level, 5),
            "main_workout": self._generate_main_workout(
                template, fitness_level, available_time, equipment, limitations
            ),
            "cool_down": self._generate_cool_down(fitness_level, 5),
            "tips": self._generate_workout_tips(goal, fitness_level),
            "progression_plan": self._generate_progression_plan(goal, fitness_level)
        }
        
        return workout
    
    def _generate_main_workout(self, template: Dict, fitness_level: str, 
                             available_time: int, equipment: List[str], 
                             limitations: List[str]) -> List[Dict]:
        """Generate main workout exercises"""
        
        focus_areas = template['focus']
        exercises = []
        time_per_exercise = (available_time - 10) / 6  # Account for warmup/cooldown
        
        # Select exercises based on focus areas
        if "full_body" in focus_areas or "balanced" in focus_areas:
            muscle_groups = ["chest", "back", "legs", "shoulders", "core"]
        elif "strength" in focus_areas or "hypertrophy" in focus_areas:
            muscle_groups = ["chest", "back", "legs", "shoulders"]
        else:
            muscle_groups = random.sample(["chest", "back", "legs", "shoulders", "core"], 3)
        
        for muscle_group in muscle_groups:
            if muscle_group in self.exercise_database:
                # Select appropriate exercise
                level_exercises = self.exercise_database[muscle_group][fitness_level]
                available_exercises = [ex for ex in level_exercises 
                                    if self._check_equipment_compatibility(ex, equipment)]
                
                if available_exercises:
                    exercise = random.choice(available_exercises)
                    exercises.append({
                        "name": exercise,
                        "muscle_group": muscle_group,
                        "sets": self._determine_sets(fitness_level, template['intensity']),
                        "reps": self._determine_reps(fitness_level, muscle_group),
                        "rest_time": self._determine_rest_time(fitness_level, template['intensity']),
                        "duration": time_per_exercise,
                        "instructions": self._get_exercise_instructions(exercise),
                        "form_tips": self._get_form_tips(exercise)
                    })
        
        return exercises
    
    def _generate_warmup(self, fitness_level: str, duration: int) -> List[Dict]:
        """Generate warmup routine"""
        warmup_exercises = [
            "Jumping Jacks", "High Knees", "Arm Circles", "Leg Swings", 
            "Hip Circles", "Torso Twists", "Light Jogging"
        ]
        
        return [
            {
                "name": random.choice(warmup_exercises),
                "duration": duration // len(warmup_exercises),
                "intensity": "light"
            } for _ in range(min(4, len(warmup_exercises)))
        ]
    
    def _generate_cool_down(self, fitness_level: str, duration: int) -> List[Dict]:
        """Generate cool-down routine"""
        stretches = [
            "Hamstring Stretch", "Quad Stretch", "Chest Stretch", 
            "Back Stretch", "Shoulder Stretch", "Triceps Stretch"
        ]
        
        return [
            {
                "name": random.choice(stretches),
                "duration": duration // len(stretches),
                "type": "static_stretch"
            } for _ in range(min(4, len(stretches)))
        ]
    
    def _estimate_calories(self, goal: str, fitness_level: str, duration: int) -> int:
        """Estimate calories burned"""
        base_calories = {
            "beginner": 5,
            "intermediate": 8,
            "advanced": 12
        }
        
        goal_multiplier = {
            "weight_loss": 1.3,
            "muscle_gain": 1.1,
            "endurance": 1.4,
            "strength": 0.9,
            "general_fitness": 1.0
        }
        
        return int(base_calories[fitness_level] * duration * goal_multiplier.get(goal, 1.0))
    
    def _determine_sets(self, fitness_level: str, intensity: str) -> int:
        """Determine number of sets"""
        base_sets = {"beginner": 2, "intermediate": 3, "advanced": 4}
        intensity_multiplier = {"moderate": 1, "high": 1.2, "moderate_to_high": 1.1}
        
        return int(base_sets[fitness_level] * intensity_multiplier.get(intensity, 1.0))
    
    def _determine_reps(self, fitness_level: str, muscle_group: str) -> str:
        """Determine rep range"""
        if muscle_group == "cardio":
            return "30-60 seconds"
        
        rep_ranges = {
            "beginner": "8-12",
            "intermediate": "10-15",
            "advanced": "12-20"
        }
        
        return rep_ranges[fitness_level]
    
    def _determine_rest_time(self, fitness_level: str, intensity: str) -> str:
        """Determine rest time between sets"""
        if intensity == "high":
            return "60-90 seconds"
        elif intensity == "moderate_to_high":
            return "45-60 seconds"
        else:
            return "30-45 seconds"
    
    def _check_equipment_compatibility(self, exercise: str, available_equipment: List[str]) -> bool:
        """Check if exercise is compatible with available equipment"""
        exercise_requirements = {
            "Bench Press": ["barbell", "bench"],
            "Pull-ups": ["pull_up_bar"],
            "Barbell Squats": ["barbell", "squat_rack"],
            "Deadlifts": ["barbell"],
            "Weighted Dips": ["dip_station", "weight_belt"],
            "Muscle-ups": ["pull_up_bar", "rings"],
            "Handstand Push-ups": [],
            "Front Lever": ["pull_up_bar"],
            "Planche": [],
            "Human Flag": ["pole"]
        }
        
        requirements = exercise_requirements.get(exercise, [])
        return all(req in available_equipment for req in requirements) or not requirements
    
    def _get_exercise_instructions(self, exercise: str) -> str:
        """Get exercise instructions"""
        instructions_db = {
            "Push-ups": "Start in plank position, lower body until chest nearly touches floor, push back up",
            "Squats": "Stand with feet shoulder-width apart, lower hips back and down, return to standing",
            "Pull-ups": "Hang from pull-up bar, pull body up until chin clears bar, lower slowly",
            "Plank": "Hold push-up position with body straight, engage core muscles"
        }
        
        return instructions_db.get(exercise, "Follow proper form and technique for this exercise")
    
    def _get_form_tips(self, exercise: str) -> List[str]:
        """Get form tips for exercise"""
        tips_db = {
            "Push-ups": ["Keep core tight", "Maintain straight line from head to heels", "Lower chest to floor"],
            "Squats": ["Keep chest up", "Knees behind toes", "Go to parallel or lower"],
            "Pull-ups": ["Engage back muscles", "Full range of motion", "Control negative portion"]
        }
        
        return tips_db.get(exercise, ["Maintain proper form", "Breathe correctly", "Start with light weight"])
    
    def _generate_workout_tips(self, goal: str, fitness_level: str) -> List[str]:
        """Generate workout-specific tips"""
        tips = []
        
        if goal == "weight_loss":
            tips.extend([
                "Focus on compound movements for maximum calorie burn",
                "Keep rest periods short to maintain heart rate",
                "Combine with proper nutrition for best results"
            ])
        elif goal == "muscle_gain":
            tips.extend([
                "Progressive overload is key - increase weight/reps over time",
                "Ensure adequate protein intake (1.6-2.2g per kg)",
                "Allow 48 hours recovery between training same muscle groups"
            ])
        
        if fitness_level == "beginner":
            tips.append("Focus on form before increasing intensity")
        
        return tips
    
    def _generate_progression_plan(self, goal: str, fitness_level: str) -> Dict:
        """Generate 4-week progression plan"""
        return {
            "week_1": {
                "focus": "Technique and adaptation",
                "intensity": "60% of max effort",
                "volume": "3 sets x 10-12 reps"
            },
            "week_2": {
                "focus": "Building foundation",
                "intensity": "70% of max effort",
                "volume": "3-4 sets x 8-12 reps"
            },
            "week_3": {
                "focus": "Increasing intensity",
                "intensity": "80% of max effort",
                "volume": "4 sets x 8-10 reps"
            },
            "week_4": {
                "focus": "Peak performance",
                "intensity": "85-90% of max effort",
                "volume": "4-5 sets x 6-8 reps"
            }
        }
    
    def generate_ai_insights(self, workout_history: List[Dict]) -> Dict:
        """Generate AI-powered insights from workout history"""
        if not workout_history:
            return {"message": "Start working out to get personalized insights!"}
        
        # Analyze patterns
        total_workouts = len(workout_history)
        avg_duration = sum(w.get('duration', 0) for w in workout_history) / total_workouts
        most_trained = self._analyze_most_trained(workout_history)
        consistency_score = self._calculate_consistency(workout_history)
        
        insights = {
            "total_workouts": total_workouts,
            "average_duration": round(avg_duration, 1),
            "consistency_score": consistency_score,
            "most_trained_muscle_groups": most_trained,
            "recommendations": self._generate_recommendations(workout_history),
            "achievement_badges": self._check_achievements(workout_history)
        }
        
        return insights
    
    def _analyze_most_trained(self, workout_history: List[Dict]) -> List[str]:
        """Analyze most trained muscle groups"""
        muscle_counts = {}
        for workout in workout_history:
            for exercise in workout.get('exercises', []):
                muscle = exercise.get('muscle_group', 'unknown')
                muscle_counts[muscle] = muscle_counts.get(muscle, 0) + 1
        
        return sorted(muscle_counts.keys(), key=lambda x: muscle_counts[x], reverse=True)[:3]
    
    def _calculate_consistency(self, workout_history: List[Dict]) -> float:
        """Calculate workout consistency score"""
        if len(workout_history) < 2:
            return 0.0
        
        dates = [datetime.fromisoformat(w.get('date', '')) for w in workout_history]
        dates.sort()
        
        # Calculate average days between workouts
        intervals = [(dates[i] - dates[i-1]).days for i in range(1, len(dates))]
        avg_interval = sum(intervals) / len(intervals)
        
        # Ideal is 2-3 days between workouts
        if 2 <= avg_interval <= 3:
            return 100.0
        elif avg_interval <= 4:
            return 80.0
        else:
            return max(0, 60.0 - (avg_interval - 4) * 10)
    
    def _generate_recommendations(self, workout_history: List[Dict]) -> List[str]:
        """Generate personalized recommendations"""
        recommendations = []
        
        if len(workout_history) < 4:
            recommendations.append("Try to work out at least 3 times per week for best results")
        
        muscle_groups = self._analyze_most_trained(workout_history)
        if len(muscle_groups) < 3:
            recommendations.append("Add variety to target different muscle groups")
        
        avg_duration = sum(w.get('duration', 0) for w in workout_history) / len(workout_history)
        if avg_duration < 30:
            recommendations.append("Consider extending workouts to 30-45 minutes")
        
        return recommendations
    
    def _check_achievements(self, workout_history: List[Dict]) -> List[Dict]:
        """Check for achievement badges"""
        achievements = []
        
        if len(workout_history) >= 10:
            achievements.append({
                "name": "Dedicated Athlete",
                "description": "Completed 10 workouts",
                "icon": "🏆"
            })
        
        if len(workout_history) >= 30:
            achievements.append({
                "name": "Fitness Warrior",
                "description": "Completed 30 workouts",
                "icon": "⚔️"
            })
        
        total_duration = sum(w.get('duration', 0) for w in workout_history)
        if total_duration >= 1000:  # ~16.6 hours
            achievements.append({
                "name": "Time Champion",
                "description": "1000+ minutes of exercise",
                "icon": "⏰"
            })
        
        return achievements
422 lines•18 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer