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
/
instance
RSK World
fitness-coach-bot
Fitness Coach Bot - Python + Flask + SQLAlchemy + Workout Plans + Exercise Guidance + Health Tracking + AI Fitness Coach
instance
  • fitness_coach.db32 KB
RELEASE_NOTES.md__init__.pyfitness_coach.cpython-313.pycREADME.mdnutrition_ai.cpython-313.pycworkout_buddy_matcher.py
models/__init__.py
Raw Download
Find: Go to:
"""
Models Package for Fitness Coach Bot
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

from .fitness_models import db, User, WorkoutPlan, Exercise, Progress, HealthTip, WorkoutExercise

__all__ = ['db', 'User', 'WorkoutPlan', 'Exercise', 'Progress', 'HealthTip', 'WorkoutExercise']
13 linesโ€ข403 B
python
fitness_coach.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
README.md
Raw Download

README.md

# Fitness Coach Bot

**AI-powered fitness coaching chatbot for workout plans, exercise guidance, and health tracking**

---

## ๐Ÿ‹๏ธ Project Information

**Author:** RSK World (https://rskworld.in)
**Founded by:** Molla Samser
**Designer & Tester:** Rima Khatun
**Contact:** help@rskworld.in | +91 93305 39277
**Year:** 2026
**Category:** Custom Chatbots
**Difficulty:** Intermediate

---

## ๐Ÿ“‹ Project Description

Fitness Coach Bot is a comprehensive AI-powered chatbot that provides personalized fitness coaching, including workout plans, exercise guidance, progress tracking, and health tips. Perfect for fitness apps and health platforms, this bot serves as your personal AI fitness trainer available 24/7.

---

## โœจ Features

- ๐Ÿ‹๏ธ **Workout Plans**: Personalized workout routines for all fitness levels
- ๐Ÿƒ **Exercise Guidance**: Proper form instructions and technique tips
- ๐Ÿ“Š **Progress Tracking**: Monitor your fitness journey and achievements
- ๐Ÿ’ก **Health Tips**: Nutrition advice and wellness recommendations
- ๐ŸŽฏ **Goal Setting**: Set and achieve your fitness objectives
- ๐Ÿ’ฌ **Interactive Chat**: Natural conversation interface
- ๐Ÿ“ฑ **Responsive Design**: Works on all devices
- ๐ŸŽจ **Modern UI**: Beautiful and intuitive interface

---

## ๐Ÿ› ๏ธ Technologies Used

- **Backend**: Python 3.8+
- **Framework**: Flask
- **Database**: SQLite (with SQLAlchemy ORM)
- **Frontend**: HTML5, CSS3, JavaScript (ES6+)
- **UI Framework**: Bootstrap 5
- **Icons**: Font Awesome
- **AI**: Custom fitness coaching engine with pattern recognition

---

## ๐Ÿ“ฆ Installation & Setup

### Prerequisites

- Python 3.8 or higher
- pip (Python package manager)
- Git

### Step 1: Clone the Repository

```bash
git clone <repository-url>
cd fitness-coach-bot
```

### Step 2: Create Virtual Environment

```bash
# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
```

### Step 3: Install Dependencies

```bash
pip install -r requirements.txt
```

### Step 4: Initialize Database

```bash
python init_db.py
```

This will create the SQLite database and populate it with sample data including exercises, workout plans, and health tips.

### Step 5: Run the Application

```bash
python app.py
```

The application will be available at `http://localhost:5000`

---

## ๐Ÿ—๏ธ Project Structure

```
fitness-coach-bot/
โ”œโ”€โ”€ app.py # Main Flask application
โ”œโ”€โ”€ init_db.py # Database initialization script
โ”œโ”€โ”€ requirements.txt # Python dependencies
โ”œโ”€โ”€ README.md # Project documentation
โ”œโ”€โ”€ models/
โ”‚ โ””โ”€โ”€ fitness_models.py # Database models
โ”œโ”€โ”€ utils/
โ”‚ โ””โ”€โ”€ fitness_coach.py # AI coaching engine
โ”œโ”€โ”€ templates/
โ”‚ โ””โ”€โ”€ index.html # Main HTML template
โ”œโ”€โ”€ static/
โ”‚ โ”œโ”€โ”€ css/
โ”‚ โ”‚ โ””โ”€โ”€ style.css # Custom styles
โ”‚ โ””โ”€โ”€ js/
โ”‚ โ””โ”€โ”€ app.js # Frontend JavaScript
โ””โ”€โ”€ data/
โ””โ”€โ”€ fitness_coach.db # SQLite database (created after init)
```

---

## ๐ŸŽฏ Usage Guide

### Getting Started

1. **Open the Application**: Navigate to `http://localhost:5000` in your browser
2. **Set Up Your Profile**: Fill in your fitness goals and personal information
3. **Start Chatting**: Ask the bot about workouts, nutrition, or fitness advice

### Sample Conversations

**Workout Plans:**
```
You: Create a beginner workout plan
Bot: Great decision to start your fitness journey! Here's a beginner-friendly approach...
```

**Nutrition Advice:**
```
You: What should I eat for muscle gain?
Bot: Protein for Fitness: Daily Needs: 1.6-2.2g per kg bodyweight...
```

**Progress Tracking:**
```
You: How do I track my fitness progress?
Bot: Tracking Your Fitness Progress: What to Track: Weight, Body Measurements...
```

### Features Explained

#### Chat Interface
- **Natural Conversation**: Chat with the AI coach like talking to a real trainer
- **Quick Suggestions**: Use preset buttons for common questions
- **Real-time Responses**: Get instant fitness advice and guidance

#### User Profile
- **Personal Information**: Age, weight, height
- **Fitness Goals**: Weight loss, muscle gain, endurance, etc.
- **Activity Level**: From sedentary to very active

#### Progress Tracking
- **Workout Count**: Total number of workouts completed
- **Streak Counter**: Consecutive days of activity
- **Calories Burned**: Estimated calories burned
- **Goals Met**: Number of fitness goals achieved

#### Health Tips
- **Randomized Tips**: Get fresh health advice with each refresh
- **Categories**: Nutrition, exercise, recovery, motivation, safety
- **Expert Advice**: Tips from fitness professionals

---

## ๐Ÿ”ง Customization

### Adding New Exercises

```python
# In init_db.py or via admin interface
new_exercise = Exercise(
name="Exercise Name",
description="Exercise description",
category="strength",
muscle_group="target_muscle",
equipment="required_equipment",
difficulty="beginner",
instructions="Step-by-step instructions",
tips="Helpful tips for proper form"
)
db.session.add(new_exercise)
db.session.commit()
```

### Modifying AI Responses

Edit the `utils/fitness_coach.py` file to customize:
- Response patterns
- Exercise recommendations
- Nutrition advice
- Motivational messages

### Styling Changes

Modify `static/css/style.css` to:
- Change color schemes
- Adjust layouts
- Add animations
- Responsive design tweaks

---

## ๐Ÿ”Œ API Endpoints

### Chat API
```
POST /api/chat
Content-Type: application/json

{
"message": "Your fitness question here"
}

Response:
{
"success": true,
"response": "AI coach response",
"timestamp": "2026-01-10T21:48:00"
}
```

### Workout Plans API
```
GET /api/workout-plans

Response:
{
"success": true,
"plans": [...]
}
```

### User Profile API
```
GET /api/user/profile
POST /api/user/profile

Content-Type: application/json
{
"name": "John Doe",
"age": 30,
"weight": 70,
"fitness_goal": "muscle_gain"
}
```

---

## ๐Ÿงช Testing

### Running Tests

```bash
# Install test dependencies
pip install pytest pytest-flask

# Run tests
pytest tests/
```

### Manual Testing

1. **Chat Functionality**: Test various user inputs and responses
2. **Profile Management**: Test saving and loading user profiles
3. **Progress Tracking**: Verify stats updates
4. **Responsive Design**: Test on different screen sizes

---

## ๐Ÿš€ Deployment

### Production Deployment

1. **Set Environment Variables**:
```bash
export FLASK_ENV=production
export SECRET_KEY=your-secret-key
```

2. **Use Gunicorn**:
```bash
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 app:app
```

3. **Database Setup**: Ensure proper database configuration for production

### Docker Deployment

```dockerfile
FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
EXPOSE 5000

CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]
```

---

## ๐Ÿค Contributing

We welcome contributions! Please follow these steps:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

---

## ๐Ÿ“„ License

This project is part of RSK World's free programming resources. Content used for educational purposes only.

---

## ๐Ÿ“ž Support & Contact

**RSK World**
- **Email**: help@rskworld.in
- **Phone**: +91 93305 39277
- **Website**: https://rskworld.in
- **Address**: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

---

## ๐Ÿ™ Acknowledgments

- **Molla Samser** - Founder & Developer
- **Rima Khatun** - Designer & Tester
- **RSK World Community** - For continuous support and feedback

---

## ๐Ÿ“ˆ Future Enhancements

- [ ] Integration with fitness wearables
- [ ] Video exercise demonstrations
- [ ] Mobile app version
- [ ] Social features and community
- [ ] Advanced analytics and insights
- [ ] Multi-language support
- [ ] Voice interaction capabilities

---

**ยฉ 2026 RSK World. All rights reserved.**
nutrition_ai.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
utils/workout_buddy_matcher.py
Raw Download
Find: Go to:
"""
Workout Buddy Matching System
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass

