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
/
__pycache__
RSK World
fitness-coach-bot
Fitness Coach Bot - Python + Flask + SQLAlchemy + Workout Plans + Exercise Guidance + Health Tracking + AI Fitness Coach
__pycache__
  • __init__.cpython-313.pyc1 KB
  • ai_workout_generator.cpython-313.pyc18.4 KB
  • analytics_engine.cpython-313.pyc26.4 KB
  • fitness_coach.cpython-313.pyc14.5 KB
  • gamification_system.cpython-313.pyc27.8 KB
  • nutrition_ai.cpython-313.pyc20.4 KB
  • smart_recovery.cpython-313.pyc10.7 KB
  • social_features.cpython-313.pyc22.1 KB
  • voice_coach.cpython-313.pyc9.9 KB
  • wearable_integration.cpython-313.pyc30.4 KB
  • workout_buddy_matcher.cpython-313.pyc13.6 KB
analytics_engine.pysocial_features.cpython-313.pycconfig.cpython-313.pycinit_db.py__init__.pysmart_recovery.cpython-313.pyc
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
social_features.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
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/__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
smart_recovery.cpython-313.pyc

This file cannot be displayed in the browser.

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