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
RSK World
fitness-coach-bot
Fitness Coach Bot - Python + Flask + SQLAlchemy + Workout Plans + Exercise Guidance + Health Tracking + AI Fitness Coach
fitness-coach-bot
  • __pycache__
  • data
  • instance
  • models
  • static
  • templates
  • utils
  • .gitignore564 B
  • ADVANCED_FEATURES.md7.1 KB
  • HOW_TO_CREATE_RELEASE.md4.1 KB
  • LICENSE1.1 KB
  • PROJECT_CHECK_SUMMARY.md5.5 KB
  • README.md8.5 KB
  • RELEASE_NOTES_v1.0.0.md6.9 KB
  • app.py16.5 KB
  • config.py1.5 KB
  • demo_data.py2.5 KB
  • init_db.py12.7 KB
  • requirements.txt442 B
RELEASE_NOTES.mdHOW_TO_CREATE_RELEASE.mdanalytics_dashboard.jsfitness_coach.cpython-313.pycapp.py
HOW_TO_CREATE_RELEASE.md
Raw Download

HOW_TO_CREATE_RELEASE.md

# How to Create GitHub Release v1.0.0

## ✅ Completed Steps

1. ✅ **Git Repository Initialized**
2. ✅ **All Files Committed** (30 files, 9519+ lines)
3. ✅ **Pushed to GitHub** (https://github.com/rskworld/fitness-coach-bot.git)
4. ✅ **Tag Created** (v1.0.0)
5. ✅ **Tag Pushed** to GitHub
6. ✅ **Release Notes Created** (RELEASE_NOTES_v1.0.0.md)

## 📝 Create GitHub Release (Manual Steps)

Since GitHub CLI is not installed, follow these steps to create a release on GitHub:

### Step 1: Go to GitHub Repository
1. Open your browser and navigate to:
```
https://github.com/rskworld/fitness-coach-bot
```

### Step 2: Navigate to Releases
1. Click on the **"Releases"** link on the right sidebar (or go to: https://github.com/rskworld/fitness-coach-bot/releases)
2. Click **"Create a new release"** button

### Step 3: Fill Release Details
1. **Choose a tag**: Select `v1.0.0` from the dropdown (it should already exist)
2. **Release title**: `Version 1.0.0 - Initial Release`
3. **Description**: Copy and paste the content from `RELEASE_NOTES_v1.0.0.md` file, or use this:

```
# Version 1.0.0 - Initial Release

## 🎉 Initial Release

This is the first official release of the Fitness Coach Bot - an AI-powered comprehensive fitness coaching chatbot application.

## ✨ Features

### Core Features
- **AI-Powered Chatbot**: Intelligent fitness coaching chatbot
- **Personalized Workout Generation**: AI-driven workout plans
- **Nutrition Analysis**: Food image analysis and meal planning
- **Progress Tracking**: Comprehensive workout tracking
- **User Profiles**: Detailed profile management

### Advanced Features
- **Social Features**: Fitness challenges, teams, progress sharing
- **Gamification System**: Achievements, levels, badges, leaderboards
- **Advanced Analytics**: Detailed fitness analytics with trends
- **Wearable Integration**: Support for Fitbit, Apple Watch, Garmin
- **Voice Coaching**: Voice command processing
- **Pose Detection**: Real-time exercise form analysis
- **Smart Recovery**: Recovery score calculation
- **Workout Buddy Matching**: Find compatible workout partners

## 🛠️ Technical Stack

- Flask 2.3.3, Python 3.13
- SQLAlchemy 2.0.45, SQLite
- Bootstrap 5, Vanilla JavaScript, Chart.js
- 20+ REST API endpoints

## 📦 Installation

1. Clone the repository:
```bash
git clone https://github.com/rskworld/fitness-coach-bot.git
cd fitness-coach-bot
```

2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. Initialize database:
```bash
python init_db.py
```

4. Run the application:
```bash
python app.py
```

## 🐛 Fixed Issues

- ✅ Fixed SQLAlchemy compatibility with Python 3.13
- ✅ Updated all dependencies
- ✅ Fixed datetime timezone issues
- ✅ Verified all imports and syntax

## 👥 Credits

**Author:** RSK World (https://rskworld.in)
**Founder:** Molla Samser
**Designer & Tester:** Rima Khatun
**Contact:** help@rskworld.in, +91 93305 39277
**Year:** 2026
```

4. **Set as latest release**: Check the box if available
5. **Set as pre-release**: Leave unchecked (this is a stable release)

### Step 4: Publish Release
1. Click the **"Publish release"** button
2. Your release will be created and visible on the releases page

---

## 🔄 Alternative: Use GitHub CLI (If Installed)

If you install GitHub CLI in the future, you can create releases using:

```bash
gh release create v1.0.0 \
--title "Version 1.0.0 - Initial Release" \
--notes-file RELEASE_NOTES_v1.0.0.md
```

---

## 📋 Summary

✅ **Repository**: https://github.com/rskworld/fitness-coach-bot
✅ **Branch**: main
✅ **Tag**: v1.0.0 (already pushed)
✅ **Release Notes**: RELEASE_NOTES_v1.0.0.md (in repository)
⏳ **GitHub Release**: Need to create manually via web interface (see steps above)

---

## 🎯 Next Steps After Creating Release

1. Verify the release is visible on GitHub
2. Share the release link with your team
3. Update project documentation if needed
4. Consider setting up automated releases for future versions
static/js/analytics_dashboard.js
Raw Download
Find: Go to:
/**
 * Advanced Analytics Dashboard with Visualizations
 * Author: RSK World (https://rskworld.in)
 * Founded by: Molla Samser
 * Designer & Tester: Rima Khatun
 * Contact: help@rskworld.in, +91 93305 39277
 * Year: 2026
 */

class AnalyticsDashboard {
    constructor() {
        this.charts = {};
        this.data = {};
        this.init();
    }

    async init() {
        await this.loadChartsLibrary();
        this.loadAnalyticsData();
        this.setupEventListeners();
    }

    async loadChartsLibrary() {
        // Load Chart.js
        if (typeof Chart === 'undefined') {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js';
            document.head.appendChild(script);
            await new Promise(resolve => script.onload = resolve);
        }
    }

    async loadAnalyticsData() {
        try {
            const response = await fetch('/api/analytics?timeframe=30');
            const data = await response.json();
            
            if (data.success) {
                this.data = data.analytics;
                this.renderAllCharts();
            }
        } catch (error) {
            console.error('Error loading analytics:', error);
        }
    }

    renderAllCharts() {
        this.renderWorkoutFrequencyChart();
        this.renderProgressChart();
        this.renderStrengthChart();
        this.renderNutritionChart();
        this.renderRecoveryChart();
        this.renderRadarChart();
    }

    renderWorkoutFrequencyChart() {
        const ctx = document.getElementById('workoutFrequencyChart');
        if (!ctx) return;

        const categories = this.data.categories || {};
        const workout = categories.workout || {};

        this.charts.workoutFrequency = new Chart(ctx, {
            type: 'line',
            data: {
                labels: this.generateDateLabels(30),
                datasets: [{
                    label: 'Workouts per Week',
                    data: this.generateWorkoutData(),
                    borderColor: 'rgb(75, 192, 192)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Workout Frequency Trend'
                    },
                    legend: {
                        display: true
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }

    renderProgressChart() {
        const ctx = document.getElementById('progressChart');
        if (!ctx) return;

        const body = this.data.categories?.body || {};
        const metrics = body.body_metrics || {};

        this.charts.progress = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Weight', 'Body Fat %', 'Muscle Mass'],
                datasets: [{
                    label: 'Current',
                    data: [
                        metrics.weight?.current || 0,
                        metrics.body_fat?.current || 0,
                        metrics.muscle_mass?.current || 0
                    ],
                    backgroundColor: [
                        'rgba(54, 162, 235, 0.8)',
                        'rgba(255, 99, 132, 0.8)',
                        'rgba(75, 192, 192, 0.8)'
                    ]
                }, {
                    label: 'Start',
                    data: [
                        metrics.weight?.start || 0,
                        metrics.body_fat?.start || 0,
                        metrics.muscle_mass?.start || 0
                    ],
                    backgroundColor: [
                        'rgba(54, 162, 235, 0.4)',
                        'rgba(255, 99, 132, 0.4)',
                        'rgba(75, 192, 192, 0.4)'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Body Composition Progress'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    renderStrengthChart() {
        const ctx = document.getElementById('strengthChart');
        if (!ctx) return;

        const strength = this.data.categories?.strength || {};
        const exercises = strength.strength_exercises || {};

        const exerciseNames = Object.keys(exercises);
        const improvements = exerciseNames.map(name => exercises[name].improvement || 0);

        this.charts.strength = new Chart(ctx, {
            type: 'line',
            data: {
                labels: exerciseNames.map(name => name.replace('_', ' ').toUpperCase()),
                datasets: [{
                    label: 'Strength Improvement %',
                    data: improvements,
                    borderColor: 'rgb(255, 99, 132)',
                    backgroundColor: 'rgba(255, 99, 132, 0.2)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Strength Progress by Exercise'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        });
    }

    renderNutritionChart() {
        const ctx = document.getElementById('nutritionChart');
        if (!ctx) return;

        const nutrition = this.data.categories?.nutrition || {};
        const macros = nutrition.macro_distribution || {};

        this.charts.nutrition = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['Protein', 'Carbs', 'Fats'],
                datasets: [{
                    data: [
                        macros.protein || 0,
                        macros.carbs || 0,
                        macros.fat || 0
                    ],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.8)',
                        'rgba(54, 162, 235, 0.8)',
                        'rgba(255, 206, 86, 0.8)'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Macronutrient Distribution'
                    },
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }

    renderRecoveryChart() {
        const ctx = document.getElementById('recoveryChart');
        if (!ctx) return;

        const recovery = this.data.categories?.recovery || {};
        const sleep = recovery.sleep_data || {};

        this.charts.recovery = new Chart(ctx, {
            type: 'radar',
            data: {
                labels: ['Sleep Duration', 'Sleep Quality', 'Consistency', 'Recovery Score'],
                datasets: [{
                    label: 'Recovery Metrics',
                    data: [
                        (sleep.avg_duration || 0) * 10, // Scale to 0-100
                        sleep.avg_quality || 0,
                        sleep.consistency || 0,
                        recovery.recovery_score || 0
                    ],
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgb(75, 192, 192)',
                    pointBackgroundColor: 'rgb(75, 192, 192)'
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Recovery Overview'
                    }
                },
                scales: {
                    r: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });
    }

    renderRadarChart() {
        const ctx = document.getElementById('overallRadarChart');
        if (!ctx) return;

        const categories = this.data.categories || {};

        this.charts.overall = new Chart(ctx, {
            type: 'radar',
            data: {
                labels: ['Workout', 'Strength', 'Cardio', 'Nutrition', 'Recovery', 'Body'],
                datasets: [{
                    label: 'Overall Fitness Score',
                    data: [
                        categories.workout?.score || 0,
                        categories.strength?.score || 0,
                        categories.cardio?.score || 0,
                        categories.nutrition?.score || 0,
                        categories.recovery?.score || 0,
                        categories.body?.score || 0
                    ],
                    backgroundColor: 'rgba(153, 102, 255, 0.2)',
                    borderColor: 'rgb(153, 102, 255)',
                    pointBackgroundColor: 'rgb(153, 102, 255)'
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Overall Fitness Profile'
                    }
                },
                scales: {
                    r: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });
    }

    generateDateLabels(days) {
        const labels = [];
        const today = new Date();
        for (let i = days - 1; i >= 0; i--) {
            const date = new Date(today);
            date.setDate(date.getDate() - i);
            labels.push(date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
        }
        return labels;
    }

    generateWorkoutData() {
        // Generate sample data - in real app, would come from backend
        const data = [];
        for (let i = 0; i < 30; i++) {
            data.push(Math.floor(Math.random() * 7) + 1);
        }
        return data;
    }

    setupEventListeners() {
        const timeframeSelect = document.getElementById('timeframeSelect');
        if (timeframeSelect) {
            timeframeSelect.addEventListener('change', (e) => {
                this.loadAnalyticsData(e.target.value);
            });
        }
    }

    exportReport() {
        // Export analytics report as PDF/image
        window.print();
    }
}

// Initialize dashboard when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('analyticsDashboard')) {
        window.analyticsDashboard = new AnalyticsDashboard();
    }
});
363 lines•11.7 KB
javascript
fitness_coach.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
app.py
Raw Download
Find: Go to:
"""
Fitness Coach Bot - A comprehensive fitness coaching chatbot
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
Description: Fitness chatbot for workout plans, exercise guidance, and health tracking
"""

from flask import Flask, render_template, request, jsonify, session
from datetime import datetime
import json
import os
import asyncio
from models.fitness_models import db, User, WorkoutPlan, Exercise, Progress, HealthTip
from utils.fitness_coach import FitnessCoach
from utils.ai_workout_generator import AIWorkoutGenerator
from utils.nutrition_ai import NutritionAI
from utils.social_features import SocialFeatures
from utils.analytics_engine import AdvancedAnalytics
from utils.gamification_system import GamificationSystem
from utils.wearable_integration import WearableIntegration, DeviceType
from utils.voice_coach import VoiceCoach
from utils.workout_buddy_matcher import WorkoutBuddyMatcher
from utils.smart_recovery import SmartRecovery

app = Flask(__name__)
app.config['SECRET_KEY'] = 'fitness-coach-bot-2026-rskworld'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///fitness_coach.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Initialize db with app
db.init_app(app)
fitness_coach = FitnessCoach()
ai_workout_generator = AIWorkoutGenerator()
nutrition_ai = NutritionAI()
social_features = SocialFeatures()
analytics_engine = AdvancedAnalytics()
gamification_system = GamificationSystem()
wearable_integration = WearableIntegration()
voice_coach = VoiceCoach()
buddy_matcher = WorkoutBuddyMatcher()
smart_recovery = SmartRecovery()

@app.route('/')
def index():
    """Main chatbot interface"""
    return render_template('index.html')

@app.route('/api/chat', methods=['POST'])
def chat():
    """Handle chat messages and provide fitness coaching responses"""
    try:
        data = request.get_json()
        user_message = data.get('message', '')
        user_id = session.get('user_id', 'anonymous')
        
        # Get AI response
        response = fitness_coach.get_response(user_message, user_id)
        
        return jsonify({
            'success': True,
            'response': response,
            'timestamp': datetime.now().isoformat()
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/workout-plans', methods=['GET'])
def get_workout_plans():
    """Get available workout plans"""
    try:
        plans = WorkoutPlan.query.all()
        return jsonify({
            'success': True,
            'plans': [plan.to_dict() for plan in plans]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/exercises', methods=['GET'])
def get_exercises():
    """Get exercises by category or muscle group"""
    try:
        category = request.args.get('category')
        muscle_group = request.args.get('muscle_group')
        
        query = Exercise.query
        if category:
            query = query.filter_by(category=category)
        if muscle_group:
            query = query.filter_by(muscle_group=muscle_group)
            
        exercises = query.all()
        return jsonify({
            'success': True,
            'exercises': [exercise.to_dict() for exercise in exercises]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/progress', methods=['POST'])
def save_progress():
    """Save user workout progress"""
    try:
        data = request.get_json()
        user_id = session.get('user_id', 'anonymous')
        
        progress = Progress(
            user_id=user_id,
            exercise_id=data.get('exercise_id'),
            sets_completed=data.get('sets_completed'),
            reps_completed=data.get('reps_completed'),
            weight_used=data.get('weight', data.get('weight_used')),
            notes=data.get('notes', ''),
            date=datetime.now()
        )
        
        db.session.add(progress)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Progress saved successfully'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/health-tips', methods=['GET'])
def get_health_tips():
    """Get health and fitness tips"""
    try:
        tips = HealthTip.query.order_by(db.func.random()).limit(5).all()
        return jsonify({
            'success': True,
            'tips': [tip.to_dict() for tip in tips]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/user/profile', methods=['GET', 'POST'])
def user_profile():
    """Get or update user profile"""
    if request.method == 'GET':
        try:
            user_id = session.get('user_id')
            if user_id:
                user = User.query.get(user_id)
                if user:
                    return jsonify({
                        'success': True,
                        'user': user.to_dict()
                    })
            return jsonify({
                'success': False,
                'message': 'User not found'
            })
        except Exception as e:
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500
    
    elif request.method == 'POST':
        try:
            data = request.get_json()
            user_id = session.get('user_id', 'anonymous')
            
            user = User.query.get(user_id)
            if not user:
                user = User(id=user_id)
                db.session.add(user)
            
            user.name = data.get('name', user.name)
            user.age = data.get('age', user.age)
            user.weight = data.get('weight', user.weight)
            user.height = data.get('height', user.height)
            user.fitness_goal = data.get('fitness_goal', user.fitness_goal)
            user.activity_level = data.get('activity_level', user.activity_level)
            
            db.session.commit()
            
            return jsonify({
                'success': True,
                'message': 'Profile updated successfully',
                'user': user.to_dict()
            })
        except Exception as e:
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500

# Advanced Features API Endpoints

@app.route('/api/ai-workout', methods=['POST'])
def generate_ai_workout():
    """Generate AI-powered personalized workout"""
    try:
        data = request.get_json()
        user_profile = data.get('user_profile', {})
        preferences = data.get('preferences', {})
        
        workout = ai_workout_generator.generate_personalized_workout(user_profile, preferences)
        
        return jsonify({
            'success': True,
            'workout': workout
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/nutrition-analyze', methods=['POST'])
def analyze_nutrition():
    """Analyze nutrition from food image"""
    try:
        data = request.get_json()
        image_data = data.get('image_data', '')
        user_profile = data.get('user_profile', {})
        
        # Run async function in sync context
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            analysis = loop.run_until_complete(nutrition_ai.analyze_food_image(image_data, user_profile))
        finally:
            loop.close()
        
        return jsonify({
            'success': True,
            'analysis': analysis
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/social-challenge', methods=['POST'])
def create_challenge():
    """Create social fitness challenge"""
    try:
        data = request.get_json()
        challenge_data = data.get('challenge', {})
        
        challenge = social_features.create_challenge(challenge_data)
        
        return jsonify({
            'success': True,
            'challenge': challenge
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/analytics', methods=['GET'])
def get_analytics():
    """Get comprehensive analytics dashboard"""
    try:
        user_id = session.get('user_id', 'anonymous')
        timeframe = request.args.get('timeframe', 30)
        
        analytics = analytics_engine.calculate_comprehensive_analytics(user_id, timeframe)
        
        return jsonify({
            'success': True,
            'analytics': analytics
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/gamification/profile', methods=['GET'])
def get_gamification_profile():
    """Get user gamification profile"""
    try:
        user_id = session.get('user_id', 'anonymous')
        profile = gamification_system.get_user_stats_summary(user_id)
        
        return jsonify({
            'success': True,
            'profile': profile
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/wearable/connect', methods=['POST'])
def connect_wearable():
    """Connect wearable device"""
    try:
        data = request.get_json()
        device_type_str = data.get('device_type')
        user_id = session.get('user_id', 'anonymous')
        auth_data = data.get('auth_data', {})
        
        # Convert string to DeviceType enum
        try:
            device_type = DeviceType(device_type_str)
        except (ValueError, TypeError):
            return jsonify({
                'success': False,
                'error': f'Invalid device type: {device_type_str}'
            }), 400
        
        # Run async function in sync context
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(wearable_integration.connect_device(device_type, user_id, auth_data))
        finally:
            loop.close()
        
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/wearable/sync/<device_id>', methods=['POST'])
def sync_wearable(device_id):
    """Sync data from wearable device"""
    try:
        # Run async function in sync context
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(wearable_integration.sync_device_data(device_id))
        finally:
            loop.close()
        
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

# Advanced Features API Endpoints

@app.route('/api/voice/command', methods=['POST'])
def voice_command():
    """Process voice command"""
    try:
        data = request.get_json()
        transcript = data.get('transcript', '')
        
        result = voice_coach.process_voice_command(transcript)
        
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/voice/workout-guidance', methods=['POST'])
def workout_guidance():
    """Get voice guidance for workout"""
    try:
        data = request.get_json()
        exercise_name = data.get('exercise_name')
        set_number = data.get('set_number', 1)
        
        guidance = voice_coach.generate_workout_guidance(exercise_name, set_number)
        
        return jsonify(guidance)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/buddy/profile', methods=['GET', 'POST'])
def buddy_profile():
    """Get or create workout buddy profile"""
    try:
        if request.method == 'POST':
            data = request.get_json()
            data['user_id'] = session.get('user_id', 'anonymous')
            result = buddy_matcher.create_buddy_profile(data)
            return jsonify(result)
        else:
            user_id = session.get('user_id', 'anonymous')
            matches = buddy_matcher.find_matches(user_id)
            return jsonify({
                'success': True,
                'matches': matches
            })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/buddy/find-matches', methods=['GET'])
def find_buddies():
    """Find workout buddy matches"""
    try:
        user_id = session.get('user_id', 'anonymous')
        limit = request.args.get('limit', 5, type=int)
        
        matches = buddy_matcher.find_matches(user_id, limit)
        
        return jsonify({
            'success': True,
            'matches': matches
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/buddy/request', methods=['POST'])
def send_buddy_request():
    """Send workout buddy request"""
    try:
        data = request.get_json()
        from_user_id = session.get('user_id', 'anonymous')
        to_user_id = data.get('to_user_id')
        message = data.get('message')
        
        result = buddy_matcher.create_buddy_request(from_user_id, to_user_id, message)
        
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/recovery/calculate', methods=['POST'])
def calculate_recovery():
    """Calculate recovery score and recommendations"""
    try:
        data = request.get_json()
        
        result = smart_recovery.calculate_recovery_score(data)
        
        return jsonify({
            'success': True,
            'recovery': result
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/recovery/activities', methods=['GET'])
def recovery_activities():
    """Get suggested recovery activities"""
    try:
        status = request.args.get('status', 'good')
        
        activities = smart_recovery.suggest_recovery_activities(status)
        
        return jsonify({
            'success': True,
            'activities': activities
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/pose-workout', methods=['POST'])
def save_pose_workout():
    """Save pose detection workout data"""
    try:
        data = request.get_json()
        user_id = session.get('user_id', 'anonymous')
        
        # Save to database
        progress = Progress(
            user_id=user_id,
            exercise_id=data.get('exercise_id', 1),
            sets_completed=1,
            reps_completed=data.get('reps', 0),
            weight_used=0,
            duration_seconds=data.get('duration', 0) // 1000,
            calories_burned=data.get('calories_burned', 0),
            notes=f"Pose detection workout - Form Score: {data.get('avgFormScore', 0)}%",
            date=datetime.now()
        )
        
        db.session.add(progress)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Workout saved successfully'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True, host='0.0.0.0', port=5000)
532 lines•16.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