SURESHBEEKHANI commited on
Commit
8d64bf6
Β·
verified Β·
1 Parent(s): 5982e62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -33
app.py CHANGED
@@ -32,7 +32,11 @@ def initialize_api_client():
32
  if not api_key:
33
  st.error("API key not found. Please check the .env configuration.")
34
  st.stop()
35
- return Groq(api_key=api_key)
 
 
 
 
36
 
37
  def encode_image(image_path):
38
  """Convert image file to base64"""
@@ -40,6 +44,10 @@ def encode_image(image_path):
40
  with open(image_path, "rb") as img_file:
41
  return base64.b64encode(img_file.read()).decode("utf-8")
42
  except FileNotFoundError:
 
 
 
 
43
  return ""
44
 
45
  def process_image(uploaded_file):
@@ -55,38 +63,43 @@ def process_image(uploaded_file):
55
 
56
  def generate_pdf(report_text, logo_b64):
57
  """Generate PDF report with nutrition analysis and logo"""
58
- buffer = io.BytesIO()
59
- doc = SimpleDocTemplate(buffer, pagesize=letter)
60
- styles = getSampleStyleSheet()
61
-
62
- # Decode logo image from base64 and resize
63
- logo_data = base64.b64decode(logo_b64)
64
- logo_image = Image.open(io.BytesIO(logo_data))
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
- logo = ReportLabImage(io.BytesIO(logo_data), width=logo_width, height=logo_height)
72
-
73
- # Build PDF content
74
- story = [
75
- logo,
76
- Spacer(1, 12),
77
- Paragraph("<b>Nutrition Analysis Report</b>", styles['Title']),
78
- Spacer(1, 12),
79
- Paragraph(report_text.replace('\n', '<br/>'), styles['BodyText'])
80
- ]
81
-
82
- doc.build(story)
83
- buffer.seek(0)
84
- return buffer
 
 
 
 
85
 
86
  def generate_analysis(uploaded_file, client):
87
  """Generate nutrition analysis using AI (Groq API)"""
88
  base64_image, img_format = process_image(uploaded_file)
89
  if not base64_image:
 
90
  return None
91
 
92
  image_url = f"data:image/{img_format.lower()};base64,{base64_image}"
@@ -118,7 +131,7 @@ def generate_analysis(uploaded_file, client):
118
  )
119
  return response.choices[0].message.content
120
  except Exception as e:
121
- st.error(f"API communication error: {e}")
122
  return None
123
 
124
  # ======================
@@ -130,6 +143,10 @@ def display_main_interface():
130
  logo_b64 = encode_image("src/logo.png")
131
 
132
  # Display logo and title
 
 
 
 
