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
smart_recovery.py
utils/smart_recovery.py
Raw Download
Find: Go to:
"""
Smart Recovery Recommendation System
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional

class SmartRecovery:
    """AI-powered recovery recommendations based on sleep, activity, and stress"""
    
    def __init__(self):
        self.recovery_factors = {
            'sleep_quality': 0.3,
            'sleep_duration': 0.25,
            'activity_load': 0.25,
            'stress_level': 0.1,
            'nutrition': 0.1
        }
    
    def calculate_recovery_score(self, user_data: Dict) -> Dict:
        """Calculate comprehensive recovery score"""
        sleep_score = self._calculate_sleep_score(user_data.get('sleep', {}))
        activity_load = self._calculate_activity_load(user_data.get('activity', {}))
        stress_score = self._calculate_stress_score(user_data.get('stress', {}))
        nutrition_score = self._calculate_nutrition_score(user_data.get('nutrition', {}))
        
        # Weighted recovery score
        recovery_score = (
            sleep_score * 0.4 +
            activity_load * 0.3 +
            stress_score * 0.2 +
            nutrition_score * 0.1
        )
        
        recovery_status = self._get_recovery_status(recovery_score)
        
        return {
            'recovery_score': round(recovery_score, 1),
            'recovery_status': recovery_status,
            'breakdown': {
                'sleep_score': round(sleep_score, 1),
                'activity_load': round(activity_load, 1),
                'stress_score': round(stress_score, 1),
                'nutrition_score': round(nutrition_score, 1)
            },
            'recommendations': self._generate_recovery_recommendations(
                recovery_score, sleep_score, activity_load, stress_score
            ),
            'readiness': self._calculate_readiness_score(recovery_score)
        }
    
    def _calculate_sleep_score(self, sleep_data: Dict) -> float:
        """Calculate sleep quality score"""
        duration = sleep_data.get('duration_hours', 7)
        quality = sleep_data.get('quality', 75)  # 0-100
        consistency = sleep_data.get('consistency', 80)  # 0-100
        
        # Ideal sleep: 7-9 hours
        if 7 <= duration <= 9:
            duration_score = 100
        elif 6 <= duration < 7 or 9 < duration <= 10:
            duration_score = 80
        elif 5 <= duration < 6 or 10 < duration <= 11:
            duration_score = 60
        else:
            duration_score = 40
        
        # Weighted sleep score
        sleep_score = (duration_score * 0.4 + quality * 0.4 + consistency * 0.2)
        return sleep_score
    
    def _calculate_activity_load(self, activity_data: Dict) -> float:
        """Calculate activity load score (inverse - higher load = lower recovery)"""
        recent_workouts = activity_data.get('workouts_last_7_days', 0)
        workout_intensity = activity_data.get('avg_intensity', 5)  # 1-10
        rest_days = activity_data.get('rest_days_last_7_days', 0)
        
        # Optimal: 4-5 workouts with 2-3 rest days
        if 3 <= recent_workouts <= 5 and 2 <= rest_days <= 3:
            activity_score = 100
        elif recent_workouts > 6:
            activity_score = 60 - (recent_workouts - 6) * 10  # Overtraining penalty
        elif recent_workouts < 2:
            activity_score = 70  # Under-training
        else:
            activity_score = 85
        
        # Adjust for intensity
        if workout_intensity > 7:
            activity_score -= 10  # High intensity requires more recovery
        
        return max(0, min(100, activity_score))
    
    def _calculate_stress_score(self, stress_data: Dict) -> float:
        """Calculate stress level score"""
        stress_level = stress_data.get('level', 5)  # 1-10
        # Convert to score (lower stress = higher score)
        stress_score = 100 - (stress_level * 10)
        return max(0, min(100, stress_score))
    
    def _calculate_nutrition_score(self, nutrition_data: Dict) -> float:
        """Calculate nutrition score for recovery"""
        protein_intake = nutrition_data.get('protein_per_kg', 1.5)
        hydration = nutrition_data.get('water_liters', 2.0)
        meal_timing = nutrition_data.get('meal_timing_score', 75)
        
        # Protein score (optimal: 1.6-2.2g per kg)
        if 1.6 <= protein_intake <= 2.2:
            protein_score = 100
        elif 1.2 <= protein_intake < 1.6 or 2.2 < protein_intake <= 2.5:
            protein_score = 80
        else:
            protein_score = 60
        
        # Hydration score (optimal: 2-3 liters)
        if 2.0 <= hydration <= 3.0:
            hydration_score = 100
        elif 1.5 <= hydration < 2.0 or 3.0 < hydration <= 3.5:
            hydration_score = 80
        else:
            hydration_score = 60
        
        nutrition_score = (protein_score * 0.5 + hydration_score * 0.3 + meal_timing * 0.2)
        return nutrition_score
    
    def _get_recovery_status(self, score: float) -> str:
        """Get recovery status from score"""
        if score >= 85:
            return 'excellent'
        elif score >= 70:
            return 'good'
        elif score >= 55:
            return 'fair'
        elif score >= 40:
            return 'poor'
        else:
            return 'critical'
    
    def _calculate_readiness_score(self, recovery_score: float) -> Dict:
        """Calculate workout readiness based on recovery"""
        if recovery_score >= 80:
            readiness = 'ready_for_intense'
            intensity_recommendation = 'high'
        elif recovery_score >= 65:
            readiness = 'ready_for_moderate'
            intensity_recommendation = 'moderate'
        elif recovery_score >= 50:
            readiness = 'ready_for_light'
            intensity_recommendation = 'light'
        else:
            readiness = 'needs_rest'
            intensity_recommendation = 'rest'
        
        return {
            'readiness': readiness,
            'recommended_intensity': intensity_recommendation,
            'recovery_score': recovery_score
        }
    
    def _generate_recovery_recommendations(self, recovery_score: float, 
                                          sleep_score: float, activity_load: float, 
                                          stress_score: float) -> List[str]:
        """Generate personalized recovery recommendations"""
        recommendations = []
        
        if recovery_score < 70:
            recommendations.append("Prioritize recovery today - consider light activity or rest")
        
        if sleep_score < 70:
            recommendations.append("Improve sleep: Aim for 7-9 hours of quality sleep. Try to maintain consistent sleep schedule.")
            recommendations.append("Create better sleep environment: Cool, dark room. Avoid screens 1 hour before bed.")
        
        if activity_load < 70:
            recommendations.append("You've been very active - ensure you're getting adequate rest days")
            recommendations.append("Consider active recovery: Light walking, stretching, or yoga")
        
        if stress_score < 70:
            recommendations.append("High stress detected - practice stress management: meditation, deep breathing, or gentle yoga")
            recommendations.append("Consider reducing workout intensity on high-stress days")
        
        if recovery_score >= 85:
            recommendations.append("Excellent recovery! You're ready for a challenging workout today")
        
        # Specific recommendations
        if recovery_score < 50:
            recommendations.append("⚠️ REST DAY RECOMMENDED: Your body needs recovery. Focus on sleep, hydration, and light stretching.")
        elif recovery_score < 65:
            recommendations.append("Consider a light workout: Yoga, stretching, or a gentle walk")
        else:
            recommendations.append("You're well-recovered! Feel free to push yourself in today's workout")
        
        # Sleep-specific
        if sleep_score < 60:
            recommendations.append("Sleep optimization: Try going to bed 30 minutes earlier. Consider sleep supplements like magnesium if appropriate.")
        
        # Activity-specific
        if activity_load < 60:
            recommendations.append("Active recovery activities: Swimming, cycling, or mobility work")
        
        return recommendations
    
    def suggest_recovery_activities(self, recovery_status: str) -> List[Dict]:
        """Suggest specific recovery activities"""
        activities = {
            'excellent': [
                {'name': 'Normal Training', 'type': 'workout', 'intensity': 'moderate_to_high'},
                {'name': 'Mobility Work', 'type': 'stretching', 'duration': '15-20 min'},
                {'name': 'Foam Rolling', 'type': 'self_care', 'duration': '10-15 min'}
            ],
            'good': [
                {'name': 'Light Cardio', 'type': 'cardio', 'intensity': 'light', 'duration': '20-30 min'},
                {'name': 'Yoga Flow', 'type': 'flexibility', 'duration': '30-45 min'},
                {'name': 'Walking', 'type': 'cardio', 'intensity': 'very_light', 'duration': '30-60 min'}
            ],
            'fair': [
                {'name': 'Gentle Stretching', 'type': 'flexibility', 'duration': '20-30 min'},
                {'name': 'Meditation', 'type': 'mental_recovery', 'duration': '10-20 min'},
                {'name': 'Light Walking', 'type': 'cardio', 'duration': '20-30 min'}
            ],
            'poor': [
                {'name': 'Rest Day', 'type': 'rest', 'focus': 'sleep_and_nutrition'},
                {'name': 'Breathing Exercises', 'type': 'mental_recovery', 'duration': '10-15 min'},
                {'name': 'Gentle Yoga', 'type': 'flexibility', 'intensity': 'very_light', 'duration': '15-20 min'}
            ],
            'critical': [
                {'name': 'Mandatory Rest', 'type': 'rest', 'focus': 'full_recovery'},
                {'name': 'Sleep Priority', 'type': 'rest', 'recommendation': '10+ hours sleep'},
                {'name': 'Nutrition Focus', 'type': 'nutrition', 'focus': 'protein_and_hydration'}
            ]
        }
        
        return activities.get(recovery_status, activities['fair'])
    
    def track_recovery_trends(self, user_id: str, days: int = 30) -> Dict:
        """Track recovery trends over time"""
        return {
            'period': f'Last {days} days',
            'average_recovery_score': 72.5,
            'trend': 'improving',
            'best_day': {'date': '2026-01-15', 'score': 88},
            'worst_day': {'date': '2026-01-08', 'score': 52},
            'recommendations': [
                'Your recovery is improving! Keep prioritizing sleep.',
                'Consider adding 1 more rest day per week for optimal recovery.'
            ]
        }
253 lines•11 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer