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
social_features.py
utils/social_features.py
Raw Download
Find: Go to:
"""
Social Features & Challenges 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
import random
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional

class SocialFeatures:
    """Advanced social features for fitness motivation and community engagement"""
    
    def __init__(self):
        self.active_challenges = {}
        self.user_achievements = {}
        self.leaderboards = {}
        self.social_feed = []
        
    def create_challenge(self, challenge_data: Dict) -> Dict:
        """Create a new fitness challenge"""
        challenge = {
            "id": self._generate_challenge_id(),
            "title": challenge_data.get("title"),
            "description": challenge_data.get("description"),
            "type": challenge_data.get("type", "individual"),  # individual, team, community
            "category": challenge_data.get("category", "general"),  # strength, cardio, nutrition, weight_loss
            "duration_days": challenge_data.get("duration_days", 30),
            "start_date": challenge_data.get("start_date", datetime.now().isoformat()),
            "end_date": None,
            "creator_id": challenge_data.get("creator_id"),
            "participants": [],
            "rules": challenge_data.get("rules", []),
            "rewards": challenge_data.get("rewards", []),
            "difficulty": challenge_data.get("difficulty", "medium"),
            "max_participants": challenge_data.get("max_participants", 100),
            "is_public": challenge_data.get("is_public", True),
            "created_at": datetime.now().isoformat(),
            "status": "upcoming"
        }
        
        # Calculate end date
        start_dt = datetime.fromisoformat(challenge["start_date"])
        challenge["end_date"] = (start_dt + timedelta(days=challenge["duration_days"])).isoformat()
        
        # Store challenge
        self.active_challenges[challenge["id"]] = challenge
        
        return challenge
    
    def join_challenge(self, user_id: str, challenge_id: str, team_id: Optional[str] = None) -> Dict:
        """Join a fitness challenge"""
        if challenge_id not in self.active_challenges:
            return {"success": False, "error": "Challenge not found"}
        
        challenge = self.active_challenges[challenge_id]
        
        # Check if challenge is still open for joining
        if challenge["status"] != "upcoming" and challenge["status"] != "active":
            return {"success": False, "error": "Challenge is not accepting new participants"}
        
        # Check if user already joined
        if any(p["user_id"] == user_id for p in challenge["participants"]):
            return {"success": False, "error": "Already joined this challenge"}
        
        # Check max participants
        if len(challenge["participants"]) >= challenge["max_participants"]:
            return {"success": False, "error": "Challenge is full"}
        
        # Add participant
        participant = {
            "user_id": user_id,
            "team_id": team_id,
            "join_date": datetime.now().isoformat(),
            "progress": {
                "points": 0,
                "workouts_completed": 0,
                "days_active": 0,
                "streak_days": 0,
                "last_activity": None
            },
            "achievements": [],
            "status": "active"
        }
        
        challenge["participants"].append(participant)
        
        # Update challenge status if needed
        if len(challenge["participants"]) >= 1 and challenge["status"] == "upcoming":
            challenge["status"] = "active"
        
        return {
            "success": True,
            "message": f"Successfully joined {challenge['title']}",
            "challenge": challenge
        }
    
    def update_challenge_progress(self, user_id: str, challenge_id: str, activity_data: Dict) -> Dict:
        """Update user's progress in a challenge"""
        if challenge_id not in self.active_challenges:
            return {"success": False, "error": "Challenge not found"}
        
        challenge = self.active_challenges[challenge_id]
        
        # Find participant
        participant = next((p for p in challenge["participants"] if p["user_id"] == user_id), None)
        if not participant:
            return {"success": False, "error": "Not participating in this challenge"}
        
        # Update progress based on activity type
        activity_type = activity_data.get("type", "workout")
        points = self._calculate_points(activity_data)
        
        participant["progress"]["points"] += points
        participant["progress"]["last_activity"] = datetime.now().isoformat()
        
        if activity_type == "workout":
            participant["progress"]["workouts_completed"] += 1
            participant["progress"]["days_active"] += 1
            participant["progress"]["streak_days"] += 1
        
        # Check for achievements
        new_achievements = self._check_challenge_achievements(participant, challenge)
        participant["achievements"].extend(new_achievements)
        
        # Update leaderboard
        self._update_leaderboard(challenge_id, user_id, participant["progress"])
        
        return {
            "success": True,
            "points_earned": points,
            "new_achievements": new_achievements,
            "current_progress": participant["progress"]
        }
    
    def _calculate_points(self, activity_data: Dict) -> int:
        """Calculate points for different activities"""
        activity_type = activity_data.get("type", "workout")
        base_points = {
            "workout": 10,
            "nutrition_logging": 5,
            "steps_goal": 15,
            "water_intake": 3,
            "sleep_goal": 8,
            "social_interaction": 2
        }
        
        points = base_points.get(activity_type, 5)
        
        # Bonus points for intensity/duration
        if activity_type == "workout":
            duration = activity_data.get("duration", 30)
            intensity = activity_data.get("intensity", "moderate")
            
            # Duration bonus
            if duration > 60:
                points += 10
            elif duration > 45:
                points += 5
            elif duration > 30:
                points += 3
            
            # Intensity bonus
            intensity_bonus = {"low": 0, "moderate": 5, "high": 10, "extreme": 15}
            points += intensity_bonus.get(intensity, 5)
        
        return points
    
    def _check_challenge_achievements(self, participant: Dict, challenge: Dict) -> List[Dict]:
        """Check for new achievements"""
        achievements = []
        progress = participant["progress"]
        
        # Workout streak achievements
        if progress["streak_days"] == 7:
            achievements.append({
                "id": "week_streak",
                "name": "Week Warrior",
                "description": "7-day workout streak",
                "icon": "🔥",
                "points": 50
            })
        elif progress["streak_days"] == 30:
            achievements.append({
                "id": "month_streak",
                "name": "Monthly Champion",
                "description": "30-day workout streak",
                "icon": "🏆",
                "points": 200
            })
        
        # Workout count achievements
        if progress["workouts_completed"] == 10:
            achievements.append({
                "id": "ten_workouts",
                "name": "Dedicated Athlete",
                "description": "Completed 10 workouts",
                "icon": "💪",
                "points": 30
            })
        elif progress["workouts_completed"] == 50:
            achievements.append({
                "id": "fifty_workouts",
                "name": "Fitness Elite",
                "description": "Completed 50 workouts",
                "icon": "⭐",
                "points": 150
            })
        
        # Points achievements
        if progress["points"] >= 100:
            achievements.append({
                "id": "century_club",
                "name": "Century Club",
                "description": "Earned 100+ points",
                "icon": "💯",
                "points": 25
            })
        
        return achievements
    
    def _update_leaderboard(self, challenge_id: str, user_id: str, progress: Dict):
        """Update challenge leaderboard"""
        if challenge_id not in self.leaderboards:
            self.leaderboards[challenge_id] = []
        
        # Update or add user to leaderboard
        leaderboard = self.leaderboards[challenge_id]
        user_entry = next((entry for entry in leaderboard if entry["user_id"] == user_id), None)
        
        if user_entry:
            user_entry["points"] = progress["points"]
            user_entry["workouts_completed"] = progress["workouts_completed"]
            user_entry["last_updated"] = datetime.now().isoformat()
        else:
            leaderboard.append({
                "user_id": user_id,
                "points": progress["points"],
                "workouts_completed": progress["workouts_completed"],
                "last_updated": datetime.now().isoformat()
            })
        
        # Sort leaderboard
        leaderboard.sort(key=lambda x: (x["points"], x["workouts_completed"]), reverse=True)
    
    def get_leaderboard(self, challenge_id: str, limit: int = 10) -> List[Dict]:
        """Get challenge leaderboard"""
        if challenge_id not in self.leaderboards:
            return []
        
        return self.leaderboards[challenge_id][:limit]
    
    def create_team(self, team_data: Dict) -> Dict:
        """Create a fitness team"""
        team = {
            "id": self._generate_team_id(),
            "name": team_data.get("name"),
            "description": team_data.get("description"),
            "creator_id": team_data.get("creator_id"),
            "members": [team_data.get("creator_id")],
            "max_members": team_data.get("max_members", 10),
            "is_private": team_data.get("is_private", False),
            "invite_code": self._generate_invite_code(),
            "team_stats": {
                "total_workouts": 0,
                "total_points": 0,
                "average_streak": 0,
                "created_at": datetime.now().isoformat()
            },
            "achievements": [],
            "created_at": datetime.now().isoformat()
        }
        
        return team
    
    def join_team(self, user_id: str, team_id: str, invite_code: Optional[str] = None) -> Dict:
        """Join a fitness team"""
        # This would integrate with database in production
        return {"success": True, "message": "Successfully joined team"}
    
    def create_social_post(self, user_id: str, post_data: Dict) -> Dict:
        """Create a social post"""
        post = {
            "id": self._generate_post_id(),
            "user_id": user_id,
            "content": post_data.get("content"),
            "type": post_data.get("type", "text"),  # text, image, workout, achievement
            "media_url": post_data.get("media_url"),
            "workout_data": post_data.get("workout_data"),
            "achievement_data": post_data.get("achievement_data"),
            "tags": post_data.get("tags", []),
            "likes": [],
            "comments": [],
            "shares": 0,
            "created_at": datetime.now().isoformat(),
            "privacy": post_data.get("privacy", "public")  # public, friends, private
        }
        
        # Add to social feed
        self.social_feed.insert(0, post)
        
        return post
    
    def interact_with_post(self, user_id: str, post_id: str, interaction_type: str, 
                         content: Optional[str] = None) -> Dict:
        """Interact with social posts (like, comment, share)"""
        # Find post
        post = next((p for p in self.social_feed if p["id"] == post_id), None)
        if not post:
            return {"success": False, "error": "Post not found"}
        
        if interaction_type == "like":
            if user_id not in post["likes"]:
                post["likes"].append(user_id)
            else:
                post["likes"].remove(user_id)
        
        elif interaction_type == "comment":
            comment = {
                "id": self._generate_comment_id(),
                "user_id": user_id,
                "content": content,
                "created_at": datetime.now().isoformat(),
                "likes": []
            }
            post["comments"].append(comment)
        
        elif interaction_type == "share":
            post["shares"] += 1
        
        return {"success": True, "post": post}
    
    def get_social_feed(self, user_id: str, feed_type: str = "all", limit: int = 20) -> List[Dict]:
        """Get personalized social feed"""
        if feed_type == "all":
            return self.social_feed[:limit]
        elif feed_type == "friends":
            # Filter by friends (would need friend relationships)
            return self.social_feed[:limit]
        elif feed_type == "trending":
            # Sort by engagement
            sorted_feed = sorted(self.social_feed, 
                             key=lambda x: len(x["likes"]) + x["shares"], 
                             reverse=True)
            return sorted_feed[:limit]
        
        return []
    
    def get_recommended_challenges(self, user_profile: Dict, limit: int = 5) -> List[Dict]:
        """Get recommended challenges based on user profile"""
        user_goals = user_profile.get("goals", ["general_fitness"])
        fitness_level = user_profile.get("fitness_level", "beginner")
        
        recommendations = []
        
        # Filter challenges based on user preferences
        for challenge in self.active_challenges.values():
            if challenge["is_public"] and challenge["status"] in ["upcoming", "active"]:
                # Check if challenge matches user goals
                if any(goal in challenge["title"].lower() for goal in user_goals):
                    recommendations.append(challenge)
                elif challenge["difficulty"] == fitness_level:
                    recommendations.append(challenge)
        
        # Sort by relevance and limit
        recommendations.sort(key=lambda x: x["created_at"], reverse=True)
        return recommendations[:limit]
    
    def generate_community_report(self, timeframe: str = "week") -> Dict:
        """Generate community-wide statistics"""
        now = datetime.now()
        
        if timeframe == "week":
            start_date = now - timedelta(days=7)
        elif timeframe == "month":
            start_date = now - timedelta(days=30)
        else:
            start_date = now - timedelta(days=1)
        
        # Calculate statistics (would query database in production)
        total_workouts = random.randint(500, 1500)
        total_users = random.randint(100, 300)
        total_calories_burned = random.randint(50000, 150000)
        active_challenges = len([c for c in self.active_challenges.values() if c["status"] == "active"])
        
        return {
            "timeframe": timeframe,
            "period": f"{start_date.strftime('%Y-%m-%d')} to {now.strftime('%Y-%m-%d')}",
            "statistics": {
                "total_workouts": total_workouts,
                "total_users": total_users,
                "total_calories_burned": total_calories_burned,
                "active_challenges": active_challenges,
                "average_workouts_per_user": round(total_workouts / total_users, 1),
                "top_activities": [
                    {"activity": "Running", "count": random.randint(200, 500)},
                    {"activity": "Strength Training", "count": random.randint(150, 400)},
                    {"activity": "Yoga", "count": random.randint(100, 300)},
                    {"activity": "Cycling", "count": random.randint(80, 250)}
                ]
            },
            "achievements_unlocked": random.randint(50, 200),
            "new_members": random.randint(10, 50)
        }
    
    def send_challenge_invitation(self, from_user_id: str, to_user_id: str, 
                               challenge_id: str, message: Optional[str] = None) -> Dict:
        """Send challenge invitation to another user"""
        invitation = {
            "id": self._generate_invitation_id(),
            "from_user_id": from_user_id,
            "to_user_id": to_user_id,
            "challenge_id": challenge_id,
            "message": message or f"Join me in this fitness challenge!",
            "status": "pending",
            "created_at": datetime.now().isoformat()
        }
        
        # In production, this would send notification and store in database
        return {"success": True, "invitation": invitation}
    
    def respond_to_invitation(self, invitation_id: str, response: str) -> Dict:
        """Respond to challenge invitation"""
        # In production, this would update database and notify sender
        return {"success": True, "response": response}
    
    def _generate_challenge_id(self) -> str:
        """Generate unique challenge ID"""
        return f"challenge_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{random.randint(1000, 9999)}"
    
    def _generate_team_id(self) -> str:
        """Generate unique team ID"""
        return f"team_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{random.randint(1000, 9999)}"
    
    def _generate_post_id(self) -> str:
        """Generate unique post ID"""
        return f"post_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{random.randint(1000, 9999)}"
    
    def _generate_comment_id(self) -> str:
        """Generate unique comment ID"""
        return f"comment_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{random.randint(1000, 9999)}"
    
    def _generate_invitation_id(self) -> str:
        """Generate unique invitation ID"""
        return f"inv_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{random.randint(1000, 9999)}"
    
    def _generate_invite_code(self) -> str:
        """Generate team invite code"""
        return ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=8))
    
    def get_user_social_stats(self, user_id: str) -> Dict:
        """Get comprehensive social statistics for a user"""
        return {
            "challenges_participated": random.randint(5, 20),
            "challenges_won": random.randint(1, 8),
            "team_memberships": random.randint(1, 3),
            "social_posts": random.randint(10, 50),
            "total_likes_received": random.randint(50, 500),
            "followers": random.randint(20, 200),
            "following": random.randint(30, 150),
            "achievement_points": random.randint(200, 2000),
            "current_streak": random.randint(0, 30),
            "longest_streak": random.randint(7, 60),
            "rank": {
                "global": random.randint(100, 5000),
                "local": random.randint(10, 100)
            }
        }
473 lines•19.4 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