SURESHBEEKHANI commited on
Commit
2513d15
Β·
verified Β·
1 Parent(s): 2dbba91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -57
app.py CHANGED
@@ -6,10 +6,12 @@ import io
6
  from dotenv import load_dotenv
7
  from groq import Groq
8
  from reportlab.lib.pagesizes import letter
9
- from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image as ReportLabImage
10
  from reportlab.lib.styles import getSampleStyleSheet
11
 
 
12
  # CONFIGURATION SETTINGS
 
13
  st.set_page_config(
14
  page_title="Smart Diet Analyzer",
15
  page_icon="🍎",
@@ -19,7 +21,10 @@ st.set_page_config(
19
 
20
  ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
21
 
 
22
  # UTILITY FUNCTIONS
 
 
23
  def initialize_api_client():
24
  """Initialize Groq API client"""
25
  load_dotenv()
@@ -51,35 +56,13 @@ def process_image(uploaded_file):
51
  return None, None
52
 
53
 
54
- def generate_pdf(report_text, logo_b64):
55
- """Generate a PDF report with logo"""
56
  buffer = io.BytesIO()
57
  doc = SimpleDocTemplate(buffer, pagesize=letter)
58
  styles = getSampleStyleSheet()
59
-
60
- # Decode the base64 logo image
61
- logo_data = base64.b64decode(logo_b64)
62
- logo_image = Image.open(io.BytesIO(logo_data))
63
-
64
- # Resize the logo to fit the page width (you can adjust size if necessary)
65
- logo_width, logo_height = logo_image.size
66
- logo_aspect = logo_height / logo_width
67
- max_logo_width = 150 # Adjust as needed
68
- logo_width = min(logo_width, max_logo_width)
69
- logo_height = int(logo_width * logo_aspect)
70
-
71
- # Create a ReportLab Image element to add the logo to the PDF
72
- logo = ReportLabImage(io.BytesIO(logo_data), width=logo_width, height=logo_height)
73
-
74
- # Build the PDF content
75
- story = [
76
- logo, # Add the logo at the top of the page
77
- Spacer(1, 12), # Space after the logo
78
- Paragraph("<b>Nutrition Analysis Report</b>", styles['Title']),
79
- Spacer(1, 12),
80
- Paragraph(report_text.replace('\n', '<br/>'), styles['BodyText'])
81
- ]
82
-
83
  doc.build(story)
84
  buffer.seek(0)
85
  return buffer
@@ -89,56 +72,53 @@ def generate_analysis(uploaded_file, client):
89
  """Generate AI-powered food analysis"""
90
  base64_image, img_format = process_image(uploaded_file)
91
  if not base64_image:
92
- st.error("Image processing failed")
93
  return None
94
 
95
  image_url = f"data:image/{img_format.lower()};base64,{base64_image}"
96
 
97
  try:
98
- st.write("Calling the API...") # Debugging statement
99
-
100
- # Corrected the message format
101
  response = client.chat.completions.create(
102
  model="llama-3.2-11b-vision-preview",
103
  messages=[
104
  {
105
- "role": "system", # System message
106
- "content": """
 
107
  You are an expert nutritionist with advanced image analysis capabilities.
108
- Your task is to analyze the provided image, identify all visible food items, and estimate their calorie content with high accuracy.
 
109
  **Instructions:**
110
- - Identify and list each food item visible in the image.
111
- - For each item, estimate the calorie content based on standard nutritional data, considering portion size, cooking method, and food density.
112
- - Clearly mark any calorie estimate as "approximate" if based on assumptions due to unclear details.
113
- - Calculate and provide the total estimated calories for the entire meal.
 
 
114
  **Output Format:**
115
  - Food Item 1: [Name] – Estimated Calories: [value] kcal
116
  - Food Item 2: [Name] – Estimated Calories: [value] kcal
117
  - ...
118
  - **Total Estimated Calories:** [value] kcal
119
- If the image lacks sufficient detail or is unclear, specify the limitations and include your confidence level in the estimate as a percentage.
120
- """
121
- },
122
- {
123
- "role": "user", # User message
124
- "content": f"Analyze the following image of food: {image_url}" # Include the image URL
125
  }
126
  ],
127
  temperature=0.2,
128
  max_tokens=400,
129
  top_p=0.5
130
  )
131
-
132
- st.write("API response received.") # Debugging statement
133
- analysis_result = response.choices[0].message.content
134
- st.write("Analysis Result: ", analysis_result) # Debugging statement
135
- return analysis_result
136
  except Exception as e:
137
  st.error(f"API communication error: {e}")
138
  return None
139
 
140
-
141
  # UI COMPONENTS
 
 
142
  def display_main_interface():
143
  """Render primary application interface"""
144
  logo_b64 = encode_image("src/logo.png")
@@ -160,7 +140,7 @@ def display_main_interface():
160
 
161
  # Left column for the Download button
162
  with col1:
163
- pdf_report = generate_pdf(st.session_state.analysis_result, logo_b64)
164
  st.download_button("πŸ“„ Download Nutrition Report", data=pdf_report, file_name="nutrition_report.pdf", mime="application/pdf")
165
 
166
  # Right column for the Clear button
@@ -185,14 +165,13 @@ def render_sidebar(client):
185
  if st.button("Analyze Meal 🍽️"):
186
  with st.spinner("Analyzing image..."):
187
  report = generate_analysis(uploaded_file, client)
188
- if report:
189
- st.session_state.analysis_result = report
190
- st.write("Analysis Result:", report) # Debugging line to display result
191
- st.rerun()
192
- else:
193
- st.error("Analysis failed. Please try again.")
194
 
 
195
  # APPLICATION ENTRYPOINT
 
 
196
  def main():
197
  """Primary application controller"""
198
  client = initialize_api_client()
 
6
  from dotenv import load_dotenv
7
  from groq import Groq
8
  from reportlab.lib.pagesizes import letter
9
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
10
  from reportlab.lib.styles import getSampleStyleSheet
11
 
12
+ # ======================
13
  # CONFIGURATION SETTINGS
14
+ # ======================
15
  st.set_page_config(
16
  page_title="Smart Diet Analyzer",
17
  page_icon="🍎",
 
21
 
22
  ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
23
 
24
+ # ======================
25
  # UTILITY FUNCTIONS
26
+ # ======================
27
+
28
  def initialize_api_client():
29
  """Initialize Groq API client"""
30
  load_dotenv()
 
56
  return None, None
57
 
58
 
59
+ def generate_pdf(report_text):
60
+ """Generate a PDF report"""
61
  buffer = io.BytesIO()
62
  doc = SimpleDocTemplate(buffer, pagesize=letter)
63
  styles = getSampleStyleSheet()
64
+ story = [Paragraph("<b>Nutrition Analysis Report</b>", styles['Title']), Spacer(1, 12),
65
+ Paragraph(report_text.replace('\n', '<br/>'), styles['BodyText'])]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  doc.build(story)
67
  buffer.seek(0)
68
  return buffer
 
72
  """Generate AI-powered food analysis"""
73
  base64_image, img_format = process_image(uploaded_file)
74
  if not base64_image:
 
75
  return None
76
 
77
  image_url = f"data:image/{img_format.lower()};base64,{base64_image}"
78
 
79
  try:
 
 
 
80
  response = client.chat.completions.create(
81
  model="llama-3.2-11b-vision-preview",
82
  messages=[
83
  {
84
+ "role": "user",
85
+ "content": [
86
+ {"type": "text", "text": """
87
  You are an expert nutritionist with advanced image analysis capabilities.
88
+ Your task is to analyze the provided image, identify all visible food items, and estimate their calorie content as accurately as possible.
89
+
90
  **Instructions:**
91
+ - List each identified food item separately.
92
+ - Use known nutritional data to provide accurate calorie estimates.
93
+ - Consider portion size, cooking method, and density of food.
94
+ - Clearly specify if an item's calorie count is an estimate due to ambiguity.
95
+ - Provide the total estimated calorie count for the entire meal.
96
+
97
  **Output Format:**
98
  - Food Item 1: [Name] – Estimated Calories: [value] kcal
99
  - Food Item 2: [Name] – Estimated Calories: [value] kcal
100
  - ...
101
  - **Total Estimated Calories:** [value] kcal
102
+
103
+ If the image is unclear or lacks enough details, state the limitations and provide a confidence percentage for the estimation.
104
+ """},
105
+ {"type": "image_url", "image_url": {"url": image_url}}
106
+ ]
 
107
  }
108
  ],
109
  temperature=0.2,
110
  max_tokens=400,
111
  top_p=0.5
112
  )
113
+ return response.choices[0].message.content
 
 
 
 
114
  except Exception as e:
115
  st.error(f"API communication error: {e}")
116
  return None
117
 
118
+ # ======================
119
  # UI COMPONENTS
120
+ # ======================
121
+
122
  def display_main_interface():
123
  """Render primary application interface"""
124
  logo_b64 = encode_image("src/logo.png")
 
140
 
141
  # Left column for the Download button
142
  with col1:
143
+ pdf_report = generate_pdf(st.session_state.analysis_result)
144
  st.download_button("πŸ“„ Download Nutrition Report", data=pdf_report, file_name="nutrition_report.pdf", mime="application/pdf")
145
 
146
  # Right column for the Clear button
 
165
  if st.button("Analyze Meal 🍽️"):
166
  with st.spinner("Analyzing image..."):
167
  report = generate_analysis(uploaded_file, client)
168
+ st.session_state.analysis_result = report
169
+ st.rerun()
 
 
 
 
170
 
171
+ # ======================
172
  # APPLICATION ENTRYPOINT
173
+ # ======================
174
+
175
  def main():
176
  """Primary application controller"""
177
  client = initialize_api_client()