Santhosh1325 commited on
Commit
89c94bf
·
verified ·
1 Parent(s): b4fcdb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -45
app.py CHANGED
@@ -3,48 +3,35 @@ import base64
3
  from huggingface_hub import InferenceClient
4
  import os
5
 
6
- # Initialize Hugging Face Inference client using tokens from environment variables
7
  client = InferenceClient(api_key=os.getenv("HF_API_TOKEN_DISH"))
8
  client1 = InferenceClient(api_key=os.getenv("HF_API_TOKEN_DIET"))
9
 
10
  # 1. Function to identify dish from image
11
  def identify_dish(image_bytes):
12
- try:
13
- # Attempt to encode the image to check for format issues
14
- encoded_image = base64.b64encode(image_bytes).decode("utf-8")
15
- except Exception:
16
- st.error("Invalid image format. Please upload a valid JPEG, PNG, or GIF image.")
17
- return None # Early exit if image encoding fails
18
-
19
  dish_name = ""
20
- try:
21
- for message in client.chat_completion(
22
- model="meta-llama/Llama-3.2-11B-Vision-Instruct",
23
- messages=[
24
- {
25
- "role": "You are a highly specialized food identification AI with extensive knowledge of global cuisines. "
26
- "Your sole task is to accurately identify dishes from images. Adhere strictly to these guidelines:\n"
27
- "1. Analyze the image thoroughly, focusing on ingredients, presentation, and cultural context.\n"
28
- "2. Provide ONLY the name of the main dish or dishes visible. Do not list individual ingredients or components.\n"
29
- "3. Use the most specific and widely recognized name for the dish.\n"
30
- "4. If multiple distinct dishes are present, list them separated by commas.\n"
31
- "5. If you cannot identify a dish with high confidence (>75%), respond with 'Unidentified dish'.\n"
32
- "6. Do not provide any explanations, descriptions, or additional commentary.\n"
33
- "7. Respond in a concise, list-like format.",
34
- "content": [
35
- {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}"}},
36
- {"type": "text", "text": "Identify the dishes in the image and return only the names of the dishes."},
37
- ],
38
- }
39
- ],
40
- max_tokens=70,
41
- stream=True,
42
- ):
43
- if message.choices[0].delta.content:
44
- dish_name += message.choices[0].delta.content
45
- except Exception:
46
- st.error("Error identifying the dish. Please try uploading a different image.")
47
- return None # Early exit if the API call fails
48
 
49
  return dish_name.strip()
50
 
@@ -105,7 +92,7 @@ def generate_diet_plan(dish_name, calorie_intake_per_day, goal):
105
 
106
  Provide the response in the following format:
107
  1. Dish assessment (e.g., "The dish {dish_name} is suitable for your goal" or "The dish {dish_name} is not suitable for your goal, as it is too high in calories for weight goal").
108
- 2. Suggest an Indian diet plan that stays near to the {calorie_intake_per_day}. For each meal (morning, lunch, evening), list the dish name, calorie count, and ingredients required to make it.
109
  """
110
  response = client1.chat_completion(
111
  model="meta-llama/Meta-Llama-3-8B-Instruct",
@@ -121,6 +108,7 @@ st.title("AI Diet Planner")
121
  # Sidebar navigation to switch between the app and the user guide
122
  menu = st.sidebar.selectbox("Menu", ["App", "User Guide"])
123
 
 
124
  if menu == "App":
125
  # Sidebar for user input
126
  st.sidebar.title("User Input")
@@ -133,22 +121,48 @@ if menu == "App":
133
  activity_level = st.sidebar.selectbox("Activity level", ["sedentary", "light", "moderate", "active", "very active"])
134
  time_frame = st.sidebar.number_input("Time frame to achieve goal (months)", min_value=1)
135
 
136
- if st.sidebar.button("Submit"):
 
 
 
 
137
  if image_file:
138
  st.write("### Results")
139
  image_bytes = image_file.read()
140
 
 
141
  dish_name = identify_dish(image_bytes)
142
- if dish_name:
143
- st.write(f"**Dish Name Identified:** {dish_name}")
144
- metrics = calculate_metrics(age, gender, height_cm, weight_kg, weight_goal, activity_level, time_frame)
145
- st.write("**Metrics Calculated:**", metrics)
146
- diet_plan = generate_diet_plan(dish_name, metrics["Daily Caloric Needs"], weight_goal)
147
- st.write("**Diet Plan:**", diet_plan)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  else:
149
- st.error("Please upload a valid image.")
 
 
150
  elif menu == "User Guide":
151
  st.write("## AI Diet Planner User Guide")
 
152
  st.markdown("""
153
  Welcome to the **AI Diet Planner**! This tool helps you calculate various fitness metrics and suggests personalized diet plans.
154
 
 
3
  from huggingface_hub import InferenceClient
4
  import os
5
 
6
+ # Initialize Hugging Face Inference client using token from environment variables
7
  client = InferenceClient(api_key=os.getenv("HF_API_TOKEN_DISH"))
8
  client1 = InferenceClient(api_key=os.getenv("HF_API_TOKEN_DIET"))
9
 
10
  # 1. Function to identify dish from image
11
  def identify_dish(image_bytes):
12
+ try
13
+ encoded_image = base64.b64encode(image_bytes).decode("utf-8")
 
 
 
 
 
14
  dish_name = ""
