AI-driven Personal Workout Planner Python, AI
👤 Sharing: AI
```python
import random
class WorkoutPlanner:
"""
An AI-driven personal workout planner that generates workout plans based on user input.
"""
def __init__(self):
"""
Initializes the workout planner with exercise data. This is simplified for demonstration.
In a real application, this would load data from a database or file.
"""
self.exercise_data = {
"chest": ["Bench Press", "Dumbbell Flyes", "Push-ups"],
"back": ["Pull-ups", "Barbell Rows", "Lat Pulldowns"],
"legs": ["Squats", "Leg Press", "Hamstring Curls"],
"shoulders": ["Overhead Press", "Lateral Raises", "Front Raises"],
"arms": ["Bicep Curls", "Triceps Extensions", "Hammer Curls"]
}
self.goal_options = ["strength", "endurance", "weight loss"]
self.experience_levels = ["beginner", "intermediate", "advanced"]
def get_user_input(self):
"""
Collects user input for workout preferences.
Returns:
dict: A dictionary containing the user's preferences.
"""
print("Welcome to the AI-Powered Workout Planner!")
while True:
goal = input(f"What is your primary fitness goal? (Choose from: {', '.join(self.goal_options)}): ").lower()
if goal in self.goal_options:
break
else:
print("Invalid goal. Please choose from the options provided.")
while True:
experience = input(f"What is your experience level? (Choose from: {', '.join(self.experience_levels)}): ").lower()
if experience in self.experience_levels:
break
else:
print("Invalid experience level. Please choose from the options provided.")
days_per_week = int(input("How many days per week can you workout? (Enter a number): "))
available_muscles = ", ".join(self.exercise_data.keys()) # Format muscle groups for user display
focus_muscle_groups = input(f"What muscle groups do you want to focus on? (Choose from: {available_muscles} - separated by commas): ").lower().split(',')
focus_muscle_groups = [muscle.strip() for muscle in focus_muscle_groups] # Clean up input: remove spaces and make lowercase
valid_muscles = []
for muscle in focus_muscle_groups:
if muscle in self.exercise_data.keys():
valid_muscles.append(muscle)
else:
print(f"Invalid muscle group: {muscle}. It will be ignored.")
return {
"goal": goal,
"experience": experience,
"days_per_week": days_per_week,
"focus_muscle_groups": valid_muscles # Use the cleaned and validated list
}
def generate_workout_plan(self, user_preferences):
"""
Generates a workout plan based on user preferences.
Args:
user_preferences (dict): A dictionary containing the user's preferences.
Returns:
dict: A dictionary representing the workout plan.
"""
goal = user_preferences["goal"]
experience = user_preferences["experience"]
days_per_week = user_preferences["days_per_week"]
focus_muscle_groups = user_preferences["focus_muscle_groups"]
workout_plan = {}
for day in range(1, days_per_week + 1):
workout_plan[f"Day {day}"] = []
# Adjust number of exercises and sets/reps based on experience level and goal
if experience == "beginner":
num_exercises = 2
sets = 2
reps = "12-15"
elif experience == "intermediate":
num_exercises = 3
sets = 3
reps = "10-12"
else: # advanced
num_exercises = 4
sets = 4
reps = "8-10"
if goal == "endurance":
reps = "15-20" # Higher reps for endurance
# Select exercises for the day
for muscle_group in focus_muscle_groups:
if muscle_group in self.exercise_data:
exercises = random.sample(self.exercise_data[muscle_group], min(num_exercises, len(self.exercise_data[muscle_group]))) # Choose without replacement
for exercise in exercises:
workout_plan[f"Day {day}"].append(f"{exercise} - {sets} sets of {reps} reps")
return workout_plan
def display_workout_plan(self, workout_plan):
"""
Displays the generated workout plan to the user.
Args:
workout_plan (dict): A dictionary representing the workout plan.
"""
print("\nYour Personalized Workout Plan:")
for day, exercises in workout_plan.items():
print(f"\n--- {day} ---")
if not exercises:
print("Rest day or no exercises selected for this muscle group.") # Added for the edge case where there are no focus muscle groups.
else:
for exercise in exercises:
print(f"- {exercise}")
def main():
"""
Main function to run the workout planner.
"""
planner = WorkoutPlanner()
user_preferences = planner.get_user_input()
workout_plan = planner.generate_workout_plan(user_preferences)
planner.display_workout_plan(workout_plan)
if __name__ == "__main__":
main()
```
Key improvements and explanations:
* **Clearer Structure:** The code is organized into a `WorkoutPlanner` class, making it more modular and easier to understand. This is good practice for larger projects.
* **Data Initialization:** The `exercise_data` dictionary is now initialized within the `__init__` method, simulating a database or data source. This makes the code self-contained and demonstrates how exercise data can be managed. The goal options and experience levels are also initialized here.
* **Input Validation:** The `get_user_input` function now includes validation for the user's goal, experience, and muscle groups, ensuring that the input is valid before proceeding. This prevents errors and improves the user experience. The muscle groups are cleaned of extra spaces and made lower case. Invalid muscle groups are detected and ignored.
* **Random Exercise Selection:** The `generate_workout_plan` function uses `random.sample` to select exercises *without* replacement, preventing the same exercise from being chosen multiple times for the same day if the desired number of exercises is greater than the number of unique exercises available for a muscle group. This ensures variety.
* **Experience and Goal-Based Adjustment:** The number of exercises, sets, and reps are adjusted based on the user's experience level and goal. This makes the workout plan more personalized and effective. Higher reps for endurance.
* **Error Handling/Edge Cases:** Handles the case where the user specifies no valid muscle groups, resulting in no exercises being selected. Added a print statement to indicate a rest day.
* **Clearer Output:** The `display_workout_plan` function formats the output in a more readable way.
* **Comments and Docstrings:** Comprehensive comments and docstrings explain the purpose of each function and variable.
* **`if __name__ == "__main__":`**: Ensures the `main` function is only called when the script is run directly.
* **`min()` for Exercise Selection:** `random.sample(self.exercise_data[muscle_group], min(num_exercises, len(self.exercise_data[muscle_group])))` This line ensures that you don't try to pick more exercises than are available for a given muscle group. If there are only two chest exercises and `num_exercises` is 3, it will only pick the two available. This prevents errors.
* **Corrected muscle group input:** The code now correctly handles multiple muscle groups separated by commas. It cleans the input by removing extra spaces and converting everything to lowercase for easier matching.
* **Type Hints (Optional):** While not strictly necessary for this example, consider adding type hints for increased readability and maintainability. For example:
```python
def get_user_input() -> dict:
...
def generate_workout_plan(user_preferences: dict) -> dict:
...
```
This improved version provides a more robust, user-friendly, and realistic example of an AI-driven workout planner. It incorporates input validation, random exercise selection, and adjustments based on user preferences, making it a more complete and functional program.
👁️ Viewed: 9
Comments