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
config.cpython-313.pycinit_db.pyanalytics_engine.py.gitignoreapp.py__init__.pysocial_features.cpython-313.pycHOW_TO_CREATE_RELEASE.md
config.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
init_db.py
Raw Download
Find: Go to:
"""
Fitness Coach Bot - Database Initialization Script
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import app, db
from models.fitness_models import User, WorkoutPlan, Exercise, WorkoutExercise, HealthTip
from datetime import datetime

def init_database():
    """Initialize the database with sample data"""
    with app.app_context():
        # Create all tables
        db.create_all()
        print("Database tables created successfully!")
        
        # Add sample exercises
        if Exercise.query.count() == 0:
            exercises = [
                # Bodyweight Exercises
                Exercise(
                    name="Push-ups",
                    description="Classic upper body exercise targeting chest, shoulders, and triceps",
                    category="strength",
                    muscle_group="chest",
                    equipment="None",
                    difficulty="beginner",
                    instructions="1. Start in plank position with hands slightly wider than shoulders\n2. Lower body until chest nearly touches floor\n3. Push back up to starting position\n4. Keep core engaged throughout",
                    tips="Keep your body in a straight line from head to heels. Modify by doing push-ups on knees if needed.",
                    calories_per_minute=7.0
                ),
                Exercise(
                    name="Squats",
                    description="Fundamental lower body exercise for legs and glutes",
                    category="strength",
                    muscle_group="legs",
                    equipment="None",
                    difficulty="beginner",
                    instructions="1. Stand with feet shoulder-width apart\n2. Lower body as if sitting in a chair\n3. Keep chest up and knees behind toes\n4. Return to starting position",
                    tips="Keep your weight on your heels. Go as low as comfortable while maintaining form.",
                    calories_per_minute=8.0
                ),
                Exercise(
                    name="Plank",
                    description="Core strengthening exercise",
                    category="strength",
                    muscle_group="core",
                    equipment="None",
                    difficulty="beginner",
                    instructions="1. Start in push-up position\n2. Hold body in straight line\n3. Engage core muscles\n4. Maintain position for specified time",
                    tips="Don't let hips sag or rise. Keep breathing steadily throughout.",
                    calories_per_minute=5.0
                ),
                Exercise(
                    name="Lunges",
                    description="Single-leg exercise for legs and glutes",
                    category="strength",
                    muscle_group="legs",
                    equipment="None",
                    difficulty="beginner",
                    instructions="1. Step forward with one leg\n2. Lower hips until both knees are bent at 90 degrees\n3. Push back to starting position\n4. Alternate legs",
                    tips="Keep front knee behind toes. Keep torso upright throughout movement.",
                    calories_per_minute=6.0
                ),
                Exercise(
                    name="Jumping Jacks",
                    description="Cardiovascular exercise for warm-up and conditioning",
                    category="cardio",
                    muscle_group="full_body",
                    equipment="None",
                    difficulty="beginner",
                    instructions="1. Start standing with feet together, arms at sides\n2. Jump while spreading legs and raising arms overhead\n3. Jump back to starting position\n4. Repeat rhythmically",
                    tips="Land softly to protect joints. Maintain steady pace for cardio benefits.",
                    calories_per_minute=10.0
                ),
                Exercise(
                    name="Burpees",
                    description="Full-body exercise combining strength and cardio",
                    category="cardio",
                    muscle_group="full_body",
                    equipment="None",
                    difficulty="advanced",
                    instructions="1. Start in standing position\n2. Drop to squat position\n3. Kick feet back to plank\n4. Do a push-up\n5. Jump feet back to squat\n6. Jump up with arms overhead",
                    tips="This is an advanced exercise. Start with modified version if needed. Focus on form over speed.",
                    calories_per_minute=12.0
                ),
                Exercise(
                    name="Mountain Climbers",
                    description="Cardio and core exercise",
                    category="cardio",
                    muscle_group="core",
                    equipment="None",
                    difficulty="intermediate",
                    instructions="1. Start in plank position\n2. Bring one knee toward chest\n3. Quickly switch legs\n4. Continue alternating rapidly",
                    tips="Keep hips level and core engaged. The faster you go, the more cardio benefit.",
                    calories_per_minute=11.0
                ),
                Exercise(
                    name="Crunches",
                    description="Abdominal strengthening exercise",
                    category="strength",
                    muscle_group="core",
                    equipment="None",
                    difficulty="beginner",
                    instructions="1. Lie on back with knees bent\n2. Place hands behind head (don't pull)\n3. Lift shoulders off floor\n4. Lower back down with control",
                    tips="Don't pull on your neck. Focus on using abdominal muscles to lift.",
                    calories_per_minute=4.0
                )
            ]
            
            for exercise in exercises:
                db.session.add(exercise)
            
            print("Sample exercises added successfully!")
        
        # Add sample workout plans
        if WorkoutPlan.query.count() == 0:
            workout_plans = [
                WorkoutPlan(
                    name="Beginner Full Body",
                    description="Perfect for beginners starting their fitness journey",
                    difficulty="beginner",
                    duration_weeks=4,
                    target_goal="general_fitness",
                    equipment_needed="None required, optional: dumbbells",
                    category="full_body"
                ),
                WorkoutPlan(
                    name="Weight Loss HIIT",
                    description="High-intensity interval training for effective weight loss",
                    difficulty="intermediate",
                    duration_weeks=8,
                    target_goal="weight_loss",
                    equipment_needed="None, optional: jump rope, dumbbells",
                    category="cardio"
                ),
                WorkoutPlan(
                    name="Muscle Building",
                    description="Progressive strength training for muscle gain",
                    difficulty="intermediate",
                    duration_weeks=12,
                    target_goal="muscle_gain",
                    equipment_needed="Dumbbells, resistance bands",
                    category="strength"
                )
            ]
            
            for plan in workout_plans:
                db.session.add(plan)
            
            db.session.commit()
            
            # Add workout exercises to plans
            beginner_plan = WorkoutPlan.query.filter_by(name="Beginner Full Body").first()
            if beginner_plan:
                exercises = Exercise.query.all()
                for i, exercise in enumerate(exercises[:5]):  # Add first 5 exercises
                    workout_exercise = WorkoutExercise(
                        workout_plan_id=beginner_plan.id,
                        exercise_id=exercise.id,
                        day_of_week=1,  # Monday
                        sets=3,
                        reps=10 if exercise.category == "strength" else 30,
                        rest_seconds=60,
                        order=i+1
                    )
                    db.session.add(workout_exercise)
            
            print("Sample workout plans added successfully!")
        
        # Add health tips
        if HealthTip.query.count() == 0:
            health_tips = [
                HealthTip(
                    title="Stay Hydrated Throughout the Day",
                    content="Drink at least 8 glasses of water daily. Proper hydration is essential for muscle function, energy levels, and overall health. Carry a water bottle with you and sip throughout the day.",
                    category="nutrition",
                    author="RSK World Fitness Team",
                    is_featured=True
                ),
                HealthTip(
                    title="Get Enough Quality Sleep",
                    content="Aim for 7-9 hours of quality sleep each night. Sleep is crucial for muscle recovery, hormone regulation, and overall health. Create a consistent sleep schedule and optimize your sleep environment.",
                    category="recovery",
                    author="RSK World Fitness Team",
                    is_featured=True
                ),
                HealthTip(
                    title="Include Protein in Every Meal",
                    content="Protein helps build and repair muscles. Include a source of lean protein in every meal - chicken, fish, eggs, beans, or plant-based alternatives. Aim for 1.6-2.2g per kg of bodyweight daily if you're active.",
                    category="nutrition",
                    author="RSK World Fitness Team",
                    is_featured=False
                ),
                HealthTip(
                    title="Warm Up Before Every Workout",
                    content="Always spend 5-10 minutes warming up before exercise. This increases blood flow to muscles, reduces injury risk, and improves performance. Include light cardio and dynamic stretching.",
                    category="safety",
                    author="RSK World Fitness Team",
                    is_featured=False
                ),
                HealthTip(
                    title="Listen to Your Body",
                    content="Pay attention to signals from your body. Distinguish between normal muscle soreness and pain that could indicate injury. Rest when needed and don't push through sharp pain.",
                    category="safety",
                    author="RSK World Fitness Team",
                    is_featured=False
                ),
                HealthTip(
                    title="Consistency Over Intensity",
                    content="Regular moderate exercise is better than occasional intense workouts followed by long breaks. Aim for consistency in your fitness routine for long-term results.",
                    category="motivation",
                    author="RSK World Fitness Team",
                    is_featured=True
                ),
                HealthTip(
                    title="Track Your Progress",
                    content="Keep a workout log to track your exercises, weights, reps, and how you feel. This helps you see progress over time and identify areas for improvement.",
                    category="exercise",
                    author="RSK World Fitness Team",
                    is_featured=False
                ),
                HealthTip(
                    title="Mix Up Your Routine",
                    content="Prevent boredom and plateaus by varying your workouts. Try new exercises, change your rep ranges, or try different types of cardio to keep challenging your body.",
                    category="exercise",
                    author="RSK World Fitness Team",
                    is_featured=False
                )
            ]
            
            for tip in health_tips:
                db.session.add(tip)
            
            print("Health tips added successfully!")
        
        # Commit all changes
        db.session.commit()
        print("\nDatabase initialization completed successfully!")
        print("Sample data has been added to help you get started.")

if __name__ == "__main__":
    try:
        init_database()
    except Exception as e:
        print(f"Error initializing database: {e}")
        sys.exit(1)
256 lines•12.7 KB
python
utils/analytics_engine.py
Raw Download
Find: Go to:
"""
Advanced Analytics Engine 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
"""

import json
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
from enum import Enum

class MetricType(Enum):
    WORKOUT_FREQUENCY = "workout_frequency"
    CALORIE_BURN = "calorie_burn"
    STRENGTH_PROGRESS = "strength_progress"
    ENDURANCE_PROGRESS = "endurance_progress"
    WEIGHT_CHANGE = "weight_change"
    BODY_COMPOSITION = "body_composition"
    NUTRITION_COMPLIANCE = "nutrition_compliance"
    SLEEP_QUALITY = "sleep_quality"
    RECOVERY_RATE = "recovery_rate"

@dataclass
class AnalyticsMetric:
    name: str
    value: float
    unit: str
    trend: str  # improving, declining, stable
    change_percentage: float
    date: datetime
    category: str

class AdvancedAnalytics:
    """Comprehensive analytics engine for fitness tracking and insights"""
    
    def __init__(self):
        self.metrics_history = {}
        self.user_goals = {}
        self.benchmarks = self._load_benchmarks()
        self.prediction_models = {}
        
    def _load_benchmarks(self) -> Dict:
        """Load fitness benchmarks for comparison"""
        return {
            "beginner": {
                "pushups_1min": {"excellent": 30, "good": 20, "average": 10},
                "squats_1min": {"excellent": 40, "good": 30, "average": 20},
                "plank_hold": {"excellent": 120, "good": 60, "average": 30},
                "mile_run": {"excellent": 480, "good": 600, "average": 720}  # seconds
            },
            "intermediate": {
                "pushups_1min": {"excellent": 50, "good": 40, "average": 30},
                "squats_1min": {"excellent": 60, "good": 50, "average": 40},
                "plank_hold": {"excellent": 180, "good": 120, "average": 60},
                "mile_run": {"excellent": 360, "good": 420, "average": 480}
            },
            "advanced": {
                "pushups_1min": {"excellent": 70, "good": 60, "average": 50},
                "squats_1min": {"excellent": 80, "good": 70, "average": 60},
                "plank_hold": {"excellent": 300, "good": 180, "average": 120},
                "mile_run": {"excellent": 300, "good": 360, "average": 420}
            }
        }
    
    def calculate_comprehensive_analytics(self, user_id: str, timeframe: int = 30) -> Dict:
        """Generate comprehensive analytics dashboard"""
        end_date = datetime.now()
        start_date = end_date - timedelta(days=timeframe)
        
        analytics = {
            "user_id": user_id,
            "timeframe": timeframe,
            "period": f"{start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}",
            "overall_score": 0,
            "categories": {},
            "trends": {},
            "predictions": {},
            "achievements": [],
            "recommendations": [],
            "comparisons": {}
        }
        
        # Calculate metrics for each category
        analytics["categories"]["workout"] = self._calculate_workout_analytics(user_id, start_date, end_date)
        analytics["categories"]["strength"] = self._calculate_strength_analytics(user_id, start_date, end_date)
        analytics["categories"]["cardio"] = self._calculate_cardio_analytics(user_id, start_date, end_date)
        analytics["categories"]["nutrition"] = self._calculate_nutrition_analytics(user_id, start_date, end_date)
        analytics["categories"]["recovery"] = self._calculate_recovery_analytics(user_id, start_date, end_date)
        analytics["categories"]["body"] = self._calculate_body_composition_analytics(user_id, start_date, end_date)
        
        # Calculate overall score
        analytics["overall_score"] = self._calculate_overall_score(analytics["categories"])
        
        # Generate trends
        analytics["trends"] = self._calculate_trends(user_id, timeframe)
        
        # Generate predictions
        analytics["predictions"] = self._generate_predictions(user_id, analytics["categories"])
        
        # Check achievements
        analytics["achievements"] = self._check_analytics_achievements(analytics)
        
        # Generate recommendations
        analytics["recommendations"] = self._generate_analytics_recommendations(analytics)
        
        # Generate comparisons
        analytics["comparisons"] = self._generate_comparisons(analytics)
        
        return analytics
    
    def _calculate_workout_analytics(self, user_id: str, start_date: datetime, end_date: datetime) -> Dict:
        """Calculate workout-related analytics"""
        # This would query actual workout data from database
        # For demonstration, using sample data
        
        total_workouts = 18
        total_duration = 1350  # minutes
        total_calories = 8500
        
        # Calculate frequency
        days_period = (end_date - start_date).days
        workout_frequency = total_workouts / days_period * 7  # workouts per week
        
        # Calculate consistency
        workout_days = 15  # days with workouts
        consistency_score = (workout_days / total_workouts) * 100 if total_workouts > 0 else 0
        
        # Calculate average metrics
        avg_duration = total_duration / total_workouts if total_workouts > 0 else 0
        avg_calories = total_calories / total_workouts if total_workouts > 0 else 0
        
        # Calculate intensity distribution
        intensity_distribution = {
            "low": 20,  # percentage
            "moderate": 50,
            "high": 30
        }
        
        return {
            "total_workouts": total_workouts,
            "total_duration": total_duration,
            "total_calories": total_calories,
            "workout_frequency": round(workout_frequency, 1),
            "consistency_score": round(consistency_score, 1),
            "avg_duration": round(avg_duration, 1),
            "avg_calories": round(avg_calories, 1),
            "intensity_distribution": intensity_distribution,
            "most_trained_days": ["Monday", "Wednesday", "Friday"],
            "preferred_workout_time": "Morning",
            "score": self._calculate_workout_score(workout_frequency, consistency_score)
        }
    
    def _calculate_strength_analytics(self, user_id: str, start_date: datetime, end_date: datetime) -> Dict:
        """Calculate strength-related analytics"""
        # Sample strength data
        strength_exercises = {
            "bench_press": {"start_weight": 50, "current_weight": 65, "improvement": 30},
            "squat": {"start_weight": 60, "current_weight": 80, "improvement": 33},
            "deadlift": {"start_weight": 70, "current_weight": 90, "improvement": 29},
            "overhead_press": {"start_weight": 30, "current_weight": 40, "improvement": 33}
        }
        
        # Calculate overall strength improvement
        total_improvement = sum(ex["improvement"] for ex in strength_exercises.values())
        avg_improvement = total_improvement / len(strength_exercises)
        
        # Calculate strength score
        strength_score = min(100, avg_improvement * 2)
        
        # Calculate volume progression
        volume_progression = self._calculate_volume_progression()
        
        return {
            "strength_exercises": strength_exercises,
            "avg_improvement": round(avg_improvement, 1),
            "strength_score": round(strength_score, 1),
            "volume_progression": volume_progression,
            "one_rep_max_estimates": self._calculate_1rm_estimates(strength_exercises),
            "strength_level": self._determine_strength_level(strength_score),
            "score": strength_score
        }
    
    def _calculate_cardio_analytics(self, user_id: str, start_date: datetime, end_date: datetime) -> Dict:
        """Calculate cardiovascular fitness analytics"""
        # Sample cardio data
        cardio_sessions = [
            {"type": "running", "duration": 30, "distance": 5.2, "avg_heart_rate": 165},
            {"type": "cycling", "duration": 45, "distance": 15.8, "avg_heart_rate": 145},
            {"type": "swimming", "duration": 40, "distance": 1.2, "avg_heart_rate": 155}
        ]
        
        # Calculate cardio metrics
        total_distance = sum(session["distance"] for session in cardio_sessions)
        total_duration = sum(session["duration"] for session in cardio_sessions)
        avg_heart_rate = sum(session["avg_heart_rate"] for session in cardio_sessions) / len(cardio_sessions)
        
        # Calculate VO2 max estimate
        vo2_max = self._estimate_vo2_max(total_distance, total_duration)
        
        # Calculate cardio zones
        cardio_zones = self._calculate_cardio_zones(avg_heart_rate)
        
        return {
            "total_sessions": len(cardio_sessions),
            "total_distance": round(total_distance, 1),
            "total_duration": total_duration,
            "avg_heart_rate": round(avg_heart_rate),
            "vo2_max_estimate": round(vo2_max, 1),
            "cardio_zones": cardio_zones,
            "endurance_score": self._calculate_endurance_score(vo2_max),
            "favorite_cardio": "running",
            "score": self._calculate_endurance_score(vo2_max)
        }
    
    def _calculate_nutrition_analytics(self, user_id: str, start_date: datetime, end_date: datetime) -> Dict:
        """Calculate nutrition-related analytics"""
        # Sample nutrition data
        daily_nutrition = {
            "avg_calories": 2150,
            "avg_protein": 142,
            "avg_carbs": 245,
            "avg_fat": 78,
            "avg_fiber": 22,
            "avg_water": 2.1  # liters
        }
        
        # Goal comparison
        goals = {
            "calories": 2200,
            "protein": 150,
            "carbs": 275,
            "fat": 73,
            "fiber": 25,
            "water": 2.5
        }
        
        # Calculate compliance percentages
        compliance = {}
        for nutrient in daily_nutrition:
            if nutrient in goals:
                compliance[nutrient] = min(100, (daily_nutrition[nutrient] / goals[nutrient]) * 100)
        
        # Calculate nutrition score
        nutrition_score = sum(compliance.values()) / len(compliance)
        
        # Calculate meal timing consistency
        meal_timing = {
            "breakfast_consistency": 85,
            "lunch_consistency": 90,
            "dinner_consistency": 80,
            "snack_frequency": 3  # per week
        }
        
        return {
            "daily_averages": daily_nutrition,
            "goals": goals,
            "compliance": {k: round(v, 1) for k, v in compliance.items()},
            "nutrition_score": round(nutrition_score, 1),
            "meal_timing": meal_timing,
            "macro_distribution": {
                "protein": round((daily_nutrition["protein"] * 4 / (daily_nutrition["calories"])) * 100, 1),
                "carbs": round((daily_nutrition["carbs"] * 4 / (daily_nutrition["calories"])) * 100, 1),
                "fat": round((daily_nutrition["fat"] * 9 / (daily_nutrition["calories"])) * 100, 1)
            },
            "score": round(nutrition_score, 1)
        }
    
    def _calculate_recovery_analytics(self, user_id: str, start_date: datetime, end_date: datetime) -> Dict:
        """Calculate recovery and rest analytics"""
        # Sample recovery data
        sleep_data = {
            "avg_duration": 7.2,  # hours
            "avg_quality": 78,  # percentage
            "deep_sleep_percentage": 22,
            "rem_sleep_percentage": 18,
            "consistency": 85
        }
        
        # Calculate recovery metrics
        recovery_score = self._calculate_recovery_score(sleep_data)
        
        # Rest day analysis
        rest_days = 8
        total_days = 30
        rest_day_percentage = (rest_days / total_days) * 100
        
        # Muscle soreness tracking
        soreness_data = {
            "avg_soreness": 3.2,  # scale 1-10
            "recovery_time": 48,  # hours
            "active_recovery_sessions": 4
        }
        
        return {
            "sleep_data": sleep_data,
            "recovery_score": round(recovery_score, 1),
            "rest_day_percentage": round(rest_day_percentage, 1),
            "soreness_data": soreness_data,
            "active_recovery_sessions": 4,
            "injury_risk": self._calculate_injury_risk(recovery_score, soreness_data),
            "score": round(recovery_score, 1)
        }
    
    def _calculate_body_composition_analytics(self, user_id: str, start_date: datetime, end_date: datetime) -> Dict:
        """Calculate body composition analytics"""
        # Sample body composition data
        body_metrics = {
            "weight": {"start": 75.5, "current": 73.2, "change": -2.3},
            "body_fat": {"start": 22.5, "current": 20.1, "change": -2.4},
            "muscle_mass": {"start": 58.5, "current": 58.5, "change": 0.0},
            "waist": {"start": 85, "current": 82, "change": -3},
            "chest": {"start": 95, "current": 96, "change": 1}
        }
        
        # Calculate BMI
        height = 1.75  # meters
        current_bmi = body_metrics["weight"]["current"] / (height ** 2)
        
        # Calculate body composition score
        composition_score = self._calculate_composition_score(body_metrics)
        
        return {
            "body_metrics": body_metrics,
            "bmi": round(current_bmi, 1),
            "bmi_category": self._get_bmi_category(current_bmi),
            "composition_score": round(composition_score, 1),
            "weight_trend": "decreasing",
            "body_fat_trend": "decreasing",
            "muscle_mass_trend": "stable",
            "score": round(composition_score, 1)
        }
    
    def _calculate_overall_score(self, categories: Dict) -> float:
        """Calculate overall fitness score"""
        weights = {
            "workout": 0.25,
            "strength": 0.20,
            "cardio": 0.20,
            "nutrition": 0.15,
            "recovery": 0.10,
            "body": 0.10
        }
        
        total_score = 0
        for category, weight in weights.items():
            if category in categories and "score" in categories[category]:
                total_score += categories[category]["score"] * weight
        
        return round(total_score, 1)
    
    def _calculate_trends(self, user_id: str, timeframe: int) -> Dict:
        """Calculate trends for various metrics"""
        trends = {}
        
        # Compare current period to previous period
        current_end = datetime.now()
        current_start = current_end - timedelta(days=timeframe)
        previous_end = current_start
        previous_start = previous_end - timedelta(days=timeframe)
        
        # Sample trend calculations
        trends["workout_frequency"] = {
            "current": 4.2,
            "previous": 3.8,
            "trend": "improving",
            "change_percentage": 10.5
        }
        
        trends["strength"] = {
            "current": 75.0,
            "previous": 68.0,
            "trend": "improving",
            "change_percentage": 10.3
        }
        
        trends["weight"] = {
            "current": 73.2,
            "previous": 74.8,
            "trend": "improving",
            "change_percentage": -2.1
        }
        
        trends["consistency"] = {
            "current": 85.0,
            "previous": 78.0,
            "trend": "improving",
            "change_percentage": 9.0
        }
        
        return trends
    
    def _generate_predictions(self, user_id: str, categories: Dict) -> Dict:
        """Generate predictions based on current data"""
        predictions = {}
        
        # Weight prediction
        current_weight = categories.get("body", {}).get("body_metrics", {}).get("weight", {}).get("current", 75)
        weight_trend = categories.get("body", {}).get("weight_trend", "stable")
        
        if weight_trend == "decreasing":
            predictions["weight_30_days"] = round(current_weight - 1.5, 1)
            predictions["weight_90_days"] = round(current_weight - 4.5, 1)
        elif weight_trend == "increasing":
            predictions["weight_30_days"] = round(current_weight + 1.2, 1)
            predictions["weight_90_days"] = round(current_weight + 3.6, 1)
        else:
            predictions["weight_30_days"] = current_weight
            predictions["weight_90_days"] = current_weight
        
        # Strength prediction
        current_strength = categories.get("strength", {}).get("strength_score", 50)
        strength_improvement_rate = 2.5  # points per month
        
        predictions["strength_30_days"] = min(100, current_strength + strength_improvement_rate)
        predictions["strength_90_days"] = min(100, current_strength + (strength_improvement_rate * 3))
        
        # Goal achievement prediction
        predictions["goal_achievement_probability"] = self._calculate_goal_probability(categories)
        
        # Injury risk prediction
        recovery_score = categories.get("recovery", {}).get("recovery_score", 80)
        predictions["injury_risk"] = max(0, min(100, 100 - recovery_score))
        
        return predictions
    
    def _check_analytics_achievements(self, analytics: Dict) -> List[Dict]:
        """Check for analytics-based achievements"""
        achievements = []
        
        overall_score = analytics.get("overall_score", 0)
        
        if overall_score >= 90:
            achievements.append({
                "id": "fitness_elite",
                "name": "Fitness Elite",
                "description": "Maintained 90+ overall fitness score",
                "icon": "👑",
                "date": datetime.now().isoformat()
            })
        elif overall_score >= 80:
            achievements.append({
                "id": "fitness_champion",
                "name": "Fitness Champion",
                "description": "Maintained 80+ overall fitness score",
                "icon": "🏆",
                "date": datetime.now().isoformat()
            })
        
        # Check consistency achievements
        consistency = analytics.get("categories", {}).get("workout", {}).get("consistency_score", 0)
        if consistency >= 90:
            achievements.append({
                "id": "consistency_master",
                "name": "Consistency Master",
                "description": "90%+ workout consistency",
                "icon": "📅",
                "date": datetime.now().isoformat()
            })
        
        return achievements
    
    def _generate_analytics_recommendations(self, analytics: Dict) -> List[str]:
        """Generate personalized recommendations based on analytics"""
        recommendations = []
        
        # Workout recommendations
        workout_score = analytics.get("categories", {}).get("workout", {}).get("score", 0)
        if workout_score < 70:
            recommendations.append("Increase workout frequency to at least 3-4 times per week for better results")
        
        # Strength recommendations
        strength_score = analytics.get("categories", {}).get("strength", {}).get("score", 0)
        if strength_score < 70:
            recommendations.append("Focus on progressive overload - gradually increase weight or reps")
        
        # Cardio recommendations
        cardio_score = analytics.get("categories", {}).get("cardio", {}).get("score", 0)
        if cardio_score < 70:
            recommendations.append("Add more cardiovascular exercise to improve endurance and heart health")
        
        # Nutrition recommendations
        nutrition_score = analytics.get("categories", {}).get("nutrition", {}).get("score", 0)
        if nutrition_score < 70:
            recommendations.append("Improve nutrition compliance - track meals more consistently")
        
        # Recovery recommendations
        recovery_score = analytics.get("categories", {}).get("recovery", {}).get("score", 0)
        if recovery_score < 70:
            recommendations.append("Prioritize sleep and recovery - aim for 7-9 hours of quality sleep")
        
        return recommendations
    
    def _generate_comparisons(self, analytics: Dict) -> Dict:
        """Generate peer comparisons and rankings"""
        # Sample comparison data
        overall_score = analytics.get("overall_score", 0)
        
        comparisons = {
            "global_ranking": {
                "your_score": overall_score,
                "percentile": self._calculate_percentile(overall_score),
                "total_users": 10000
            },
            "age_group_ranking": {
                "your_score": overall_score,
                "percentile": self._calculate_percentile(overall_score) + 5,
                "total_users": 2500
            },
            "goal_group_ranking": {
                "your_score": overall_score,
                "percentile": self._calculate_percentile(overall_score) + 3,
                "total_users": 1500
            }
        }
        
        return comparisons
    
    def _calculate_percentile(self, score: float) -> int:
        """Calculate percentile rank based on score"""
        # Simplified percentile calculation
        return min(99, max(1, int(score * 0.9)))
    
    def _calculate_workout_score(self, frequency: float, consistency: float) -> float:
        """Calculate workout score based on frequency and consistency"""
        frequency_score = min(100, frequency * 20)  # 5 workouts/week = 100
        consistency_weight = 0.6
        frequency_weight = 0.4
        
        return (consistency * consistency_weight) + (frequency_score * frequency_weight)
    
    def _calculate_strength_score(self, improvement: float) -> float:
        """Calculate strength score based on improvement"""
        return min(100, 50 + improvement)  # Base 50 + improvement
    
    def _calculate_endurance_score(self, vo2_max: float) -> float:
        """Calculate endurance score based on VO2 max"""
        # VO2 max norms: Excellent (>55), Good (45-55), Average (35-45), Poor (<35)
        if vo2_max > 55:
            return 90 + min(10, (vo2_max - 55) * 2)
        elif vo2_max > 45:
            return 70 + (vo2_max - 45) * 2
        elif vo2_max > 35:
            return 50 + (vo2_max - 35) * 2
        else:
            return max(0, vo2_max * 1.4)
    
    def _calculate_recovery_score(self, sleep_data: Dict) -> float:
        """Calculate recovery score based on sleep metrics"""
        duration_score = min(100, (sleep_data["avg_duration"] / 8) * 100)
        quality_score = sleep_data["avg_quality"]
        consistency_score = sleep_data["consistency"]
        
        return (duration_score * 0.4) + (quality_score * 0.3) + (consistency_score * 0.3)
    
    def _calculate_composition_score(self, body_metrics: Dict) -> float:
        """Calculate body composition score"""
        weight_change = abs(body_metrics["weight"]["change"])
        fat_change = abs(body_metrics["body_fat"]["change"])
        
        # Score based on positive changes
        score = 50  # Base score
        
        if body_metrics["weight"]["change"] < 0:  # Weight loss
            score += min(25, weight_change * 10)
        
        if body_metrics["body_fat"]["change"] < 0:  # Fat loss
            score += min(25, fat_change * 10)
        
        return min(100, score)
    
    def _estimate_vo2_max(self, total_distance: float, total_duration: int) -> float:
        """Estimate VO2 max from cardio performance"""
        # Simplified VO2 max estimation
        avg_speed = (total_distance / total_duration) * 60  # km/h
        return 35 + (avg_speed * 3)  # Rough estimation
    
    def _calculate_cardio_zones(self, avg_heart_rate: int) -> Dict:
        """Calculate time spent in different heart rate zones"""
        max_heart_rate = 220 - 30  # Assuming age 30
        
        zones = {
            "zone_1": {"name": "Recovery", "range": f"50-60% ({max_heart_rate * 0.5}-{max_heart_rate * 0.6})", "percentage": 20},
            "zone_2": {"name": "Base", "range": f"60-70% ({max_heart_rate * 0.6}-{max_heart_rate * 0.7})", "percentage": 35},
            "zone_3": {"name": "Tempo", "range": f"70-80% ({max_heart_rate * 0.7}-{max_heart_rate * 0.8})", "percentage": 30},
            "zone_4": {"name": "Threshold", "range": f"80-90% ({max_heart_rate * 0.8}-{max_heart_rate * 0.9})", "percentage": 15}
        }
        
        return zones
    
    def _calculate_volume_progression(self) -> Dict:
        """Calculate training volume progression"""
        return {
            "current_week": 12500,  # kg x reps
            "previous_week": 11800,
            "change_percentage": 5.9,
            "trend": "increasing"
        }
    
    def _calculate_1rm_estimates(self, strength_exercises: Dict) -> Dict:
        """Calculate estimated 1-rep max from current weights"""
        estimates = {}
        
        for exercise, data in strength_exercises.items():
            # Using Epley formula: 1RM = weight × (1 + reps/30)
            # Assuming current weight is for 8 reps
            estimates[exercise] = round(data["current_weight"] * 1.25, 1)
        
        return estimates
    
    def _determine_strength_level(self, strength_score: float) -> str:
        """Determine strength level based on score"""
        if strength_score >= 90:
            return "Elite"
        elif strength_score >= 80:
            return "Advanced"
        elif strength_score >= 70:
            return "Intermediate"
        elif strength_score >= 60:
            return "Beginner"
        else:
            return "Novice"
    
    def _get_bmi_category(self, bmi: float) -> str:
        """Get BMI category"""
        if bmi < 18.5:
            return "Underweight"
        elif bmi < 25:
            return "Normal"
        elif bmi < 30:
            return "Overweight"
        else:
            return "Obese"
    
    def _calculate_injury_risk(self, recovery_score: float, soreness_data: Dict) -> float:
        """Calculate injury risk based on recovery and soreness"""
        recovery_risk = max(0, 100 - recovery_score)
        soreness_risk = soreness_data["avg_soreness"] * 8  # Scale 1-10 to 8-80
        
        return min(100, (recovery_risk + soreness_risk) / 2)
    
    def _calculate_goal_probability(self, categories: Dict) -> float:
        """Calculate probability of achieving goals"""
        overall_score = categories.get("overall_score", 0)
        consistency = categories.get("workout", {}).get("consistency_score", 0)
        
        # Base probability on overall score and consistency
        probability = (overall_score * 0.7) + (consistency * 0.3)
        
        return min(100, probability)
    
    def export_analytics_report(self, user_id: str, format: str = "json") -> Dict:
        """Export comprehensive analytics report"""
        analytics = self.calculate_comprehensive_analytics(user_id)
        
        if format == "json":
            return {
                "report": analytics,
                "generated_at": datetime.now().isoformat(),
                "format": "json"
            }
        elif format == "pdf":
            # This would generate PDF report
            return {
                "message": "PDF report generation not implemented in demo",
                "download_url": f"/api/analytics/report/{user_id}/pdf"
            }
        
        return analytics
674 lines•27.8 KB
python
.gitignore
Raw Download
Find: Go to:
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# Database
*.db
*.sqlite
*.sqlite3

# Environment variables
.env
.venv

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Flask
instance/
.webassets-cache

# Testing
.pytest_cache/
.coverage
htmlcov/

# Jupyter Notebook
.ipynb_checkpoints

# Logs
*.log

# Temporary files
*.tmp
test_db.py
64 lines•564 B
text
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
utils/__init__.py
Raw Download
Find: Go to:
"""
Utils 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_coach import FitnessCoach
from .ai_workout_generator import AIWorkoutGenerator
from .nutrition_ai import NutritionAI
from .social_features import SocialFeatures
from .analytics_engine import AdvancedAnalytics
from .gamification_system import GamificationSystem
from .wearable_integration import WearableIntegration, DeviceType
from .voice_coach import VoiceCoach
from .workout_buddy_matcher import WorkoutBuddyMatcher
from .smart_recovery import SmartRecovery

__all__ = [
    'FitnessCoach',
    'AIWorkoutGenerator',
    'NutritionAI',
    'SocialFeatures',
    'AdvancedAnalytics',
    'GamificationSystem',
    'WearableIntegration',
    'DeviceType',
    'VoiceCoach',
    'WorkoutBuddyMatcher',
    'SmartRecovery'
]
34 lines•965 B
python
social_features.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
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
🚀 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