SanaAdeel commited on
Commit
6e200e9
·
verified ·
1 Parent(s): 812e5a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -122
app.py CHANGED
@@ -9,75 +9,25 @@ def load_data(file_url):
9
  gdown.download(file_url, file_path, quiet=False)
10
  return pd.read_excel(file_path, engine='openpyxl')
11
 
12
- # Function to generate the weekly menu based on BMI, dietary restriction, and pantry sync
13
- def generate_menu(data, season, outings, dietary_restrictions, bmi, pantry_ingredients):
 
14
  season_data = data[(data['Season'] == season) | (data['Season'] == 'All Seasons')]
15
 
16
- # Define the number of dishes based on BMI
17
- if bmi < 18.5: # Underweight
18
- sub_category_pref = {
19
- 'Sabzi': 3, # More vegetables to increase calorie intake
20
- 'Rice': 2, # More rice to increase carbohydrates
21
- 'Daal': 2, # Protein-rich dals
22
- 'Meat': 3, # More meat for proteins
23
- 'Chicken': 2,
24
- 'Fish': 1
25
- }
26
- elif 18.5 <= bmi < 24.9: # Normal weight
27
- sub_category_pref = {
28
- 'Sabzi': 2,
29
- 'Rice': 2,
30
- 'Daal': 2,
31
- 'Meat': 2,
32
- 'Chicken': 2,
33
- 'Fish': 1
34
- }
35
- elif 25 <= bmi < 29.9: # Overweight
36
- sub_category_pref = {
37
- 'Sabzi': 4, # More vegetables
38
- 'Rice': 1, # Limit rice
39
- 'Daal': 2, # Protein-rich dals
40
- 'Meat': 1, # Limit meat intake
41
- 'Chicken': 3,
42
- 'Fish': 1
43
- }
44
- else: # Obese
45
- sub_category_pref = {
46
- 'Sabzi': 5, # More vegetables
47
- 'Rice': 1, # Very limited rice
48
- 'Daal': 2, # Protein-rich dals
49
- 'Meat': 1, # Very limited meat
50
- 'Chicken': 2,
51
- 'Fish': 1
52
- }
53
 
54
  meals_needed = 14 - outings # Main Courses (14) minus outings
55
 
56
  menu = []
57
- shopping_list = set() # Track missing ingredients
58
 
59
- for sub_category, freq in sub_category_pref.items():
60
  sub_category_dishes = season_data[season_data['Sub-Category'] == sub_category]
61
-
62
- # Filter dishes based on dietary restrictions
63
- if dietary_restrictions == 'Diabetic':
64
- sub_category_dishes = sub_category_dishes[~sub_category_dishes['Ingredients'].str.contains('sugar', case=False, na=False)]
65
- elif dietary_restrictions == 'Gluten-Free':
66
- sub_category_dishes = sub_category_dishes[~sub_category_dishes['Ingredients'].str.contains('gluten', case=False, na=False)]
67
- elif dietary_restrictions == 'Low-Sodium':
68
- sub_category_dishes = sub_category_dishes[~sub_category_dishes['Ingredients'].str.contains('sodium', case=False, na=False)]
69
-
70
- # Sample the dishes based on the user preference
71
- selected_dishes = sub_category_dishes.sample(min(freq, len(sub_category_dishes)))
72
-
73
- # Check the ingredients for the pantry and add missing items to the shopping list
74
- for dish in selected_dishes.to_dict('records'):
75
- ingredients = dish.get('Ingredients', '').split(',')
76
- for ingredient in ingredients:
77
- if ingredient.strip().lower() not in pantry_ingredients:
78
- shopping_list.add(ingredient.strip().lower())
79
-
80
- menu.append(dish)
81
 
82
  menu = menu[:meals_needed]
83
 
