ALHarsaa commited on
Commit
e036d2b
·
unverified ·
1 Parent(s): 107d75c

Created app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ import numpy as np
4
+ from google import genai
5
+ from PIL import Image
6
+
7
+ # Initialize Gemini Client
8
+ client = genai.Client()
9
+
10
+ # Force full viewport usage to widen the camera layout frame
11
+ st.set_page_config(page_title="NutriScan AI Pro", page_icon="🛡️", layout="wide")
12
+
13
+ st.title("🛡️ NutriScan AI: Conversational Diet Intelligence")
14
+ st.write("A production-hardened hybrid edge/cloud system with dynamic session memory.")
15
+
16
+ st.markdown("---")
17
+
18
+ # --- STEP 1: CONTEXT INJECTION DECK (SIDEBAR) ---
19
+ st.sidebar.header("👤 Dynamic Health Profile")
20
+
21
+ goal_options = ["Weight Loss", "Muscle Gain / Clean Bulk", "Diabetes Management", "Hypertension Control", "Gluten-Free Induction"]
22
+ selected_goals = st.sidebar.multiselect("Primary Objectives", options=goal_options)
23
+
24
+ # Custom Goal Input Gate
25
+ custom_goal_active = st.sidebar.checkbox("Inject custom targets?")
26
+ custom_goal_text = ""
27
+ if custom_goal_active:
28
+ custom_goal_text = st.sidebar.text_input("Type custom health profile constraints:")
29
+
30
+ allergy_options = ["Dairy", "Nuts", "Gluten", "Soy", "Artificial Sweeteners", "Preservatives"]
31
+ selected_allergies = st.sidebar.multiselect("STRICT Avoidances / Allergies", options=allergy_options)
32
+
33
+ additional_notes = st.sidebar.text_area("Narrative Clinical Notes (e.g., medical conditions):")
34
+
35
+ # Construct the master string block
36
+ final_goals = selected_goals + ([custom_goal_text] if custom_goal_text else [])
37
+ user_profile_context = f"""
38
+ USER HEALTH PROFILE DOSSIER:
39
+ - Objectives: {', '.join(final_goals) if final_goals else 'General Fitness Check'}
40
+ - Strict Allergens to Flag: {', '.join(selected_allergies) if selected_allergies else 'None specified'}
41
+ - Medical/Narrative Notes: {additional_notes if additional_notes else 'None provided'}
42
+ """
43
+
44
+ # --- STEP 2: CONVERSATIONAL MEMORY INITIALIZATION ---
45
+ if "chat_history" not in st.session_state:
46
+ st.session_state.chat_history = []
47
+ if "vault_images" not in st.session_state:
48
+ st.session_state.vault_images = []
49
+
50
+ # --- STEP 3: MULTI-IMAGE ACQUISITION CANVAS ---
51
+ st.subheader("📸 Frame Capture Pipeline")
52
+ col_cam, col_vault = st.columns([2, 3])
53
+
54
+ with col_cam:
55
+ captured_file = st.camera_input("Position product packaging in center view")
56
+ if captured_file is not None:
57
+ img = Image.open(captured_file)
58
+
59
+ # Guard against duplicates inside the active frame cycle
60
+ if len(st.session_state.vault_images) == 0 or captured_file.name != st.session_state.get("last_uploaded_name", ""):
61
+ st.session_state.vault_images.append(img)
62
+ st.session_state.last_uploaded_name = captured_file.name
63
+ st.success(f"Frame buffered into system memory! Canvas Count: {len(st.session_state.vault_images)}")
64
+
65
+ with col_vault:
66
+ if st.session_state.vault_images:
67
+ st.write("⚡ **Buffered Frame Stack Active:**")
68
+ # Render thumbnails of all taken photos side-by-side
69
+ thumb_cols = st.columns(min(len(st.session_state.vault_images), 4))
70
+ for idx, thumb_img in enumerate(st.session_state.vault_images):
71
+ with thumb_cols[idx % 4]:
72
+ st.image(thumb_img, caption=f"Scan #{idx+1}", width=120)
73
+
74
+ if st.button("🗑️ Clear Image Stack"):
75
+ st.session_state.vault_images = []
76
+ st.rerun()
77
+
78
+ st.markdown("---")
79
+
80
+ # --- STEP 4: INTERACTIVE CHAT ENGINE LAYOUT ---
81
+ st.subheader("💬 AI Clinical Consultation Stream")
82
+
83
+ # Render previous conversational statements
84
+ for message in st.session_state.chat_history:
85
+ with st.chat_message(message["role"]):
86
+ st.markdown(message["content"])
87
+
88
+ # System Execution Prompter
89
+ if user_message := st.chat_input("Ask a question about your scanned items..."):
90
+
91
+ # 1. Display User Message Instantly
92
+ st.session_state.chat_history.append({"role": "user", "content": user_message})
93
+ with st.chat_message("user"):
94
+ st.markdown(user_message)
95
+
96
+ # 2. Build Multi-modal Prompt Strategy
97
+ # Construct systemic ground truth logic framework
98
+ system_logic_prompt = f"""
99
+ You are an expert digital dietitian. You are analyzing an interactive product scan loop.
100
+
101
+ CRITICAL OPERATION PROTOCOLS:
102
+ 1. Cross-reference all inputs against this profile context: {user_profile_context}
103
+ 2. Analyze the attached sequence of product photos sequentially.
104
+ 3. If the user's query requires finer granular data that you cannot see in the current image stack, or if a photo is unclear, DO NOT guess. State your initial observation and explicitly request the user to take an additional focused scan.
105
+
106
+ CURRENT CHAT HISTORY DIALOGUE FOR TRACKING CONTEXT:
107
+ """
108
+
109
+ # Pack background context strings, active image arrays, and current input together
110
+ payload = [system_logic_prompt]
111
+
112
+ # Compile chat history text strings into payload
113
+ for msg in st.session_state.chat_history[:-1]:
114
+ payload.append(f"{msg['role'].upper()}: {msg['content']}\n")
115
+
116
+ # Inject our list of images directly into the multimodal generation array
117
+ payload.extend(st.session_state.vault_images)
118
+
119
+ # Inject current fresh query prompt
120
+ payload.append(f"CURRENT USER INQUIRY: {user_message}\nASSISTANT SYSTEM OUTPUT:")
121
+
122
+ # 3. Call Cloud Model Infrastructure
123
+ with st.chat_message("assistant"):
124
+ with st.spinner("Analyzing data streams..."):
125
+ try:
126
+ response = client.models.generate_content(
127
+ model='gemini-2.5-flash',
128
+ contents=payload
129
+ )
130
+ st.markdown(response.text)
131
+ st.session_state.chat_history.append({"role": "assistant", "content": response.text})
132
+ except Exception as e:
133
+ st.error(f"Execution Error: {e}")