@dataclass
class WorkoutBuddy:
    user_id: str
    name: str
    fitness_level: str
    goals: List[str]
    preferred_workout_time: str
    location: Optional[str] = None
    preferred_activities: List[str] = None
    availability: Dict = None
    compatibility_score: float = 0.0

class WorkoutBuddyMatcher:
    """AI-powered workout buddy matching system"""
    
    def __init__(self):
        self.buddy_profiles = {}
        self.active_matches = {}
        
    def create_buddy_profile(self, user_data: Dict) -> Dict:
        """Create or update buddy matching profile"""
        profile = WorkoutBuddy(
            user_id=user_data.get('user_id'),
            name=user_data.get('name', 'User'),
            fitness_level=user_data.get('fitness_level', 'beginner'),
            goals=user_data.get('goals', []),
            preferred_workout_time=user_data.get('preferred_workout_time', 'morning'),
            location=user_data.get('location'),
            preferred_activities=user_data.get('preferred_activities', []),
            availability=user_data.get('availability', {})
        )
        
        self.buddy_profiles[profile.user_id] = profile
        
        return {
            'success': True,
            'profile': self._profile_to_dict(profile),
            'message': 'Buddy profile created successfully'
        }
    
    def find_matches(self, user_id: str, limit: int = 5) -> List[Dict]:
        """Find compatible workout buddies"""
        if user_id not in self.buddy_profiles:
            return []
        
        user_profile = self.buddy_profiles[user_id]
        matches = []
        
        for buddy_id, buddy_profile in self.buddy_profiles.items():
            if buddy_id == user_id:
                continue
            
            # Calculate compatibility score
            score = self._calculate_compatibility(user_profile, buddy_profile)
            
            if score > 0.5:  # Minimum compatibility threshold
                buddy_profile.compatibility_score = score
                matches.append({
                    'buddy': self._profile_to_dict(buddy_profile),
                    'compatibility_score': round(score * 100, 1),
                    'match_reasons': self._get_match_reasons(user_profile, buddy_profile)
                })
        
        # Sort by compatibility score
        matches.sort(key=lambda x: x['compatibility_score'], reverse=True)
        
        return matches[:limit]
    
    def _calculate_compatibility(self, user: WorkoutBuddy, buddy: WorkoutBuddy) -> float:
        """Calculate compatibility score between two users"""
        score = 0.0
        factors = 0
        
        # Fitness level compatibility (0.3 weight)
        level_match = self._match_fitness_level(user.fitness_level, buddy.fitness_level)
        score += level_match * 0.3
        factors += 0.3
        
        # Goals compatibility (0.25 weight)
        goals_match = self._match_goals(user.goals, buddy.goals)
        score += goals_match * 0.25
        factors += 0.25
        
        # Workout time compatibility (0.2 weight)
        time_match = 1.0 if user.preferred_workout_time == buddy.preferred_workout_time else 0.5
        score += time_match * 0.2
        factors += 0.2
        
        # Activity preferences (0.15 weight)
        activity_match = self._match_activities(user.preferred_activities, buddy.preferred_activities)
        score += activity_match * 0.15
        factors += 0.15
        
        # Location proximity (0.1 weight) - if both have location
        if user.location and buddy.location:
            location_match = self._calculate_location_proximity(user.location, buddy.location)
            score += location_match * 0.1
            factors += 0.1
        
        # Normalize score
        return score / factors if factors > 0 else 0.0
    
    def _match_fitness_level(self, level1: str, level2: str) -> float:
        """Match fitness levels"""
        levels = {'beginner': 1, 'intermediate': 2, 'advanced': 3}
        level1_num = levels.get(level1.lower(), 2)
        level2_num = levels.get(level2.lower(), 2)
        
        diff = abs(level1_num - level2_num)
        if diff == 0:
            return 1.0
        elif diff == 1:
            return 0.7  # Adjacent levels are somewhat compatible
        else:
            return 0.3  # Too far apart
    
    def _match_goals(self, goals1: List[str], goals2: List[str]) -> float:
        """Match fitness goals"""
        if not goals1 or not goals2:
            return 0.5  # Neutral if no goals specified
        
        common_goals = set(g.lower() for g in goals1) & set(g.lower() for g in goals2)
        all_goals = set(g.lower() for g in goals1) | set(g.lower() for g in goals2)
        
        if not all_goals:
            return 0.5
        
        return len(common_goals) / len(all_goals)
    
    def _match_activities(self, activities1: List[str], activities2: List[str]) -> float:
        """Match preferred activities"""
        if not activities1 or not activities2:
            return 0.5
        
        common = set(a.lower() for a in activities1) & set(a.lower() for a in activities2)
        total = len(set(a.lower() for a in activities1) | set(a.lower() for a in activities2))
        
        if total == 0:
            return 0.5
        
        return len(common) / total
    
    def _calculate_location_proximity(self, loc1: str, loc2: str) -> float:
        """Calculate location proximity (simplified)"""
        # In real implementation, would use geocoding API
        # For now, simple string matching
        if loc1.lower() == loc2.lower():
            return 1.0
        
        # Check if same city (simple check)
        loc1_parts = loc1.lower().split(',')
        loc2_parts = loc2.lower().split(',')
        
        if len(loc1_parts) > 0 and len(loc2_parts) > 0:
            if loc1_parts[0] == loc2_parts[0]:
                return 0.7  # Same city
        
        return 0.3  # Different locations
    
    def _get_match_reasons(self, user: WorkoutBuddy, buddy: WorkoutBuddy) -> List[str]:
        """Get reasons why users are matched"""
        reasons = []
        
        if user.fitness_level == buddy.fitness_level:
            reasons.append(f"Same fitness level: {user.fitness_level}")
        
        common_goals = set(g.lower() for g in user.goals) & set(g.lower() for g in buddy.goals)
        if common_goals:
            reasons.append(f"Shared goals: {', '.join(list(common_goals)[:2])}")
        
        if user.preferred_workout_time == buddy.preferred_workout_time:
            reasons.append(f"Same workout time preference: {user.preferred_workout_time}")
        
        common_activities = set(a.lower() for a in user.preferred_activities or []) & \
                           set(a.lower() for a in buddy.preferred_activities or [])
        if common_activities:
            reasons.append(f"Similar interests: {', '.join(list(common_activities)[:2])}")
        
        return reasons if reasons else ["Potential workout buddy"]
    
    def create_buddy_request(self, from_user_id: str, to_user_id: str, message: Optional[str] = None) -> Dict:
        """Send workout buddy request"""
        request = {
            'id': f"buddy_req_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{from_user_id}",
            'from_user_id': from_user_id,
            'to_user_id': to_user_id,
            'message': message or "Would you like to be workout buddies?",
            'status': 'pending',
            'created_at': datetime.now().isoformat()
        }
        
        return {
            'success': True,
            'request': request,
            'message': 'Buddy request sent successfully'
        }
    
    def accept_buddy_request(self, request_id: str) -> Dict:
        """Accept buddy request"""
        return {
            'success': True,
            'message': 'Buddy request accepted! You are now workout buddies.',
            'match': {
                'created_at': datetime.now().isoformat(),
                'status': 'active'
            }
        }
    
    def suggest_group_workout(self, user_ids: List[str], workout_data: Dict) -> Dict:
        """Suggest group workout for matched buddies"""
        return {
            'success': True,
            'suggestion': {
                'workout_type': workout_data.get('type', 'group_training'),
                'suggested_time': workout_data.get('time'),
                'participants': user_ids,
                'message': 'Group workout suggestion created',
                'created_at': datetime.now().isoformat()
            }
        }
    
    def _profile_to_dict(self, profile: WorkoutBuddy) -> Dict:
        """Convert profile to dictionary"""
        return {
            'user_id': profile.user_id,
            'name': profile.name,
            'fitness_level': profile.fitness_level,
            'goals': profile.goals,
            'preferred_workout_time': profile.preferred_workout_time,
            'location': profile.location,
            'preferred_activities': profile.preferred_activities or [],
            'availability': profile.availability or {}
        }
248 linesโ€ข9.5 KB
python
๐Ÿš€ Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work โค๏ธ

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