15
+ except Exception:
16
+ st.error("Invalid image format. Please upload a valid JPEG, PNG, or GIF image.")
17
+ return None
18
+
19
+ for message in client.chat_completion(
20
+ model="meta-llama/Llama-3.2-11B-Vision-Instruct",
21
+ messages=[
22
+ {
23
+ "role": "You are a highly specialized food identification AI with extensive knowledge of global cuisines. Your sole task is to accurately identify dishes from images. Adhere strictly to these guidelines:\n1. Analyze the image thoroughly, focusing on ingredients, presentation, and cultural context.\n2. Provide ONLY the name of the main dish or dishes visible. Do not list individual ingredients or components.\n3. Use the most specific and widely recognized name for the dish.\n4. If multiple distinct dishes are present, list them separated by commas.\n5. If you cannot identify a dish with high confidence (>90%), respond with 'Unidentified dish'.\n6. Do not provide any explanations, descriptions, or additional commentary.\n7. Respond in a concise, list-like format.\nYour response should contain nothing but the dish name(s) or 'Unidentified dish'.",
24
+ "content": [
25
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}" }},
26
+ {"type": "text", "text": "Identify the dishes in the image and return only the names of the dishes."},
27
+ ],
28
+ }
29
+ ],
30
+ max_tokens=70,
31
+ stream=True,
32
+ ):
33
+ if message.choices[0].delta.content:
34
+ dish_name += message.choices[0].delta.content
 
 
 
 
 
 
 
 
35
 
36
  return dish_name.strip()
37
 
 
92
 
93
  Provide the response in the following format:
94
  1. Dish assessment (e.g., "The dish {dish_name} is suitable for your goal" or "The dish {dish_name} is not suitable for your goal, as it is too high in calories for weight goal").
95
+ 2. Suggest an Indian diet plan that stays near to the {calorie_intake_per_day}. For each meal (morning, lunch, evening), list the dish name, calorie count, and ingredients required to make it.And Make it with in 700 Tokens.
96
  """
97
  response = client1.chat_completion(
98
  model="meta-llama/Meta-Llama-3-8B-Instruct",
 
108
  # Sidebar navigation to switch between the app and the user guide
109
  menu = st.sidebar.selectbox("Menu", ["App", "User Guide"])
110
 
111
+ # If the user selects the app, show the existing app
112
  if menu == "App":
113
  # Sidebar for user input
114
  st.sidebar.title("User Input")
 
121
  activity_level = st.sidebar.selectbox("Activity level", ["sedentary", "light", "moderate", "active", "very active"])
122
  time_frame = st.sidebar.number_input("Time frame to achieve goal (months)", min_value=1)
123
 
124
+ # Submit button
125
+ submit = st.sidebar.button("Submit")
126
+
127
+ # Process the image and calculate metrics upon submission
128
+ if submit:
129
  if image_file:
130
  st.write("### Results")
131
  image_bytes = image_file.read()
132
 
133
+ # Step 1: Identify the dish
134
  dish_name = identify_dish(image_bytes)
135
+ st.markdown("<hr>", unsafe_allow_html=True)
136
+ st.write("#### Dish Name Identified:")
137
+ st.markdown(f"<div style='background-color: #d4edda; color: #155724; padding: 10px; border-radius: 10px;'>{dish_name}</div>", unsafe_allow_html=True)
138
+
139
+ # Step 2: Perform Calculations
140
+ metrics = calculate_metrics(age, gender, height_cm, weight_kg, weight_goal, activity_level, time_frame)
141
+ st.markdown("<hr>", unsafe_allow_html=True)
142
+ st.write("#### Metrics Calculated:")
143
+ st.markdown(f"""
144
+ <div style='background-color: #f8d7da; color: #721c24; padding: 10px; border-radius: 10px;'>
145
+ <p><b>Your BMI:</b> {metrics['BMI']:.2f}</p>
146
+ <p><b>Your BMR(Basal metabolic rate):</b> {metrics['BMR']:.2f} calories</p>
147
+ <p><b>Your TDEE(Total Daily Energy Expenditure):</b> {metrics['TDEE']:.2f} calories</p>
148
+ <p><b>Ideal Body Weight (IBW):</b> {metrics['IBW']:.2f} kg</p>
149
+ <p><b>Daily Caloric Needs:</b> {metrics['Daily Caloric Needs']:.2f} calories</p>
150
+ </div>
151
+ """, unsafe_allow_html=True)
152
+
153
+ # Step 3: Generate diet plan
154
+ diet_plan = generate_diet_plan(dish_name, metrics["Daily Caloric Needs"], weight_goal)
155
+ st.markdown("<hr>", unsafe_allow_html=True)
156
+ st.write("#### Diet Plan Based on Dish & Goal:")
157
+ st.markdown(f"<div style='background-color: #d1ecf1; color: #0c5460; padding: 10px; border-radius: 10px;'>{diet_plan}</div>", unsafe_allow_html=True)
158
+
159
  else:
160
+ st.error("Please upload a valid image in JPEG, PNG, JPG, or GIF format.")
161
+
162
+ # If the user selects the User Guide, show a detailed guide about the app
163
  elif menu == "User Guide":
164
  st.write("## AI Diet Planner User Guide")
165
+
166
  st.markdown("""
167
  Welcome to the **AI Diet Planner**! This tool helps you calculate various fitness metrics and suggests personalized diet plans.
168