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
fitness_coach.py
utils/fitness_coach.py
Raw Download
Find: Go to:
"""
Fitness Coach Bot - AI-powered fitness coaching engine
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

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

class FitnessCoach:
    """Main fitness coaching AI that provides personalized fitness advice"""
    
    def __init__(self):
        self.greeting_patterns = [
            r'^(hi|hello|hey|good morning|good afternoon|good evening)',
            r'^(how are you|how do you do)',
            r'^(what\'s up|sup)'
        ]
        
        self.workout_requests = [
            r'(workout|exercise|training|fitness|gym)',
            r'(plan|routine|schedule|program)',
            r'(beginner|start|new|first time)'
        ]
        
        self.nutrition_requests = [
            r'(diet|nutrition|food|eat|eating)',
            r'(protein|carbs|fat|calories)',
            r'(meal|breakfast|lunch|dinner)'
        ]
        
        self.progress_requests = [
            r'(progress|track|tracking|record)',
            r'(weight|loss|gain|measurement)',
            r'(goal|target|achievement)'
        ]
        
        self.motivation_quotes = [
            "The only bad workout is the one that didn't happen.",
            "Your body can stand almost anything. It's your mind you have to convince.",
            "Success starts with self-discipline.",
            "Don't stop when you're tired. Stop when you're done.",
            "The pain you feel today will be the strength you feel tomorrow.",
            "Fitness is not about being better than someone else. It's about being better than you used to be.",
            "A one hour workout is 4% of your day. No excuses.",
            "The hardest lift is lifting your butt off the couch."
        ]
    
    def get_response(self, user_message: str, user_id: str) -> str:
        """Generate appropriate response based on user input"""
        message_lower = user_message.lower()
        
        # Check for greetings
        if self._matches_patterns(message_lower, self.greeting_patterns):
            return self._get_greeting_response()
        
        # Check for workout requests
        if self._matches_patterns(message_lower, self.workout_requests):
            return self._get_workout_response(message_lower)
        
        # Check for nutrition requests
        if self._matches_patterns(message_lower, self.nutrition_requests):
            return self._get_nutrition_response(message_lower)
        
        # Check for progress requests
        if self._matches_patterns(message_lower, self.progress_requests):
            return self._get_progress_response(message_lower)
        
        # Check for motivation requests
        if any(word in message_lower for word in ['motivate', 'motivation', 'inspire', 'encourage']):
            return self._get_motivation_response()
        
        # Default response
        return self._get_default_response()
    
    def _matches_patterns(self, text: str, patterns: List[str]) -> bool:
        """Check if text matches any of the given patterns"""
        for pattern in patterns:
            if re.search(pattern, text):
                return True
        return False
    
    def _get_greeting_response(self) -> str:
        """Generate greeting response"""
        greetings = [
            "Hello! I'm your fitness coach bot. I'm here to help you with workout plans, exercise guidance, and health tracking. What would you like to know today?",
            "Hi there! Ready to start your fitness journey? I can help you create workout plans, track your progress, and provide health tips. What's your goal?",
            "Welcome! I'm excited to be your fitness coach. Whether you're a beginner or experienced, I'm here to support your fitness goals. How can I help you today?"
        ]
        return random.choice(greetings)
    
    def _get_workout_response(self, message: str) -> str:
        """Generate workout-related response"""
        if 'beginner' in message or 'start' in message or 'new' in message:
            return self._get_beginner_workout_advice()
        elif 'plan' in message or 'routine' in message:
            return self._get_workout_plan_advice()
        elif 'muscle' in message or 'strength' in message:
            return self._get_strength_training_advice()
        elif 'cardio' in message or 'endurance' in message:
            return self._get_cardio_advice()
        else:
            return self._get_general_workout_advice()
    
    def _get_beginner_workout_advice(self) -> str:
        """Provide advice for beginners"""
        return """Great decision to start your fitness journey! Here's a beginner-friendly approach:

🏋️ **Start with these basics:**
- **Frequency**: 3 days per week, with rest days in between
- **Duration**: 30-45 minutes per session
- **Focus**: Full body workouts to build a foundation

