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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -55
app.py CHANGED
@@ -3,31 +3,48 @@ import base64
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
- encoded_image = base64.b64encode(image_bytes).decode("utf-8")
13
- dish_name = ""
 
 
 
 
14
 
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 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'.",
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
 
32
  return dish_name.strip()
33
 
@@ -88,7 +105,7 @@ def generate_diet_plan(dish_name, calorie_intake_per_day, goal):
88
 
89
  Provide the response in the following format:
90
  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").
91
- 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.
92
  """
93
  response = client1.chat_completion(
94
  model="meta-llama/Meta-Llama-3-8B-Instruct",
@@ -104,7 +121,6 @@ st.title("AI Diet Planner")
104
  # Sidebar navigation to switch between the app and the user guide
105
  menu = st.sidebar.selectbox("Menu", ["App", "User Guide"])
106
 
107
- # If the user selects the app, show the existing app
108
  if menu == "App":
109
  # Sidebar for user input
110
  st.sidebar.title("User Input")
@@ -117,48 +133,22 @@ if menu == "App":
117
  activity_level = st.sidebar.selectbox("Activity level", ["sedentary", "light", "moderate", "active", "very active"])
118
  time_frame = st.sidebar.number_input("Time frame to achieve goal (months)", min_value=1)
119
 
120
- # Submit button
121
- submit = st.sidebar.button("Submit")
122
-
123
- # Process the image and calculate metrics upon submission
124
- if submit:
125
  if image_file:
126
  st.write("### Results")
127
  image_bytes = image_file.read()
128
 
129
- # Step 1: Identify the dish
130
  dish_name = identify_dish(image_bytes)
131
- st.markdown("<hr>", unsafe_allow_html=True)
132
- st.write("#### Dish Name Identified:")
133
- st.markdown(f"<div style='background-color: #d4edda; color: #155724; padding: 10px; border-radius: 10px;'>{dish_name}</div>", unsafe_allow_html=True)
134
-
135
- # Step 2: Perform Calculations
136
- metrics = calculate_metrics(age, gender, height_cm, weight_kg, weight_goal, activity_level, time_frame)
137
- st.markdown("<hr>", unsafe_allow_html=True)
138
- st.write("#### Metrics Calculated:")
139
- st.markdown(f"""
140
- <div style='background-color: #f8d7da; color: #721c24; padding: 10px; border-radius: 10px;'>
141
- <p><b>Your BMI:</b> {metrics['BMI']:.2f}</p>
142
- <p><b>Your BMR(Basal metabolic rate):</b> {metrics['BMR']:.2f} calories</p>
143
- <p><b>Your TDEE(Total Daily Energy Expenditure):</b> {metrics['TDEE']:.2f} calories</p>
144
- <p><b>Ideal Body Weight (IBW):</b> {metrics['IBW']:.2f} kg</p>
145
- <p><b>Daily Caloric Needs:</b> {metrics['Daily Caloric Needs']:.2f} calories</p>
146
- </div>
147
- """, unsafe_allow_html=True)
148
-
149
- # Step 3: Generate diet plan
150
- diet_plan = generate_diet_plan(dish_name, metrics["Daily Caloric Needs"], weight_goal)
151
- st.markdown("<hr>", unsafe_allow_html=True)
152
- st.write("#### Diet Plan Based on Dish & Goal:")
153
- st.markdown(f"<div style='background-color: #d1ecf1; color: #0c5460; padding: 10px; border-radius: 10px;'>{diet_plan}</div>", unsafe_allow_html=True)
154
-
155
  else:
156
- st.error("Please upload a valid image in JPEG, PNG, JPG, or GIF format.")
157
-
158
- # If the user selects the User Guide, show a detailed guide about the app
159
  elif menu == "User Guide":
160
  st.write("## AI Diet Planner User Guide")
161
-
162
  st.markdown("""
163
  Welcome to the **AI Diet Planner**! This tool helps you calculate various fitness metrics and suggests personalized diet plans.
164
 
 
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
 
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
  # 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
  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