133
  st.markdown(f"""
134
  <div style="text-align: center;">
135
  <img src="data:image/png;base64,{logo_b64}" width="100">
@@ -147,12 +164,15 @@ def display_main_interface():
147
  # Column for download button
148
  with col1:
149
  pdf_report = generate_pdf(st.session_state.analysis_result, logo_b64)
150
- st.download_button("πŸ“„ Download Nutrition Report", data=pdf_report, file_name="nutrition_report.pdf", mime="application/pdf")
 
 
 
151
 
152
  # Column for clear button
153
  with col2:
154
  if st.button("Clear Analysis πŸ—‘οΈ"):
155
- st.session_state.pop('analysis_result')
156
  st.rerun()
157
 
158
  if st.session_state.get('analysis_result'):
@@ -170,8 +190,11 @@ def render_sidebar(client):
170
  if st.button("Analyze Meal 🍽️"):
171
  with st.spinner("Analyzing image..."):
172
  report = generate_analysis(uploaded_file, client)
173
- st.session_state.analysis_result = report
174
- st.rerun()
 
 
 
175
 
176
  # ======================
177
  # APPLICATION ENTRYPOINT
 
32
  if not api_key:
33
  st.error("API key not found. Please check the .env configuration.")
34
  st.stop()
35
+ try:
36
+ return Groq(api_key=api_key)
37
+ except Exception as e:
38
+ st.error(f"Error initializing API client: {e}")
39
+ st.stop()
40
 
41
  def encode_image(image_path):
42
  """Convert image file to base64"""
 
44
  with open(image_path, "rb") as img_file:
45
  return base64.b64encode(img_file.read()).decode("utf-8")
46
  except FileNotFoundError:
47
+ st.error(f"Error: Image file '{image_path}' not found.")
48
+ return ""
49
+ except Exception as e:
50
+ st.error(f"Error encoding image '{image_path}': {e}")
51
  return ""
52
 
53
  def process_image(uploaded_file):
 
63
 
64
  def generate_pdf(report_text, logo_b64):
65
  """Generate PDF report with nutrition analysis and logo"""
66
+ try:
67
+ buffer = io.BytesIO()
68
+ doc = SimpleDocTemplate(buffer, pagesize=letter)
69
+ styles = getSampleStyleSheet()
70
+
71
+ # Decode logo image from base64 and resize
72
+ logo_data = base64.b64decode(logo_b64)
73
+ logo_image = Image.open(io.BytesIO(logo_data))
74
+ logo_width, logo_height = logo_image.size
75
+ logo_aspect = logo_height / logo_width
76
+ max_logo_width = 150 # Adjust as needed
77
+ logo_width = min(logo_width, max_logo_width)
78
+ logo_height = int(logo_width * logo_aspect)
79
+
80
+ logo = ReportLabImage(io.BytesIO(logo_data), width=logo_width, height=logo_height)
81
+
82
+ # Build PDF content
83
+ story = [
84
+ logo,
85
+ Spacer(1, 12),
86
+ Paragraph("<b>Nutrition Analysis Report</b>", styles['Title']),
87
+ Spacer(1, 12),
88
+ Paragraph(report_text.replace('\n', '<br/>'), styles['BodyText'])
89
+ ]
90
+
91
+ doc.build(story)
92
+ buffer.seek(0)
93
+ return buffer
94
+ except Exception as e:
95
+ st.error(f"Error generating PDF: {e}")
96
+ return None
97
 
98
  def generate_analysis(uploaded_file, client):
99
  """Generate nutrition analysis using AI (Groq API)"""
100
  base64_image, img_format = process_image(uploaded_file)
101
  if not base64_image:
102
+ st.error("Failed to process image. Cannot generate analysis.")
103
  return None
104
 
105
  image_url = f"data:image/{img_format.lower()};base64,{base64_image}"
 
131
  )
132
  return response.choices[0].message.content
133
  except Exception as e:
134
+ st.error(f"Error communicating with API: {e}")
135
  return None
136
 
137
  # ======================
 
143
  logo_b64 = encode_image("src/logo.png")
144
 
145
  # Display logo and title
146
+ if not logo_b64:
147
+ st.error("Logo image not found or failed to encode.")
148
+ return
149
+
150
  st.markdown(f"""
151
  <div style="text-align: center;">
152
  <img src="data:image/png;base64,{logo_b64}" width="100">
 
164
  # Column for download button
165
  with col1:
166
  pdf_report = generate_pdf(st.session_state.analysis_result, logo_b64)
167
+ if pdf_report:
168
+ st.download_button("πŸ“„ Download Nutrition Report", data=pdf_report, file_name="nutrition_report.pdf", mime="application/pdf")
169
+ else:
170
+ st.error("Failed to generate PDF report.")
171
 
172
  # Column for clear button
173
  with col2:
174
  if st.button("Clear Analysis πŸ—‘οΈ"):
175
+ st.session_state.pop('analysis_result', None)
176
  st.rerun()
177
 
178
  if st.session_state.get('analysis_result'):
 
190
  if st.button("Analyze Meal 🍽️"):
191
  with st.spinner("Analyzing image..."):
192
  report = generate_analysis(uploaded_file, client)
193
+ if report:
194
+ st.session_state.analysis_result = report
195
+ st.rerun()
196
+ else:
197
+ st.error("Failed to generate analysis. Please try again.")
198
 
199
  # ======================
200
  # APPLICATION ENTRYPOINT