@@ -87,42 +37,36 @@ def generate_menu(data, season, outings, dietary_restrictions, bmi, pantry_ingre
87
  side_dishes = data[data['Course'] == 'Side Dish'].sample(2).to_dict('records')
88
  menu.extend(side_dishes)
89
 
90
- # Function to assign weekdays to dishes (for Breakfast, Lunch, and Dinner)
 
 
91
  def assign_weekdays(menu):
92
  weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
93
- menu_with_weekdays = []
94
 
95
- # Assigning the dishes to the weekdays for Breakfast, Lunch, and Dinner
96
  for i, dish in enumerate(menu):
97
  if isinstance(dish, dict):
98
- dish_name = dish["Name"]
99
  else:
100
- dish_name = dish # If it's just a string, take the name directly
101
 
102
- dish_with_day = {"Name": dish_name, "Weekday": weekdays[i % 7]}
103
  menu_with_weekdays.append(dish_with_day)
104
 
105
- return menu_with_weekdays
106
 
107
- menu_df = pd.DataFrame(menu)
108
-
109
- # Apply weekdays to the menu
110
- full_menu_with_weekdays = assign_weekdays(menu_df)
111
 
112
- # Split menu for breakfast, lunch, and dinner (assuming 7 for each)
113
- breakfast_menu = full_menu_with_weekdays[:7]
114
- lunch_menu = full_menu_with_weekdays[7:14]
115
- dinner_menu = full_menu_with_weekdays[14:21]
116
 
117
- # Convert to DataFrame for display
118
- breakfast_menu_df = pd.DataFrame(breakfast_menu)
119
- lunch_menu_df = pd.DataFrame(lunch_menu)
120
- dinner_menu_df = pd.DataFrame(dinner_menu)
121
 
122
- # Calculate total cost (assuming it's available in the data)
123
- total_cost = menu_df["Cost per 4 persons"].sum()
124
 
125
- return breakfast_menu_df, lunch_menu_df, dinner_menu_df, total_cost, shopping_list
126
 
127
  # Function to calculate BMI and recommend diet
128
  def bmi_insights(weight, height_cm):
@@ -130,22 +74,18 @@ def bmi_insights(weight, height_cm):
130
  bmi = weight / (height_m ** 2)
131
 
132
  if bmi < 18.5:
133
- return f"Your BMI is {bmi:.2f}. You are underweight. A diet rich in proteins and healthy fats would be beneficial."
134
  elif 18.5 <= bmi < 24.9:
135
- return f"Your BMI is {bmi:.2f}. You are in the normal weight range. Maintain a balanced diet."
136
  elif 25 <= bmi < 29.9:
137
- return f"Your BMI is {bmi:.2f}. You are overweight. Consider reducing sugar intake."
138
  else:
139
- return f"Your BMI is {bmi:.2f}. You are obese. A calorie-restricted diet with lean proteins is recommended."
140
-
141
- # Function for Smart Inventory Management (Pantry Sync)
142
- def pantry_sync(available_ingredients):
143
- return set(available_ingredients)
144
 
145
  # Main workflow
146
  def main():
147
  st.title("Roz Roz Ka Masla..... Aaj Kya Pakayen!!! ")
148
- st.title("Now generate weekly Menu with BMI Insights and more features")
149
 
150
  # Add food image at the top right of the app
151
  image = Image.open("food_image.jpg") # Ensure you have an image in the same folder
@@ -166,50 +106,25 @@ def main():
166
 
167
  # Main menu generation section
168
  season = st.selectbox("Select the current season", ["Summer", "Winter"])
 
169
 
170
  outings = st.number_input("Enter the number of outings this week", min_value=0, max_value=14, value=0)
171
 
172
- # Dietary restrictions
173
- dietary_restrictions = st.selectbox("Select any dietary restrictions", ["None", "Diabetic", "Gluten-Free", "Low-Sodium"])
174
-
175
- # Pantry Sync
176
- pantry_ingredients_input = st.text_area("Enter available ingredients in your pantry (comma separated)")
177
- if pantry_ingredients_input:
178
- pantry_ingredients = pantry_sync(pantry_ingredients_input.split(','))
179
- else:
180
- pantry_ingredients = set()
181
-
182
  if st.button("Generate Menu"):
183
- bmi = weight / (height_cm / 100) ** 2 # BMI calculation
184
- breakfast_menu, lunch_menu, dinner_menu, total_cost, shopping_list = generate_menu(data, season, outings, dietary_restrictions, bmi, pantry_ingredients)
185
 
186
  st.header("Weekly Menu")
187
-
188
- # Display Breakfast Menu
189
- st.subheader("Breakfast Menu")
190
- for index, row in breakfast_menu.iterrows():
191
- st.write(f"{row['Weekday']}: {row['Name']}")
192
-
193
- # Display Lunch Menu
194
  st.subheader("Lunch Menu")
195
- for index, row in lunch_menu.iterrows():
196
- st.write(f"{row['Weekday']}: {row['Name']}")
197
 
198
- # Display Dinner Menu
199
  st.subheader("Dinner Menu")
200
- for index, row in dinner_menu.iterrows():
201
- st.write(f"{row['Weekday']}: {row['Name']}")
202
 
203
  st.subheader(f"Total Expenditure for the Week: PKR {total_cost}")
204
 
205
- # Shopping list for missing ingredients
206
- if shopping_list:
207
- st.subheader("Shopping List for Missing Ingredients")
208
- st.write(sorted(shopping_list))
209
-
210
  # Save menu to Excel
211
  with pd.ExcelWriter("weekly_menu_split.xlsx") as writer:
212
- breakfast_menu.to_excel(writer, sheet_name="Breakfast", index=False)
213
  lunch_menu.to_excel(writer, sheet_name="Lunch", index=False)
214
  dinner_menu.to_excel(writer, sheet_name="Dinner", index=False)
215
 
 
9
  gdown.download(file_url, file_path, quiet=False)
10
  return pd.read_excel(file_path, engine='openpyxl')
11
 
12
+ # Function to generate the weekly menu
13
+ def generate_menu(data, season, dietary_restriction, outings):
14
+ # Filter data by season and dietary restrictions
15
  season_data = data[(data['Season'] == season) | (data['Season'] == 'All Seasons')]
16
 
17
+ # Apply dietary restrictions (e.g., remove gluten or low-sodium)
18
+ if dietary_restriction == "Gluten-Free":
19
+ season_data = season_data[season_data['Gluten-Free'] == True]
20
+ elif dietary_restriction == "Low-Sodium":
21
+ season_data = season_data[season_data['Sodium'] < 100]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  meals_needed = 14 - outings # Main Courses (14) minus outings
24
 
25
  menu = []
26
+ sub_categories = ['Sabzi', 'Rice', 'Daal', 'Meat', 'Chicken', 'Fish']
27
 
28
+ for sub_category in sub_categories:
29
  sub_category_dishes = season_data[season_data['Sub-Category'] == sub_category]
30
+ menu.extend(sub_category_dishes.sample(min(1, len(sub_category_dishes))).to_dict('records'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  menu = menu[:meals_needed]
33
 
 
37
  side_dishes = data[data['Course'] == 'Side Dish'].sample(2).to_dict('records')
38
  menu.extend(side_dishes)
39
 
40
+ menu_df = pd.DataFrame(menu)
41
+
42
+ # Function to assign weekdays to dishes
43
  def assign_weekdays(menu):
44
  weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
 
45
 
46
+ menu_with_weekdays = []
47
  for i, dish in enumerate(menu):
48
  if isinstance(dish, dict):
49
+ dish_with_day = dish.copy() # Copy the dish dictionary
50
  else:
51
+ dish_with_day = {"Name": dish} # If it's just a string, create a dict with "Name" key
52
 
53
+ dish_with_day["Weekday"] = weekdays[i % 7] # Assign the weekday
54
  menu_with_weekdays.append(dish_with_day)
55
 
56
+ return pd.DataFrame(menu_with_weekdays)
57
 
58
+ lunch_menu = menu_df.iloc[:len(menu_df)//2]
59
+ dinner_menu = menu_df.iloc[len(menu_df)//2:]
 
 
60
 
61
+ total_cost = menu_df["Cost per 4 persons"].sum()
 
 
 
62
 
63
+ lunch_menu = assign_weekdays(lunch_menu)
64
+ dinner_menu = assign_weekdays(dinner_menu)
 
 
65
 
66
+ lunch_menu = lunch_menu[["Name", "Weekday"]]
67
+ dinner_menu = dinner_menu[["Name", "Weekday"]]
68
 
69
+ return lunch_menu, dinner_menu, total_cost
70
 
71
  # Function to calculate BMI and recommend diet
72
  def bmi_insights(weight, height_cm):
 
74
  bmi = weight / (height_m ** 2)
75
 
76
  if bmi < 18.5:
77
+ return f"Your BMI is {bmi:.2f}. You are underweight. A diet rich in proteins and healthy fats would be beneficial. Consider incorporating more calories and nutritious snacks."
78
  elif 18.5 <= bmi < 24.9:
79
+ return f"Your BMI is {bmi:.2f}. You are in the normal weight range. Maintain a balanced diet, including fruits, vegetables, whole grains, and lean proteins."
80
  elif 25 <= bmi < 29.9:
81
+ return f"Your BMI is {bmi:.2f}. You are overweight. A diet with fewer carbs and more lean proteins can help manage your weight. Consider reducing sugar intake."
82
  else:
83
+ return f"Your BMI is {bmi:.2f}. You are obese. A calorie-restricted diet with a focus on whole foods, vegetables, and lean proteins is recommended. Consult a health professional for personalized guidance."
 
 
 
 
84
 
85
  # Main workflow
86
  def main():
87
  st.title("Roz Roz Ka Masla..... Aaj Kya Pakayen!!! ")
88
+ st.title("Now generate weekly Menu with BMI Insights")
89
 
90
  # Add food image at the top right of the app
91
  image = Image.open("food_image.jpg") # Ensure you have an image in the same folder
 
106
 
107
  # Main menu generation section
108
  season = st.selectbox("Select the current season", ["Summer", "Winter"])
109
+ dietary_restriction = st.selectbox("Select your dietary restriction", ["None", "Gluten-Free", "Low-Sodium"])
110
 
111
  outings = st.number_input("Enter the number of outings this week", min_value=0, max_value=14, value=0)
112
 
113
+ # Generate Menu when button is clicked
 
 
 
 
 
 
 
 
 
114
  if st.button("Generate Menu"):
115
+ lunch_menu, dinner_menu, total_cost = generate_menu(data, season, dietary_restriction, outings)
 
116
 
117
  st.header("Weekly Menu")
 
 
 
 
 
 
 
118
  st.subheader("Lunch Menu")
119
+ st.write(lunch_menu)
 
120
 
 
121
  st.subheader("Dinner Menu")
122
+ st.write(dinner_menu)
 
123
 
124
  st.subheader(f"Total Expenditure for the Week: PKR {total_cost}")
125
 
 
 
 
 
 
126
  # Save menu to Excel
127
  with pd.ExcelWriter("weekly_menu_split.xlsx") as writer:
 
128
  lunch_menu.to_excel(writer, sheet_name="Lunch", index=False)
129
  dinner_menu.to_excel(writer, sheet_name="Dinner", index=False)
130