**Sample Beginner Routine:**
1. **Warm-up** (5-10 minutes): Light cardio and dynamic stretching
2. **Strength Training** (20-25 minutes):
   - Bodyweight squats: 2 sets of 10-12 reps
   - Push-ups (knee or regular): 2 sets of 8-10 reps
   - Plank: 2 sets of 20-30 seconds
   - Lunges: 2 sets of 8-10 reps per leg
3. **Cool-down** (5-10 minutes): Static stretching

**Important Tips:**
- Focus on proper form over heavy weights
- Listen to your body and don't push through pain
- Stay consistent and gradually increase intensity
- Consider consulting a certified trainer for personalized guidance

Would you like me to create a more detailed plan based on your specific goals?"""
    
    def _get_workout_plan_advice(self) -> str:
        """Provide workout planning advice"""
        return """I'll help you create an effective workout plan! To give you the best recommendations, I need to know:

📋 **Your Profile:**
- What's your fitness goal? (weight loss, muscle gain, endurance, general fitness)
- What's your current fitness level? (beginner, intermediate, advanced)
- How many days per week can you work out?
- Do you have access to a gym or prefer home workouts?
- Any equipment available?
- Any injuries or medical conditions?

**Popular Workout Plans I can help with:**
- **Weight Loss**: HIIT + Cardio + Strength training (4-5 days/week)
- **Muscle Gain**: Progressive strength training (4-6 days/week)
- **General Fitness**: Balanced routine (3-4 days/week)
- **Home Workouts**: Bodyweight and minimal equipment (3-5 days/week)

