ankit5566 commited on
Commit
072571e
Β·
verified Β·
1 Parent(s): 75c8f14

Updated app.py to add analysis

Browse files

- Added more options for analysis and suggestions
- Generate graphs
- Analyse historical data and provide suggestions
- Maintain DB history
- Historical Analysis added

Files changed (1) hide show
  1. app.py +443 -66
app.py CHANGED
@@ -9,6 +9,10 @@ import os
9
  import openai
10
  import json
11
  from dotenv import load_dotenv
 
 
 
 
12
 
13
  # Load environment variables
14
  load_dotenv()
@@ -88,19 +92,16 @@ def parse_nutrition_response(response_text):
88
 
89
  def init_db():
90
  """
91
- Initialize database with all required columns.
92
- If table exists, drop it and recreate with the correct schema.
93
  """
94
  try:
95
  conn = sqlite3.connect("nutrition_data.db")
96
  cursor = conn.cursor()
97
 
98
- # Drop existing table if it exists
99
- cursor.execute('''DROP TABLE IF EXISTS records''')
100
-
101
- # Create new table with all required columns
102
- cursor.execute('''CREATE TABLE records (
103
- id INTEGER PRIMARY KEY AUTOINCREMENT,
104
  image BLOB,
105
  timestamp TEXT,
106
  macronutrients TEXT,
@@ -117,7 +118,7 @@ def init_db():
117
  except Exception as e:
118
  st.error(f"Error initializing database: {str(e)}")
119
 
120
- def save_record(image, macronutrients, micronutrients, food_items, improvements, goal):
121
  try:
122
  conn = sqlite3.connect("nutrition_data.db")
123
  cursor = conn.cursor()
@@ -128,19 +129,45 @@ def save_record(image, macronutrients, micronutrients, food_items, improvements,
128
  food_items_json = json.dumps(food_items)
129
  improvements_json = json.dumps(improvements)
130
 
131
- cursor.execute("""
132
- INSERT INTO records (image, timestamp, macronutrients, micronutrients, food_items, improvements, goal)
133
- VALUES (?, ?, ?, ?, ?, ?, ?)
134
- """, (
135
- image,
136
- datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
137
- macronutrients_json,
138
- micronutrients_json,
139
- food_items_json,
140
- improvements_json,
141
- goal
142
- ))
143
- conn.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  conn.close()
145
  except Exception as e:
146
  st.error(f"Error saving to database: {str(e)}")
@@ -224,18 +251,21 @@ def process_image_for_analysis(image, max_size=(800, 800), quality=85):
224
  Returns:
225
  bytes of the processed image
226
  """
227
- # Create a copy to avoid modifying original
228
- img_copy = image.copy()
229
-
230
- # Resize using LANCZOS resampling
231
- img_copy.thumbnail(max_size, Image.LANCZOS)
232
-
233
- # Compress and convert to bytes
234
- image_bytes = io.BytesIO()
235
- img_copy.save(image_bytes, format='JPEG', quality=quality)
236
-
237
- return image_bytes.getvalue()
238
-
 
 
 
239
 
240
  # # Initialize database
241
  init_db()
@@ -243,11 +273,43 @@ init_db()
243
  # # Streamlit UI
244
  st.title("Macronutrient Counter")
245
  st.sidebar.header("Your Goal")
246
- goal = st.sidebar.radio("Select your goal:", ["Maintain weight", "Fat loss", "Weight gain"])
247
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  st.header("Upload Food Image")
249
  uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])
250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
  # Update the main UI section where results are displayed
253
  if uploaded_file:
@@ -258,6 +320,10 @@ if uploaded_file:
258
  st.session_state.image_bytes = None
259
  st.session_state.base64_image = None
260
  st.session_state.last_uploaded_file = uploaded_file.name
 
 
 
 
261
 
262
  image = Image.open(uploaded_file)
263
  st.image(image, caption="Uploaded Image", use_column_width=True)
@@ -266,15 +332,43 @@ if uploaded_file:
266
  if not st.session_state.analysis_done and st.button("Analyze Image"):
267
  with st.spinner("πŸ”„ Analyzing your food image... This may take a few seconds."):
268
  try:
 
 
 
 
 
 
269
  image_bytes = process_image_for_analysis(image)
 
 
 
 
270
  st.session_state.image_bytes = image_bytes
271
  st.session_state.base64_image = base64.b64encode(image_bytes).decode("utf-8")
272
 
273
  # Initial analysis
274
  result = analyze_image_with_image_recognition(image_bytes)
275
  message_content = result.choices[0].message.content
276
- st.session_state.initial_result = parse_nutrition_response(message_content)
 
 
 
277
  st.session_state.analysis_done = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  st.success("βœ… Analysis completed successfully!")
279
  st.rerun()
280
  except Exception as e:
@@ -304,10 +398,8 @@ if uploaded_file:
304
  current_analysis = json.dumps(parsed_result, indent=2)
305
 
306
  prompt_text = f'''Analyze the food items in this image, considering the following user description: '{meal_description}'
307
-
308
  Your previous analysis was:
309
  {current_analysis}
310
-
311
  Please provide a refined analysis based on the user's description and your previous analysis.
312
  Keep the values that seem accurate and adjust only what needs to be changed based on the new information.
313
  Provide the nutritional information in the following JSON format only:
@@ -365,6 +457,10 @@ Provide the nutritional information in the following JSON format only:
365
  st.session_state.initial_result = parsed_result
366
  st.success("Analysis refined successfully!")
367
 
 
 
 
 
368
  except Exception as e:
369
  st.error(f"Error during refinement: {str(e)}")
370
  st.write("Using original analysis results...")
@@ -412,6 +508,144 @@ Provide the nutritional information in the following JSON format only:
412
  st.write(f"- {suggestion}")
413
  st.write("\nContext:")
414
  st.write(parsed_result['improvements']['context'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
 
416
  # Save to database
417
  save_record(
@@ -420,36 +654,179 @@ Provide the nutritional information in the following JSON format only:
420
  parsed_result['micronutrients'],
421
  parsed_result['food_items'],
422
  parsed_result['improvements'],
423
- goal
 
 
424
  )
425
 
426
- # View saved records
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427
  st.header("View Past Records")
428
  if st.button("Show Records"):
429
- conn = sqlite3.connect("nutrition_data.db")
430
- cursor = conn.cursor()
431
- cursor.execute("SELECT timestamp, macronutrients, food_items, goal, image FROM records")
432
- records = cursor.fetchall()
433
- conn.close()
434
-
435
- for record in records:
436
- st.write(f"**Timestamp:** {record[0]}")
437
-
438
- # Parse and display macronutrients
439
- macros = json.loads(record[1])
440
- st.write("**Macronutrients:**")
441
- st.write(f"- Carbohydrates: {macros['carbohydrates']}g")
442
- st.write(f"- Protein: {macros['protein']}g")
443
- st.write(f"- Fat: {macros['fat']}g")
444
 
445
- # Parse and display food items
446
- foods = json.loads(record[2])
447
- st.write("**Foods Identified:**")
448
- for food in foods:
449
- st.write(f"- {food}")
450
 
451
- st.write(f"**Goal:** {record[3]}")
452
- # Display the image
453
- image_data = record[4]
454
- st.image(image_data, caption="Saved Image", use_column_width=True)
455
- st.write("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  import openai
10
  import json
11
  from dotenv import load_dotenv
12
+ import plotly.graph_objects as go
13
+ import plotly.express as px
14
+ import pandas as pd
15
+ from datetime import datetime
16
 
17
  # Load environment variables
18
  load_dotenv()
 
92
 
93
  def init_db():
94
  """
95
+ Initialize database if it doesn't exist.
96
+ Only creates table if it doesn't already exist.
97
  """
98
  try:
99
  conn = sqlite3.connect("nutrition_data.db")
100
  cursor = conn.cursor()
101
 
102
+ # Create table only if it doesn't exist
103
+ cursor.execute('''CREATE TABLE IF NOT EXISTS records (
104
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
 
 
 
105
  image BLOB,
106
  timestamp TEXT,
107
  macronutrients TEXT,
 
118
  except Exception as e:
119
  st.error(f"Error initializing database: {str(e)}")
120
 
121
+ def save_record(image, macronutrients, micronutrients, food_items, improvements, goal, is_refinement, custom_timestamp=None):
122
  try:
123
  conn = sqlite3.connect("nutrition_data.db")
124
  cursor = conn.cursor()
 
129
  food_items_json = json.dumps(food_items)
130
  improvements_json = json.dumps(improvements)
131
 
132
+ # Use custom timestamp if provided, otherwise use current time
133
+ timestamp = custom_timestamp.strftime('%Y-%m-%d %H:%M:%S') if custom_timestamp else datetime.now().strftime('%Y-%m-%d %H:%M:%S')
134
+
135
+ if is_refinement:
136
+ # Update the most recent record instead of creating a new one
137
+ cursor.execute("""
138
+ UPDATE records
139
+ SET macronutrients = ?,
140
+ micronutrients = ?,
141
+ food_items = ?,
142
+ improvements = ?
143
+ WHERE id = (
144
+ SELECT id
145
+ FROM records
146
+ ORDER BY timestamp DESC
147
+ LIMIT 1
148
+ )
149
+ """, (
150
+ macronutrients_json,
151
+ micronutrients_json,
152
+ food_items_json,
153
+ improvements_json
154
+ ))
155
+ else:
156
+ # Insert a new record
157
+ cursor.execute("""
158
+ INSERT INTO records (image, timestamp, macronutrients, micronutrients, food_items, improvements, goal)
159
+ VALUES (?, ?, ?, ?, ?, ?, ?)
160
+ """, (
161
+ image,
162
+ timestamp,
163
+ macronutrients_json,
164
+ micronutrients_json,
165
+ food_items_json,
166
+ improvements_json,
167
+ goal
168
+ ))
169
+
170
+ conn.commit()
171
  conn.close()
172
  except Exception as e:
173
  st.error(f"Error saving to database: {str(e)}")
 
251
  Returns:
252
  bytes of the processed image
253
  """
254
+ try:
255
+ # Create a copy to avoid modifying original
256
+ img_copy = image.copy()
257
+
258
+ # Resize using LANCZOS resampling
259
+ img_copy.thumbnail(max_size, Image.LANCZOS)
260
+
261
+ # Compress and convert to bytes
262
+ image_bytes = io.BytesIO()
263
+ img_copy.save(image_bytes, format='JPEG', quality=quality)
264
+
265
+ return image_bytes.getvalue()
266
+ except Exception as e:
267
+ st.error(f"Error processing image: {str(e)}")
268
+ return None
269
 
270
  # # Initialize database
271
  init_db()
 
273
  # # Streamlit UI
274
  st.title("Macronutrient Counter")
275
  st.sidebar.header("Your Goal")
276
+ goal = st.sidebar.radio(
277
+ "Select your goal:",
278
+ [
279
+ "Maintain weight",
280
+ "Fat loss",
281
+ "Weight gain",
282
+ "Muscle Gain",
283
+ "Pregnancy",
284
+ "Body Building Competition",
285
+ "Marathon Training",
286
+ "Endurance Training",
287
+ "Senior Citizen",
288
+ "Diabetic Patient",
289
+ "Kidney Patient"
290
+ ],
291
+ help="Select your primary health or fitness goal. This will help tailor the nutritional analysis and recommendations to your specific needs."
292
+ )
293
  st.header("Upload Food Image")
294
  uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])
295
 
296
+ # Add time input with default to current time
297
+ col1, col2 = st.columns([2, 1])
298
+ with col1:
299
+ meal_time = st.time_input(
300
+ "Select meal time (optional)",
301
+ value=datetime.now().time(),
302
+ help="Select the time when this meal was consumed. Defaults to current time if not specified."
303
+ )
304
+ with col2:
305
+ meal_date = st.date_input(
306
+ "Select date (optional)",
307
+ value=datetime.now().date(),
308
+ help="Select the date when this meal was consumed. Defaults to today if not specified."
309
+ )
310
+
311
+ # Combine date and time for timestamp
312
+ custom_timestamp = datetime.combine(meal_date, meal_time)
313
 
314
  # Update the main UI section where results are displayed
315
  if uploaded_file:
 
320
  st.session_state.image_bytes = None
321
  st.session_state.base64_image = None
322
  st.session_state.last_uploaded_file = uploaded_file.name
323
+ if 'record_saved' in st.session_state:
324
+ del st.session_state.record_saved
325
+ # Force a rerun to clear displayed results
326
+ st.rerun()
327
 
328
  image = Image.open(uploaded_file)
329
  st.image(image, caption="Uploaded Image", use_column_width=True)
 
332
  if not st.session_state.analysis_done and st.button("Analyze Image"):
333
  with st.spinner("πŸ”„ Analyzing your food image... This may take a few seconds."):
334
  try:
335
+ # Ensure image exists and is valid
336
+ if image is None:
337
+ st.error("Please upload an image first")
338
+ st.stop()
339
+
340
+ # Process image
341
  image_bytes = process_image_for_analysis(image)
342
+ if image_bytes is None:
343
+ st.error("Failed to process image")
344
+ st.stop()
345
+
346
  st.session_state.image_bytes = image_bytes
347
  st.session_state.base64_image = base64.b64encode(image_bytes).decode("utf-8")
348
 
349
  # Initial analysis
350
  result = analyze_image_with_image_recognition(image_bytes)
351
  message_content = result.choices[0].message.content
352
+ parsed_result = parse_nutrition_response(message_content)
353
+
354
+ # Save to session state
355
+ st.session_state.initial_result = parsed_result
356
  st.session_state.analysis_done = True
357
+
358
+ # Save to database only if not already saved
359
+ if 'record_saved' not in st.session_state:
360
+ save_record(
361
+ image_bytes,
362
+ parsed_result['macronutrients'],
363
+ parsed_result['micronutrients'],
364
+ parsed_result['food_items'],
365
+ parsed_result['improvements'],
366
+ goal,
367
+ is_refinement=False,
368
+ custom_timestamp=custom_timestamp
369
+ )
370
+ st.session_state.record_saved = True
371
+
372
  st.success("βœ… Analysis completed successfully!")
373
  st.rerun()
374
  except Exception as e:
 
398
  current_analysis = json.dumps(parsed_result, indent=2)
399
 
400
  prompt_text = f'''Analyze the food items in this image, considering the following user description: '{meal_description}'
 
401
  Your previous analysis was:
402
  {current_analysis}
 
403
  Please provide a refined analysis based on the user's description and your previous analysis.
404
  Keep the values that seem accurate and adjust only what needs to be changed based on the new information.
405
  Provide the nutritional information in the following JSON format only:
 
457
  st.session_state.initial_result = parsed_result
458
  st.success("Analysis refined successfully!")
459
 
460
+
461
+
462
+ st.success("βœ… Analysis refined and saved successfully!")
463
+
464
  except Exception as e:
465
  st.error(f"Error during refinement: {str(e)}")
466
  st.write("Using original analysis results...")
 
508
  st.write(f"- {suggestion}")
509
  st.write("\nContext:")
510
  st.write(parsed_result['improvements']['context'])
511
+
512
+ # Add Past Records Analysis section
513
+ st.write("---")
514
+ st.subheader("πŸ“Š Historical Diet Analysis")
515
+ if st.button("Analyze My Diet History"):
516
+ try:
517
+ conn = sqlite3.connect("nutrition_data.db")
518
+ cursor = conn.cursor()
519
+ cursor.execute("SELECT macronutrients, micronutrients, food_items, goal, timestamp FROM records ORDER BY timestamp DESC")
520
+ past_records = cursor.fetchall()
521
+ conn.close()
522
+
523
+ if not past_records:
524
+ st.info("No past records found. Add more meals to get a detailed analysis!")
525
+ else:
526
+ # Prepare data for analysis
527
+ analysis_prompt = {
528
+ "records": [],
529
+ "current_goal": goal,
530
+ "total_records": len(past_records)
531
+ }
532
+
533
+ for record in past_records:
534
+ analysis_prompt["records"].append({
535
+ "macronutrients": json.loads(record[0]),
536
+ "micronutrients": json.loads(record[1]),
537
+ "foods": json.loads(record[2]),
538
+ "goal": record[3],
539
+ "timestamp": record[4]
540
+ })
541
+
542
+ # Call OpenAI for analysis
543
+ with st.spinner("πŸ”„ Analyzing your diet history..."):
544
+ response = openai.ChatCompletion.create(
545
+ model="gpt-4",
546
+ messages=[
547
+ {
548
+ "role": "user",
549
+ "content": f"""Analyze the following diet history and provide a comprehensive nutritional analysis.
550
+ Diet History: {json.dumps(analysis_prompt, indent=2)}
551
+
552
+ Please provide analysis in the following format:
553
+ {{
554
+ "trend_analysis": {{
555
+ "macronutrient_trends": [
556
+ "πŸ” Detailed observations about macronutrient patterns",
557
+ "⚠️ Any concerning patterns or excesses"
558
+ ],
559
+ "micronutrient_trends": [
560
+ "πŸ” Key observations about vitamin and mineral intake",
561
+ "⚠️ Notable deficiencies or concerns"
562
+ ]
563
+ }},
564
+ "goal_alignment": {{
565
+ "progress": [
566
+ "βœ… Areas aligned with {goal}",
567
+ "❌ Areas needing improvement"
568
+ ],
569
+ "recommendations": [
570
+ "πŸ’‘ Specific actionable recommendations",
571
+ "🎯 Goal-specific suggestions"
572
+ ]
573
+ }},
574
+ "dietary_balance": {{
575
+ "strengths": [
576
+ "πŸ’ͺ Strong aspects of the diet",
577
+ "🌟 Particularly healthy choices"
578
+ ],
579
+ "improvements": [
580
+ "πŸ“ˆ Areas for improvement",
581
+ "πŸ”„ Suggested dietary adjustments"
582
+ ]
583
+ }},
584
+ "alerts": [
585
+ "⚠️ Alert: [specific concern]",
586
+ "πŸ“’ Warning: [potential issue]"
587
+ ]
588
+ }}"""
589
+ }
590
+ ],
591
+ max_tokens=1000
592
+ )
593
+
594
+ try:
595
+ analysis = json.loads(response.choices[0].message.content)
596
+
597
+ # Create DataFrame from records for plotting
598
+ df_records = []
599
+ for record in analysis_prompt["records"]:
600
+ timestamp = datetime.strptime(record["timestamp"], '%Y-%m-%d %H:%M:%S')
601
+ macros = record["macronutrients"]
602
+ df_records.append({
603
+ 'timestamp': timestamp,
604
+ 'calories': macros.get('calories', 0),
605
+ 'protein': macros.get('protein', 0),
606
+ 'carbohydrates': macros.get('carbohydrates', 0),
607
+ 'fat': macros.get('fat', 0)
608
+ })
609
+
610
+ df = pd.DataFrame(df_records)
611
+
612
+ # Display Trend Analysis
613
+ st.write("### πŸ“ˆ Nutritional Trends")
614
+
615
+ # Remove the line charts and keep only the pie chart
616
+ # Macronutrient Distribution Pie Chart (Average)
617
+ avg_macros = {
618
+ 'Protein': df['protein'].mean(),
619
+ 'Carbohydrates': df['carbohydrates'].mean(),
620
+ 'Fat': df['fat'].mean()
621
+ }
622
+
623
+ fig_pie = go.Figure(data=[go.Pie(
624
+ labels=list(avg_macros.keys()),
625
+ values=list(avg_macros.values()),
626
+ hole=.3
627
+ )])
628
+
629
+ fig_pie.update_layout(title='Average Macronutrient Distribution')
630
+ st.plotly_chart(fig_pie, use_container_width=True)
631
+
632
+ # Display the rest of the analysis
633
+ st.write("### πŸ“Š Detailed Analysis")
634
+
635
+ st.write("**Macronutrient Patterns:**")
636
+ for trend in analysis["trend_analysis"]["macronutrient_trends"]:
637
+ st.write(f"- {trend}")
638
+
639
+ # Continue with the rest of your existing analysis display...
640
+
641
+ except json.JSONDecodeError:
642
+ st.error("Error parsing the analysis response. Please try again.")
643
+
644
+ except Exception as e:
645
+ st.error(f"Error analyzing diet history: {str(e)}")
646
+
647
+ except Exception as e:
648
+ st.error(f"Error analyzing diet history: {str(e)}")
649
 
650
  # Save to database
651
  save_record(
 
654
  parsed_result['micronutrients'],
655
  parsed_result['food_items'],
656
  parsed_result['improvements'],
657
+ goal,
658
+ is_refinement=True,
659
+ custom_timestamp=custom_timestamp
660
  )
661
 
662
+ # Add a section to clear database
663
+ st.header("Database Management")
664
+ if st.button("πŸ—‘οΈ Clear All Records"):
665
+ try:
666
+ conn = sqlite3.connect("nutrition_data.db")
667
+ cursor = conn.cursor()
668
+ cursor.execute("DROP TABLE IF EXISTS records")
669
+ conn.commit()
670
+
671
+ # Recreate the table
672
+ cursor.execute('''CREATE TABLE IF NOT EXISTS records (
673
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
674
+ image BLOB,
675
+ timestamp TEXT,
676
+ macronutrients TEXT,
677
+ micronutrients TEXT,
678
+ food_items TEXT,
679
+ improvements TEXT,
680
+ goal TEXT
681
+ )''')
682
+ conn.commit()
683
+ conn.close()
684
+
685
+ # Clear session state as well
686
+ if 'analysis_done' in st.session_state:
687
+ st.session_state.analysis_done = False
688
+ if 'initial_result' in st.session_state:
689
+ st.session_state.initial_result = None
690
+ if 'image_bytes' in st.session_state:
691
+ st.session_state.image_bytes = None
692
+ if 'base64_image' in st.session_state:
693
+ st.session_state.base64_image = None
694
+ if 'last_uploaded_file' in st.session_state:
695
+ st.session_state.last_uploaded_file = None
696
+
697
+ st.success("βœ… Database cleared successfully! You can now start adding new records.")
698
+ st.rerun()
699
+ except Exception as e:
700
+ st.error(f"Error clearing database: {str(e)}")
701
+ st.write("Debug info:", e)
702
+
703
+ def display_records():
704
+ try:
705
+ conn = sqlite3.connect("nutrition_data.db")
706
+ cursor = conn.cursor()
707
+
708
+ # Debug: Check if table exists
709
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='records'")
710
+ if not cursor.fetchone():
711
+ st.warning("Database table does not exist!")
712
+ return
713
+
714
+ cursor.execute("SELECT COUNT(*) FROM records")
715
+ count = cursor.fetchone()[0]
716
+ st.write(f"Total records in database: {count}")
717
+
718
+ cursor.execute("SELECT DISTINCT timestamp, macronutrients, micronutrients, food_items, goal, image FROM records ORDER BY timestamp DESC")
719
+ records = cursor.fetchall()
720
+ conn.close()
721
+
722
+ if not records:
723
+ st.info("No records found in the database.")
724
+ else:
725
+ for record in records:
726
+ st.write("---")
727
+ st.write(f"**πŸ“… Timestamp:** {record[0]}")
728
+
729
+ # Parse and display macronutrients
730
+ macros = json.loads(record[1])
731
+ st.write("**πŸ’ͺ Macronutrients:**")
732
+ for macro, value in macros.items():
733
+ if macro == 'calories':
734
+ st.write(f"- {macro.title()}: {value} kcal")
735
+ elif macro in ['sodium', 'cholesterol']:
736
+ st.write(f"- {macro.title()}: {value} mg")
737
+ else:
738
+ st.write(f"- {macro.title()}: {value}g")
739
+
740
+ # Parse and display micronutrients
741
+ micros = json.loads(record[2])
742
+ st.write("\n**πŸ₯— Micronutrients:**")
743
+ for micro, value in micros.items():
744
+ if micro in ['vitamin_a']:
745
+ st.write(f"- {micro.replace('_', ' ').title()}: {value} IU")
746
+ elif micro in ['fiber']:
747
+ st.write(f"- {micro.title()}: {value}g")
748
+ else:
749
+ st.write(f"- {micro.replace('_', ' ').title()}: {value} mg")
750
+
751
+ # Parse and display food items
752
+ foods = json.loads(record[3])
753
+ st.write("\n**🍽️ Foods Identified:**")
754
+ for food in foods:
755
+ st.write(f"- {food}")
756
+
757
+ st.write(f"\n**🎯 Goal:** {record[4]}")
758
+
759
+ # Display the image only once
760
+ if record[5]: # Check if image exists
761
+ st.image(record[5], caption="Meal Image", use_column_width=True)
762
+
763
+ st.write("---")
764
+ except Exception as e:
765
+ st.error(f"Error loading records: {str(e)}")
766
+ st.write("Debug info:", e)
767
+
768
+ # View saved records with debug information
769
  st.header("View Past Records")
770
  if st.button("Show Records"):
771
+ try:
772
+ conn = sqlite3.connect("nutrition_data.db")
773
+ cursor = conn.cursor()
 
 
 
 
 
 
 
 
 
 
 
 
774
 
775
+ # Debug: Check if table exists
776
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='records'")
777
+ if not cursor.fetchone():
778
+ st.warning("Database table does not exist!")
 
779
 
780
+ cursor.execute("SELECT COUNT(*) FROM records")
781
+ count = cursor.fetchone()[0]
782
+ st.write(f"Total records in database: {count}")
783
+
784
+ cursor.execute("SELECT DISTINCT timestamp, macronutrients, micronutrients, food_items, goal, image FROM records ORDER BY timestamp DESC")
785
+ records = cursor.fetchall()
786
+ conn.close()
787
+
788
+ if not records:
789
+ st.info("No records found in the database.")
790
+ else:
791
+ for record in records:
792
+ st.write("---")
793
+ st.write(f"**πŸ“… Timestamp:** {record[0]}")
794
+
795
+ # Parse and display macronutrients
796
+ macros = json.loads(record[1])
797
+ st.write("**πŸ’ͺ Macronutrients:**")
798
+ for macro, value in macros.items():
799
+ if macro == 'calories':
800
+ st.write(f"- {macro.title()}: {value} kcal")
801
+ elif macro in ['sodium', 'cholesterol']:
802
+ st.write(f"- {macro.title()}: {value} mg")
803
+ else:
804
+ st.write(f"- {macro.title()}: {value}g")
805
+
806
+ # Parse and display micronutrients
807
+ micros = json.loads(record[2])
808
+ st.write("\n**πŸ₯— Micronutrients:**")
809
+ for micro, value in micros.items():
810
+ if micro in ['vitamin_a']:
811
+ st.write(f"- {micro.replace('_', ' ').title()}: {value} IU")
812
+ elif micro in ['fiber']:
813
+ st.write(f"- {micro.title()}: {value}g")
814
+ else:
815
+ st.write(f"- {micro.replace('_', ' ').title()}: {value} mg")
816
+
817
+ # Parse and display food items
818
+ foods = json.loads(record[3])
819
+ st.write("\n**🍽️ Foods Identified:**")
820
+ for food in foods:
821
+ st.write(f"- {food}")
822
+
823
+ st.write(f"\n**🎯 Goal:** {record[4]}")
824
+
825
+ # Display the image
826
+ if record[5]: # Check if image exists
827
+ st.image(record[5], caption=f"Meal Image - {record[0]}", use_column_width=True)
828
+
829
+ st.write("---")
830
+ except Exception as e:
831
+ st.error(f"Error loading records: {str(e)}")
832
+ st.write("Debug info:", e)