Plan / app.py
AlaaElsayed's picture
Update app.py
080aaba verified
import gradio as gr
import pandas as pd
import joblib
from collections import OrderedDict
# Load models and encoders
food_model = joblib.load("goal_classifier.pkl")
exercise_model = joblib.load("exercise_classifier.pkl")
encoders = joblib.load("encoder.pkl")
df = pd.read_csv("monthly_fitness_dataset_user200.csv")
le_gender = encoders['le_gender']
le_workout = encoders['le_workout']
le_goal = encoders['le_goal']
le_exercise = encoders['le_exercise']
preprocessor = encoders['preprocessor']
def calculate_bmi(weight_kg, height_cm):
return weight_kg / ((height_cm / 100) ** 2)
def get_meal_plan(week, day):
filtered = df[(df['Week'] == week) & (df['Day'] == day)]
if not filtered.empty:
row = filtered.iloc[0]
return OrderedDict([
("Breakfast", {"Meal": row["Breakfast"], "Calories": int(row["Calories_Breakfast"])}),
("Snack_1", {"Meal": row["Snack_1"], "Calories": int(row["Calories_Snack_1"])}),
("Lunch", {"Meal": row["Lunch"], "Calories": int(row["Calories_Lunch"])}),
("Snack_2", {"Meal": row["Snack_2"], "Calories": int(row["Calories_Snack_2"])}),
("Dinner", {"Meal": row["Dinner"], "Calories": int(row["Calories_Dinner"])}),
])
return OrderedDict()
def get_exercise(week, day):
filtered = df[(df['Week'] == week) & (df['Day'] == day)]
exercises = []
seen = set()
if not filtered.empty:
for _, row in filtered.iterrows():
try:
exercise_name = le_exercise.inverse_transform([row['Exercise_Name']])[0]
except:
exercise_name = row['Exercise_Name']
exercise_key = (
exercise_name,
row["Exercise_Description"],
row["Exercise_Duration"]
)
if exercise_key not in seen:
seen.add(exercise_key)
exercises.append({
"Exercise_Name": exercise_name,
"Exercise_Description": row["Exercise_Description"],
"Exercise_Duration": row["Exercise_Duration"]
})
return exercises
def recommend(choice, gender, age, height_cm, weight_kg, workout_history, goal, week, day):
try:
user_input = {
'Gender': le_gender.transform([gender])[0],
'Age': age,
'Height_cm': height_cm,
'Weight_kg': weight_kg,
'Workout_History': le_workout.transform([workout_history])[0],
'Goal': le_goal.transform([goal])[0],
'Week': week,
'Day': day
}
user_input['BMI'] = calculate_bmi(weight_kg, height_cm)
user_df = pd.DataFrame([user_input])
user_X = preprocessor.transform(user_df)
food_model.predict(user_X)
exercise_model.predict(user_X)
if choice == "meal":
meal_plan = get_meal_plan(week, day)
return {
"Meal_Plan": meal_plan,
"Total_Calories": sum(meal["Calories"] for meal in meal_plan.values())
}
elif choice == "exercise":
return {"Exercises": get_exercise(week, day)}
else:
return {"error": "Invalid choice. Must be 'meal' or 'exercise'"}
except Exception as e:
return {"error": str(e)}
# Gradio interface
demo = gr.Interface(
fn=recommend,
inputs=[
gr.Radio(choices=["meal", "exercise"], label="Choice"),
gr.Radio(choices=["Male", "Female"], label="Gender"),
gr.Slider(10, 80, step=1, label="Age"),
gr.Slider(100, 220, step=1, label="Height (cm)"),
gr.Slider(30, 200, step=1, label="Weight (kg)"),
gr.Dropdown(choices=le_workout.classes_.tolist(), label="Workout History"),
gr.Dropdown(choices=le_goal.classes_.tolist(), label="Goal"),
gr.Slider(1, 4, step=1, label="Week"),
gr.Slider(1, 7, step=1, label="Day")
],
outputs=gr.JSON(label="Recommendation"),
title="Fitness Meal & Exercise Recommendation System",
description="Select your info and receive a personalized meal plan or exercise for the chosen week & day."
)
if __name__ == "__main__":
demo.launch()