Once you share your details, I can create a personalized plan just for you! What's your primary fitness goal?"""
    
    def _get_strength_training_advice(self) -> str:
        """Provide strength training advice"""
        return """Strength training is excellent for building muscle and boosting metabolism! Here's what you need to know:

💪 **Key Principles:**
- **Progressive Overload**: Gradually increase weight, reps, or sets
- **Proper Form**: Quality over quantity always
- **Rest & Recovery**: Muscles grow during rest, not training
- **Consistency**: Regular training is crucial

**Effective Strength Training Split:**
- **Push Day**: Chest, shoulders, triceps
- **Pull Day**: Back, biceps
- **Leg Day**: Quads, hamstrings, glutes, calves
- **Rest/Active Recovery**: Light cardio or stretching

**Sample Exercises:**
- **Compound Movements**: Squats, deadlifts, bench press, overhead press
- **Isolation Exercises**: Bicep curls, tricep extensions, leg curls
- **Core Work**: Planks, Russian twists, leg raises

**Frequency**: 3-5 days per week with adequate rest between muscle groups

Need specific exercise recommendations or form tips?"""
    
    def _get_cardio_advice(self) -> str:
        """Provide cardio training advice"""
        return """Cardio is fantastic for heart health and endurance! Here's your guide:

🏃 **Types of Cardio:**
- **Steady-State**: Moderate intensity for 30-60 minutes
- **HIIT**: High-intensity intervals with rest periods
- **LISS**: Low-intensity steady-state for longer durations

**Effective Cardio Workouts:**
1. **HIIT Protocol** (20 minutes):
   - 30 seconds maximum effort
   - 90 seconds active recovery
   - Repeat 10-12 times

2. **Steady-State Options**:
   - Running/jogging: 30-45 minutes
   - Cycling: 45-60 minutes
   - Swimming: 30-45 minutes
   - Brisk walking: 45-60 minutes

**Frequency Guidelines:**
- **General Fitness**: 3-4 sessions per week
- **Weight Loss**: 4-6 sessions per week
- **Athletic Performance**: 5-7 sessions per week

**Tips for Success:**
- Mix different types to prevent boredom
- Monitor your heart rate zones
- Include warm-up and cool-down
- Stay hydrated throughout

What type of cardio interests you most?"""
    
    def _get_general_workout_advice(self) -> str:
        """Provide general workout advice"""
        return """Here are some essential workout tips for everyone:

🎯 **Workout Fundamentals:**
- **Warm-up**: Always start with 5-10 minutes of light activity
- **Progressive overload**: Gradually increase intensity over time
- **Rest days**: Allow 48 hours between intense sessions for same muscle groups
- **Listen to your body**: Pain vs. discomfort - know the difference

**Balanced Approach:**
- **Strength Training**: 2-4 days per week
- **Cardiovascular Exercise**: 3-5 days per week
- **Flexibility/Mobility**: Daily stretching or yoga

**Common Mistakes to Avoid:**
- Skipping warm-ups and cool-downs
- Using improper form to lift heavier
- Not getting enough rest and recovery
- Comparing your progress to others
- Neglecting nutrition and hydration

**Success Tips:**
- Set realistic, specific goals
- Track your progress consistently
- Find activities you enjoy
- Stay patient and consistent

What specific area would you like to focus on first?"""
    
    def _get_nutrition_response(self, message: str) -> str:
        """Generate nutrition-related response"""
        if 'protein' in message:
            return """**Protein for Fitness:**
- **Daily Needs**: 1.6-2.2g per kg bodyweight for active individuals
- **Best Sources**: Lean meats, fish, eggs, dairy, legumes, protein powder
- **Timing**: 20-30g within 30 minutes post-workout
- **Spread intake**: Every 3-4 hours throughout the day"""
        
        elif 'weight loss' in message or 'diet' in message:
            return """**Weight Loss Nutrition:**
- **Calorie Deficit**: 300-500 calories below maintenance
- **Macros**: 40% protein, 30% carbs, 30% fats (adjust as needed)
- **Focus**: Whole foods, high protein, fiber-rich foods
- **Hydration**: 2-3 liters water daily
- **Meal Timing**: 3 main meals + 1-2 snacks"""
        
        else:
            return """**Basic Nutrition Principles:**
- **Balanced Macros**: Protein, carbs, and healthy fats
- **Whole Foods**: Minimize processed foods
- **Hydration**: 2-3 liters water daily
- **Timing**: Fuel workouts, recover properly
- **Consistency**: Sustainable habits over perfection

Need specific meal planning advice?"""
    
    def _get_progress_response(self, message: str) -> str:
        """Generate progress tracking response"""
        return """**Tracking Your Fitness Progress:**

📊 **What to Track:**
- **Weight**: Weekly measurements (same time/day)
- **Body Measurements**: Monthly (waist, hips, chest, arms)
- **Progress Photos**: Monthly (front, side, back)
- **Performance**: Reps, weights, distances, times
- **How You Feel**: Energy levels, sleep quality

**Tools for Tracking:**
- Fitness apps and wearables
- Workout journal
- Body composition scales
- Progress photos

**Remember:**
- Progress isn't always linear
- Focus on trends, not daily fluctuations
- Celebrate non-scale victories
- Adjust goals as needed

What aspect of progress tracking would you like help with?"""
    
    def _get_motivation_response(self) -> str:
        """Generate motivational response"""
        quote = random.choice(self.motivation_quotes)
        return f"""💪 **Daily Motivation:**

*{quote}*

**Stay Motivated With These Tips:**
- Set specific, achievable goals
- Track your progress and celebrate wins
- Find a workout buddy or community
- Mix up your routine to prevent boredom
- Remember your "why" - your reason for starting
- Be patient with yourself
- Focus on how far you've come, not how far to go

You've got this! Every workout counts, every healthy choice matters. What's your next step toward your goal?"""
    
    def _get_default_response(self) -> str:
        """Generate default response for unrecognized input"""
        return """I'm here to help you with your fitness journey! I can assist you with:

🏋️ **Workout Plans & Routines**
- Beginner to advanced programs
- Home and gym workouts
- Strength training and cardio

🥗 **Nutrition Guidance**
- Meal planning tips
- Protein and macro advice
- Healthy eating strategies

📈 **Progress Tracking**
- Setting and monitoring goals
- Measuring improvements
- Staying motivated

💪 **Exercise Guidance**
- Proper form and technique
- Exercise variations
- Injury prevention

**Just ask me about:**
- "Create a beginner workout plan"
- "What should I eat for muscle gain?"
- "How do I track my progress?"
- "Give me some motivation"

What would you like to focus on today?"""
346 lines•13.3 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