Santhosh54321 commited on
Commit
70e1d58
·
verified ·
1 Parent(s): 8d0cc26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -55
app.py CHANGED
@@ -11,29 +11,27 @@ def identify_dish(image_bytes):
11
  encoded_image = base64.b64encode(image_bytes).decode("utf-8")
12
  dish_name = ""
13
 
14
- try:
15
- for message in client.chat_completion(
16
- model="meta-llama/Llama-3.2-11B-Vision-Instruct",
17
- messages=[
18
- {
19
- "role": "You are a food identification expert who identifies dishes from images. Your task is to strictly return the names of the dishes present in the image. Only return the dish names if you have high Confidence Level and without additional explanation or description.",
20
- "content": [
21
- {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}" }},
22
- {"type": "text", "text": "Identify the dishes in the image and return only the names of the dishes."},
23
- ],
24
- }
25
- ],
26
- max_tokens=70,
27
- stream=True,
28
- ):
29
- if message.choices[0].delta.content:
30
- dish_name += message.choices[0].delta.content
31
- except:
32
- st.error("Error processing the image. Please upload a valid image.")
33
  return dish_name.strip()
34
 
35
- # 2. Function to calculate metrics
36
- def calculate_metrics(age, gender, height_cm, weight_kg, weight_goal, activity_level):
37
  bmi = weight_kg / ((height_cm / 100) ** 2)
38
 
39
  if gender == "male":
@@ -86,6 +84,7 @@ def generate_diet_plan(dish_name, calorie_intake_per_day, goal):
86
  - Dish Name: {dish_name}
87
  - Caloric Intake per Day: {calorie_intake_per_day} calories
88
  - Goal: {goal}
 
89
  """
90
  response = client.chat_completion(
91
  model="meta-llama/Meta-Llama-3-8B-Instruct",
@@ -95,7 +94,10 @@ def generate_diet_plan(dish_name, calorie_intake_per_day, goal):
95
 
96
  return response.choices[0].message.content
97
 
98
- # Streamlit Sidebar for user input
 
 
 
99
  st.sidebar.title("User Input")
100
  image_file = st.sidebar.file_uploader("Upload an image of the dish", type=["jpeg", "png"])
101
  age = st.sidebar.number_input("Enter your age", min_value=1)
@@ -106,47 +108,49 @@ weight_goal = st.sidebar.selectbox("Weight goal", ["loss", "gain", "maintain"])
106
  activity_level = st.sidebar.selectbox("Activity level", ["sedentary", "light", "moderate", "active", "very active"])
107
  time_frame = st.sidebar.number_input("Time frame to achieve goal (months)", min_value=1)
108
 
109
- # Submit Button
110
- if st.sidebar.button("Submit"):
 
 
 
111
  if image_file:
112
- # Step 1: Identify the dish
113
  image_bytes = image_file.read()
 
 
114
  dish_name = identify_dish(image_bytes)
115
- if dish_name:
116
- st.write("### Results")
117
- st.divider()
118
- st.write("**Dish Name Identified:**")
119
- st.success(dish_name)
120
-
121
- # Step 2: Perform Calculations
122
- metrics = calculate_metrics(age, gender, height_cm, weight_kg, weight_goal, activity_level)
123
- st.divider()
124
- st.write("**Calculated Metrics:**")
125
- st.write(f"**BMI:** {metrics['BMI']:.2f}")
126
- st.write(f"**BMR:** {metrics['BMR']:.2f} calories")
127
- st.write(f"**TDEE:** {metrics['TDEE']:.2f} calories")
128
- st.write(f"**Ideal Body Weight:** {metrics['IBW']:.2f} kg")
129
- st.write(f"**Daily Caloric Needs:** {metrics['Daily Caloric Needs']:.2f} calories")
130
-
131
- # Step 3: Generate Diet Plan
132
- st.divider()
133
- st.write("**Diet Plan Based on Dish & Goal:**")
134
- diet_plan = generate_diet_plan(dish_name, metrics["Daily Caloric Needs"], weight_goal)
135
- st.info(diet_plan)
136
- else:
137
- st.error("Unable to identify the dish. Please try again with a different image.")
 
138
  else:
139
- st.error("Please upload an image of the dish.")
140
 
141
- # CSS for styling
142
  st.markdown("""
143
  <style>
