AlaaElsayed commited on
Commit
dc1e3fb
·
verified ·
1 Parent(s): 517be57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -128
app.py CHANGED
@@ -7,15 +7,15 @@ from collections import OrderedDict
7
  food_model = joblib.load("goal_classifier.pkl")
8
  exercise_model = joblib.load("exercise_classifier.pkl")
9
  encoders = joblib.load("encoder.pkl")
10
- df = pd.read_csv("fitness_meal_plan_with_exercises.csv")
11
 
12
- # Load individual encoders
13
- le_gender = encoders['gender']
14
- le_workout = encoders['workout']
15
- le_goal = encoders['goal']
16
- le_exercise = encoders['exercise']
17
  preprocessor = encoders['preprocessor']
18
 
 
19
  def calculate_bmi(weight_kg, height_cm):
20
  return weight_kg / ((height_cm / 100) ** 2)
21
 
@@ -34,18 +34,34 @@ def get_meal_plan(week, day):
34
 
35
  def get_exercise(week, day):
36
  filtered = df[(df['Week'] == week) & (df['Day'] == day)]
 
 
 
37
  if not filtered.empty:
38
- row = filtered.iloc[0]
39
- try:
40
- row['Exercise_Name'] = le_exercise.inverse_transform([row['Exercise_Name']])[0]
41
- except:
42
- pass
43
- return row[['Exercise_Name', 'Exercise_Description', 'Exercise_Duration']].to_dict()
44
- return {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  def recommend(choice, gender, age, height_cm, weight_kg, workout_history, goal, week, day):
47
  try:
48
- # Encode inputs
49
  user_input = {
50
  'Gender': le_gender.transform([gender])[0],
51
  'Age': age,
@@ -59,15 +75,12 @@ def recommend(choice, gender, age, height_cm, weight_kg, workout_history, goal,
59
 
60
  user_input['BMI'] = calculate_bmi(weight_kg, height_cm)
61
 
62
- # Prepare for prediction
63
  user_df = pd.DataFrame([user_input])
64
  user_X = preprocessor.transform(user_df)
65
 
66
- # Optionally use models (if needed for future logic)
67
  food_model.predict(user_X)
68
  exercise_model.predict(user_X)
69
 
70
- # Output
71
  if choice == "meal":
72
  meal_plan = get_meal_plan(week, day)
73
  return {
@@ -75,7 +88,7 @@ def recommend(choice, gender, age, height_cm, weight_kg, workout_history, goal,
75
  "Total_Calories": sum(meal["Calories"] for meal in meal_plan.values())
76
  }
77
  elif choice == "exercise":
78
- return {"Exercise": get_exercise(week, day)}
79
  else:
80
  return {"error": "Invalid choice. Must be 'meal' or 'exercise'"}
81
  except Exception as e:
@@ -103,116 +116,6 @@ demo = gr.Interface(
103
  if __name__ == "__main__":
104
  demo.launch()
105
 
106
-
107
-
108
- # import gradio as gr
109
- # import pandas as pd
110
- # import joblib
111
- # from collections import OrderedDict
112
-
113
- # # Load models
114
- # food_model = joblib.load("goal_classifier.pkl")
115
- # exercise_model = joblib.load("exercise_classifier.pkl")
116
-
117
- # # Load individual encoders & preprocessor
118
- # le_gender = joblib.load("le_gender.pkl")
119
- # le_workout = joblib.load("le_workout.pkl")
120
- # le_goal = joblib.load("le_goal.pkl")
121
- # le_exercise = joblib.load("exercise.pkl")
122
- # preprocessor = joblib.load("preprocessor.pkl")
123
-
124
- # # Load dataset
125
- # df = pd.read_csv("fitness_meal_plan_with_exercises.csv")
126
-
127
- # # Reverse map exercise ID to name
128
- # exercise_reverse_mapping = {v: k for k, v in le_exercise.items()}
129
-
130
- # def calculate_bmi(weight_kg, height_cm):
131
- # return weight_kg / ((height_cm / 100) ** 2)
132
-
133
- # def get_meal_plan(week, day):
134
- # filtered = df[(df['Week'] == week) & (df['Day'] == day)]
135
- # if not filtered.empty:
136
- # row = filtered.iloc[0]
137
- # return OrderedDict([
138
- # ("Breakfast", {"Meal": row["Breakfast"], "Calories": int(row["Calories_Breakfast"])}),
139
- # ("Snack_1", {"Meal": row["Snack_1"], "Calories": int(row["Calories_Snack_1"])}),
140
- # ("Lunch", {"Meal": row["Lunch"], "Calories": int(row["Calories_Lunch"])}),
141
- # ("Snack_2", {"Meal": row["Snack_2"], "Calories": int(row["Calories_Snack_2"])}),
142
- # ("Dinner", {"Meal": row["Dinner"], "Calories": int(row["Calories_Dinner"])}),
143
- # ])
144
- # return OrderedDict()
145
-
146
- # def get_exercise(week, day):
147
- # filtered = df[(df['Week'] == week) & (df['Day'] == day)]
148
- # if not filtered.empty:
149
- # row = filtered.iloc[0]
150
- # exercise_id = row['Exercise_ID']
151
- # exercise_name = exercise_reverse_mapping.get(exercise_id, "Unknown Exercise")
152
- # return {
153
- # "Exercise_Name": exercise_name,
154
- # "Exercise_Description": row["Exercise_Description"],
155
- # "Exercise_Duration": row["Exercise_Duration"]
156
- # }
157
- # return {}
158
-
159
- # def recommend(choice, gender, age, height_cm, weight_kg, workout_history, goal, week, day):
160
- # try:
161
- # user_input = {
162
- # 'Gender': le_gender.transform([gender])[0],
163
- # 'Age': age,
164
- # 'Height_cm': height_cm,
165
- # 'Weight_kg': weight_kg,
166
- # 'Workout_History': le_workout.transform([workout_history])[0],
167
- # 'Goal': le_goal.transform([goal])[0],
168
- # 'Week': week,
169
- # 'Day': day
170
- # }
171
-
172
- # user_input['BMI'] = calculate_bmi(weight_kg, height_cm)
173
-
174
- # # Prepare for prediction
175
- # user_df = pd.DataFrame([user_input])
176
- # user_X = preprocessor.transform(user_df)
177
-
178
- # # Predict (not used yet, can be incorporated)
179
- # _ = food_model.predict(user_X)
180
- # _ = exercise_model.predict(user_X)
181
-
182
- # if choice == "meal":
183
- # meal_plan = get_meal_plan(week, day)
184
- # return {
185
- # "Meal_Plan": meal_plan,
186
- # "Total_Calories": sum(meal["Calories"] for meal in meal_plan.values())
187
- # }
188
- # elif choice == "exercise":
189
- # return {"Exercise": get_exercise(week, day)}
190
- # else:
191
- # return {"error": "Invalid choice. Must be 'meal' or 'exercise'"}
192
- # except Exception as e:
193
- # return {"error": str(e)}
194
-
195
- # # Gradio interface
196
- # demo = gr.Interface(
197
- # fn=recommend,
198
- # inputs=[
199
- # gr.Radio(choices=["meal", "exercise"], label="Choice"),
200
- # gr.Radio(choices=["Male", "Female"], label="Gender"),
201
- # gr.Slider(10, 80, step=1, label="Age"),
202
- # gr.Slider(100, 220, step=1, label="Height (cm)"),
203
- # gr.Slider(30, 200, step=1, label="Weight (kg)"),
204
- # gr.Dropdown(choices=le_workout.classes_.tolist(), label="Workout History"),
205
- # gr.Dropdown(choices=le_goal.classes_.tolist(), label="Goal"),
206
- # gr.Slider(1, 4, step=1, label="Week"),
207
- # gr.Slider(1, 7, step=1, label="Day")
208
- # ],
209
- # outputs=gr.JSON(label="Recommendation"),
210
- # title="Fitness Meal & Exercise Recommendation System",
211
- # description="Select your details to receive a personalized meal or exercise plan for the selected week and day."
212
- # )
213
-
214
- # if __name__ == "__main__":
215
- # demo.launch()
216
 
217
 
218
 
 
7
  food_model = joblib.load("goal_classifier.pkl")
8
  exercise_model = joblib.load("exercise_classifier.pkl")
9
  encoders = joblib.load("encoder.pkl")
10
+ df = pd.read_csv("/content/monthly_fitness_dataset_user200.csv")
11
 
12
+ le_gender = encoders['le_gender']
13
+ le_workout = encoders['le_workout']
14
+ le_goal = encoders['le_goal']
15
+ le_exercise = encoders['le_exercise']
 
16
  preprocessor = encoders['preprocessor']
17
 
18
+
19
  def calculate_bmi(weight_kg, height_cm):
20
  return weight_kg / ((height_cm / 100) ** 2)
21
 
 
34
 
35
  def get_exercise(week, day):
36
  filtered = df[(df['Week'] == week) & (df['Day'] == day)]
37
+ exercises = []
38
+ seen = set()
39
+
40
  if not filtered.empty:
41
+ for _, row in filtered.iterrows():
42
+ try:
43
+ exercise_name = le_exercise.inverse_transform([row['Exercise_Name']])[0]
44
+ except:
45
+ exercise_name = row['Exercise_Name']
46
+
47
+ exercise_key = (
48
+ exercise_name,
49
+ row["Exercise_Description"],
50
+ row["Exercise_Duration"]
51
+ )
52
+
53
+ if exercise_key not in seen:
54
+ seen.add(exercise_key)
55
+ exercises.append({
56
+ "Exercise_Name": exercise_name,
57
+ "Exercise_Description": row["Exercise_Description"],
58
+ "Exercise_Duration": row["Exercise_Duration"]
59
+ })
60
+
61
+ return exercises
62
 
63
  def recommend(choice, gender, age, height_cm, weight_kg, workout_history, goal, week, day):
64
  try:
 
65
  user_input = {
66
  'Gender': le_gender.transform([gender])[0],
67
  'Age': age,
 
75
 
76
  user_input['BMI'] = calculate_bmi(weight_kg, height_cm)
77
 
 
78
  user_df = pd.DataFrame([user_input])
79
  user_X = preprocessor.transform(user_df)
80
 
 
81
  food_model.predict(user_X)
82
  exercise_model.predict(user_X)
83
 
 
84
  if choice == "meal":
85
  meal_plan = get_meal_plan(week, day)
86
  return {
 
88
  "Total_Calories": sum(meal["Calories"] for meal in meal_plan.values())
89
  }
90
  elif choice == "exercise":
91
+ return {"Exercises": get_exercise(week, day)}
92
  else:
93
  return {"error": "Invalid choice. Must be 'meal' or 'exercise'"}
94
  except Exception as e:
 
116
  if __name__ == "__main__":
117
  demo.launch()
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
 
121