Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -26,74 +26,84 @@ ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg']
|
|
26 |
# ======================
|
27 |
|
28 |
def initialize_api_client():
|
29 |
-
"""Initialize Groq API client
|
30 |
load_dotenv()
|
31 |
api_key = os.getenv("GROQ_API_KEY")
|
32 |
if not api_key:
|
33 |
-
st.error("API key not found. Please
|
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 |
-
"""
|
43 |
try:
|
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):
|
54 |
-
"""Convert uploaded image file to base64 string"""
|
55 |
try:
|
56 |
image = Image.open(uploaded_file)
|
57 |
-
|
58 |
-
|
59 |
-
return
|
60 |
except Exception as e:
|
61 |
st.error(f"Error processing image: {e}")
|
62 |
return None, None
|
63 |
|
|
|
64 |
def generate_pdf(report_text, logo_b64):
|
65 |
-
"""Generate PDF report with
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
|
98 |
def generate_analysis(uploaded_file, client):
|
99 |
"""Generate nutrition analysis using AI (Groq API)"""
|
@@ -138,20 +148,15 @@ def generate_analysis(uploaded_file, client):
|
|
138 |
st.error(f"Error communicating with API: {e}")
|
139 |
return None
|
140 |
|
141 |
-
|
142 |
# ======================
|
143 |
# UI COMPONENTS
|
144 |
# ======================
|
145 |
|
146 |
def display_main_interface():
|
147 |
-
"""Render
|
148 |
logo_b64 = encode_image("src/logo.png")
|
149 |
|
150 |
-
#
|
151 |
-
if not logo_b64:
|
152 |
-
st.error("Logo image not found or failed to encode.")
|
153 |
-
return
|
154 |
-
|
155 |
st.markdown(f"""
|
156 |
<div style="text-align: center;">
|
157 |
<img src="data:image/png;base64,{logo_b64}" width="100">
|
@@ -162,30 +167,28 @@ def display_main_interface():
|
|
162 |
|
163 |
st.markdown("---")
|
164 |
|
165 |
-
# Display analysis results if available
|
166 |
if st.session_state.get('analysis_result'):
|
|
|
167 |
col1, col2 = st.columns([1, 1])
|
168 |
|
169 |
-
#
|
170 |
with col1:
|
171 |
pdf_report = generate_pdf(st.session_state.analysis_result, logo_b64)
|
172 |
-
|
173 |
-
st.download_button("📄 Download Nutrition Report", data=pdf_report, file_name="nutrition_report.pdf", mime="application/pdf")
|
174 |
-
else:
|
175 |
-
st.error("Failed to generate PDF report.")
|
176 |
|
177 |
-
#
|
178 |
with col2:
|
179 |
if st.button("Clear Analysis 🗑️"):
|
180 |
-
st.session_state.pop('analysis_result'
|
181 |
st.rerun()
|
182 |
|
183 |
if st.session_state.get('analysis_result'):
|
184 |
st.markdown("### 🎯 Nutrition Analysis Report")
|
185 |
st.info(st.session_state.analysis_result)
|
186 |
|
|
|
187 |
def render_sidebar(client):
|
188 |
-
"""
|
189 |
with st.sidebar:
|
190 |
st.subheader("Image Upload")
|
191 |
uploaded_file = st.file_uploader("Upload Food Image", type=ALLOWED_FILE_TYPES)
|
@@ -195,18 +198,15 @@ def render_sidebar(client):
|
|
195 |
if st.button("Analyze Meal 🍽️"):
|
196 |
with st.spinner("Analyzing image..."):
|
197 |
report = generate_analysis(uploaded_file, client)
|
198 |
-
|
199 |
-
|
200 |
-
st.rerun()
|
201 |
-
else:
|
202 |
-
st.error("Failed to generate analysis. Please try again.")
|
203 |
|
204 |
# ======================
|
205 |
# APPLICATION ENTRYPOINT
|
206 |
# ======================
|
207 |
|
208 |
def main():
|
209 |
-
"""
|
210 |
client = initialize_api_client()
|
211 |
display_main_interface()
|
212 |
render_sidebar(client)
|
|
|
26 |
# ======================
|
27 |
|
28 |
def initialize_api_client():
|
29 |
+
"""Initialize Groq API client"""
|
30 |
load_dotenv()
|
31 |
api_key = os.getenv("GROQ_API_KEY")
|
32 |
if not api_key:
|
33 |
+
st.error("API key not found. Please verify .env configuration.")
|
|
|
|
|
|
|
|
|
|
|
34 |
st.stop()
|
35 |
+
return Groq(api_key=api_key)
|
36 |
+
|
37 |
|
38 |
def encode_image(image_path):
|
39 |
+
"""Encode an image to base64"""
|
40 |
try:
|
41 |
with open(image_path, "rb") as img_file:
|
42 |
return base64.b64encode(img_file.read()).decode("utf-8")
|
43 |
except FileNotFoundError:
|
|
|
|
|
|
|
|
|
44 |
return ""
|
45 |
|
46 |
+
|
47 |
+
def resize_image(image):
|
48 |
+
"""Resize the image to reduce size before encoding it to base64"""
|
49 |
+
max_width = 800 # Max width in pixels
|
50 |
+
max_height = 800 # Max height in pixels
|
51 |
+
image.thumbnail((max_width, max_height))
|
52 |
+
return image
|
53 |
+
|
54 |
+
|
55 |
+
def compress_image(image):
|
56 |
+
"""Compress the image to JPEG format with a lower quality to reduce size"""
|
57 |
+
buffer = io.BytesIO()
|
58 |
+
image.save(buffer, format="JPEG", quality=70) # Reduce quality to 70%
|
59 |
+
return base64.b64encode(buffer.getvalue()).decode('utf-8')
|
60 |
+
|
61 |
+
|
62 |
def process_image(uploaded_file):
|
63 |
+
"""Convert uploaded image file to base64 string with compression"""
|
64 |
try:
|
65 |
image = Image.open(uploaded_file)
|
66 |
+
image = resize_image(image) # Resize the image to reduce its size
|
67 |
+
base64_image = compress_image(image) # Compress the image
|
68 |
+
return base64_image, "jpeg" # Use 'jpeg' as format
|
69 |
except Exception as e:
|
70 |
st.error(f"Error processing image: {e}")
|
71 |
return None, None
|
72 |
|
73 |
+
|
74 |
def generate_pdf(report_text, logo_b64):
|
75 |
+
"""Generate a PDF report with logo"""
|
76 |
+
buffer = io.BytesIO()
|
77 |
+
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
78 |
+
styles = getSampleStyleSheet()
|
79 |
+
|
80 |
+
# Decode the base64 logo image
|
81 |
+
logo_data = base64.b64decode(logo_b64)
|
82 |
+
logo_image = Image.open(io.BytesIO(logo_data))
|
83 |
+
|
84 |
+
# Resize the logo to fit the page width (you can adjust size if necessary)
|
85 |
+
logo_width, logo_height = logo_image.size
|
86 |
+
logo_aspect = logo_height / logo_width
|
87 |
+
max_logo_width = 150 # Adjust as needed
|
88 |
+
logo_width = min(logo_width, max_logo_width)
|
89 |
+
logo_height = int(logo_width * logo_aspect)
|
90 |
+
|
91 |
+
# Create a ReportLab Image element to add the logo to the PDF
|
92 |
+
logo = ReportLabImage(io.BytesIO(logo_data), width=logo_width, height=logo_height)
|
93 |
+
|
94 |
+
# Build the PDF content
|
95 |
+
story = [
|
96 |
+
logo, # Add the logo at the top of the page
|
97 |
+
Spacer(1, 12), # Space after the logo
|
98 |
+
Paragraph("<b>Nutrition Analysis Report</b>", styles['Title']),
|
99 |
+
Spacer(1, 12),
|
100 |
+
Paragraph(report_text.replace('\n', '<br/>'), styles['BodyText'])
|
101 |
+
]
|
102 |
+
|
103 |
+
doc.build(story)
|
104 |
+
buffer.seek(0)
|
105 |
+
return buffer
|
106 |
+
|
107 |
|
108 |
def generate_analysis(uploaded_file, client):
|
109 |
"""Generate nutrition analysis using AI (Groq API)"""
|
|
|
148 |
st.error(f"Error communicating with API: {e}")
|
149 |
return None
|
150 |
|
|
|
151 |
# ======================
|
152 |
# UI COMPONENTS
|
153 |
# ======================
|
154 |
|
155 |
def display_main_interface():
|
156 |
+
"""Render primary application interface"""
|
157 |
logo_b64 = encode_image("src/logo.png")
|
158 |
|
159 |
+
# HTML with inline styles to change text colors
|
|
|
|
|
|
|
|
|
160 |
st.markdown(f"""
|
161 |
<div style="text-align: center;">
|
162 |
<img src="data:image/png;base64,{logo_b64}" width="100">
|
|
|
167 |
|
168 |
st.markdown("---")
|
169 |
|
|
|
170 |
if st.session_state.get('analysis_result'):
|
171 |
+
# Create two columns: one for download and one for clear button
|
172 |
col1, col2 = st.columns([1, 1])
|
173 |
|
174 |
+
# Left column for the Download button
|
175 |
with col1:
|
176 |
pdf_report = generate_pdf(st.session_state.analysis_result, logo_b64)
|
177 |
+
st.download_button("📄 Download Nutrition Report", data=pdf_report, file_name="nutrition_report.pdf", mime="application/pdf")
|
|
|
|
|
|
|
178 |
|
179 |
+
# Right column for the Clear button
|
180 |
with col2:
|
181 |
if st.button("Clear Analysis 🗑️"):
|
182 |
+
st.session_state.pop('analysis_result')
|
183 |
st.rerun()
|
184 |
|
185 |
if st.session_state.get('analysis_result'):
|
186 |
st.markdown("### 🎯 Nutrition Analysis Report")
|
187 |
st.info(st.session_state.analysis_result)
|
188 |
|
189 |
+
|
190 |
def render_sidebar(client):
|
191 |
+
"""Create sidebar UI elements"""
|
192 |
with st.sidebar:
|
193 |
st.subheader("Image Upload")
|
194 |
uploaded_file = st.file_uploader("Upload Food Image", type=ALLOWED_FILE_TYPES)
|
|
|
198 |
if st.button("Analyze Meal 🍽️"):
|
199 |
with st.spinner("Analyzing image..."):
|
200 |
report = generate_analysis(uploaded_file, client)
|
201 |
+
st.session_state.analysis_result = report
|
202 |
+
st.rerun()
|
|
|
|
|
|
|
203 |
|
204 |
# ======================
|
205 |
# APPLICATION ENTRYPOINT
|
206 |
# ======================
|
207 |
|
208 |
def main():
|
209 |
+
"""Primary application controller"""
|
210 |
client = initialize_api_client()
|
211 |
display_main_interface()
|
212 |
render_sidebar(client)
|