144
  .stButton button { background-color: #4CAF50; color: white; }
145
- .stAlert { background-color: #f9f9f9; border: 1px solid #ddd; padding: 10px; }
146
  .stContainer { border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; }
147
- .stSuccess { background-color: #e8f5e9; }
148
- .stInfo { background-color: #e3f2fd; }
149
- .stError { background-color: #ffebee; }
150
  </style>
151
  """, unsafe_allow_html=True)
152
-
 
11
  encoded_image = base64.b64encode(image_bytes).decode("utf-8")
12
  dish_name = ""
13
 
14
+ for message in client.chat_completion(
15
+ model="meta-llama/Llama-3.2-11B-Vision-Instruct",
16
+ messages=[
17
+ {
18
+ "role": "You are a food identification expert who identifies dishes from images. Your task is to strictly return the names of the dishes present in the image. Only return the dish names if you have high Confidence Level and without additional explanation or description.",
19
+ "content": [
20
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}" }},
21
+ {"type": "text", "text": "Identify the dishes in the image and return only the names of the dishes."},
22
+ ],
23
+ }
24
+ ],
25
+ max_tokens=70,
26
+ stream=True,
27
+ ):
28
+ if message.choices[0].delta.content:
29
+ dish_name += message.choices[0].delta.content
30
+
 
 
31
  return dish_name.strip()
32
 
33
+ # 2. Function to get user inputs and calculate daily caloric needs
34
+ def calculate_metrics(age, gender, height_cm, weight_kg, weight_goal, activity_level, time_frame_months):
35
  bmi = weight_kg / ((height_cm / 100) ** 2)
36
 
37
  if gender == "male":
 
84
  - Dish Name: {dish_name}
85
  - Caloric Intake per Day: {calorie_intake_per_day} calories
86
  - Goal: {goal}
87
+
88
  """
89
  response = client.chat_completion(
90
  model="meta-llama/Meta-Llama-3-8B-Instruct",
 
94
 
95
  return response.choices[0].message.content
96
 
97
+ # Streamlit App Title
98
+ st.title("AI Diet Planner")
99
+
100
+ # Sidebar for user input
101
  st.sidebar.title("User Input")
102
  image_file = st.sidebar.file_uploader("Upload an image of the dish", type=["jpeg", "png"])
103
  age = st.sidebar.number_input("Enter your age", min_value=1)
 
108
  activity_level = st.sidebar.selectbox("Activity level", ["sedentary", "light", "moderate", "active", "very active"])
109
  time_frame = st.sidebar.number_input("Time frame to achieve goal (months)", min_value=1)
110
 
111
+ # Submit button
112
+ submit = st.sidebar.button("Submit")
113
+
114
+ # Process the image and calculate metrics upon submission
115
+ if submit:
116
  if image_file:
117
+ st.write("### Results")
118
  image_bytes = image_file.read()
119
+
120
+ # Step 1: Identify the dish
121
  dish_name = identify_dish(image_bytes)
122
+ st.markdown("<hr>", unsafe_allow_html=True)
123
+ st.write("#### Dish Name Identified:")
124
+ st.markdown(f"<div style='background-color: #d4edda; color: #155724; padding: 10px; border-radius: 10px;'>{dish_name}</div>", unsafe_allow_html=True)
125
+
126
+ # Step 2: Perform Calculations
127
+ metrics = calculate_metrics(age, gender, height_cm, weight_kg, weight_goal, activity_level, time_frame)
128
+ st.markdown("<hr>", unsafe_allow_html=True)
129
+ st.write("#### Metrics Calculated:")
130
+ st.markdown(f"""
131
+ <div style='background-color: #f8d7da; color: #721c24; padding: 10px; border-radius: 10px;'>
132
+ <p><b>Your BMI:</b> {metrics['BMI']:.2f}</p>
133
+ <p><b>Your BMR:</b> {metrics['BMR']:.2f} calories</p>
134
+ <p><b>Your TDEE:</b> {metrics['TDEE']:.2f} calories</p>
135
+ <p><b>Ideal Body Weight (IBW):</b> {metrics['IBW']:.2f} kg</p>
136
+ <p><b>Daily Caloric Needs:</b> {metrics['Daily Caloric Needs']:.2f} calories</p>
137
+ </div>
138
+ """, unsafe_allow_html=True)
139
+
140
+ # Step 3: Generate diet plan
141
+ diet_plan = generate_diet_plan(dish_name, metrics["Daily Caloric Needs"], weight_goal)
142
+ st.markdown("<hr>", unsafe_allow_html=True)
143
+ st.write("#### Diet Plan Based on Dish & Goal:")
144
+ st.markdown(f"<div style='background-color: #d1ecf1; color: #0c5460; padding: 10px; border-radius: 10px;'>{diet_plan}</div>", unsafe_allow_html=True)
145
+
146
  else:
147
+ st.error("Please upload a valid image in JPEG or PNG format.")
148
 
149
+ # CSS styling
150
  st.markdown("""
151
  <style>
152
  .stButton button { background-color: #4CAF50; color: white; }
 
153
  .stContainer { border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; }
154
+ hr { border: 1px solid #e9ecef; margin: 20px 0; }
 
 
155
  </style>
156
  """, unsafe_allow_html=True)