1
0

app.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. import streamlit as st
  2. import pymysql
  3. import myloginpath
  4. import ollama
  5. import bcrypt
  6. import requests
  7. import string
  8. import random
  9. import smtplib
  10. from email.message import EmailMessage
  11. import pandas as pd
  12. from unit_converter import UnitConverter
  13. from snmp_notifier import notifier
  14. def local_web_search(query: str) -> str:
  15. try:
  16. req = requests.get(f'http://127.0.0.1:8080/search', params={'q': query, 'format': 'json'})
  17. if req.status_code == 200:
  18. data = req.json()
  19. results = data.get('results', [])
  20. if not results: return f"No results found on the web for '{query}'."
  21. snippets = [f"Source: {r.get('url')}\nContent: {r.get('content')}" for r in results[:3]]
  22. return "\n\n".join(snippets)
  23. return "Search engine returned an error."
  24. except Exception as e: return f"Local search engine unreachable: {e}"
  25. search_tool_schema = {
  26. 'type': 'function',
  27. 'function': {
  28. 'name': 'local_web_search',
  29. 'description': 'Search the internet for info not in DB.',
  30. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']},
  31. },
  32. }
  33. def search_nutrition_db(query: str) -> str:
  34. conn = get_db_connection('app_reader')
  35. if not conn: return "Database connection failed."
  36. try:
  37. with conn.cursor() as cursor:
  38. # Query products view via natural language match on core table
  39. sql = """
  40. SELECT c.product_name, m.proteins_100g, m.fat_100g, m.carbohydrates_100g, m.sugars_100g
  41. FROM food_db.products_core c
  42. LEFT JOIN food_db.products_macros m ON c.code = m.code
  43. WHERE MATCH(c.product_name, c.ingredients_text) AGAINST(%s IN NATURAL LANGUAGE MODE)
  44. AND c.product_name IS NOT NULL AND c.product_name != ''
  45. LIMIT 5
  46. """
  47. cursor.execute(sql, (query,))
  48. results = cursor.fetchall()
  49. if not results: return f"No database records found for '{query}'."
  50. snippets = []
  51. for r in results:
  52. snippets.append(f"- {r['product_name']}: Protein {r['proteins_100g']}g, Fat {r['fat_100g']}g, Carbs {r['carbohydrates_100g']}g, Sugars {r['sugars_100g']}g (per 100g)")
  53. return "\n".join(snippets)
  54. except Exception as e:
  55. return f"Database query failed: {e}"
  56. finally:
  57. conn.close()
  58. db_search_tool_schema = {
  59. 'type': 'function',
  60. 'function': {
  61. 'name': 'search_nutrition_db',
  62. 'description': 'Search the local medical nutrition database for product macros and ingredients. ALWAYS prioritize this over web search.',
  63. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The product or food name to search for (e.g. apple, chicken, bread)'}}, 'required': ['query']},
  64. },
  65. }
  66. def get_db_connection(login_path):
  67. try:
  68. conf = myloginpath.parse(login_path)
  69. if not conf or not conf.get('user'):
  70. st.error(f"⚠️ MySQL configuration missing for `{login_path}`. If you are testing locally on Windows, this app must be run on the Ubuntu server where `mysql_config_editor` is properly configured.")
  71. return None
  72. return pymysql.connect(
  73. host=conf.get('host', '127.0.0.1'),
  74. user=conf.get('user'),
  75. password=conf.get('password'),
  76. database='food_db',
  77. cursorclass=pymysql.cursors.DictCursor
  78. )
  79. except Exception as e:
  80. st.error(f"Connection Failed: {e}")
  81. return None
  82. def verify_login(username, password):
  83. conn = get_db_connection('app_auth')
  84. if not conn: return False
  85. with conn.cursor() as cursor:
  86. cursor.execute("SELECT password_hash FROM users WHERE username = %s LIMIT 1", (username,))
  87. result = cursor.fetchone()
  88. conn.close()
  89. if result: return bcrypt.checkpw(password.encode('utf-8'), result['password_hash'].encode('utf-8'))
  90. return False
  91. def get_user_id(username):
  92. conn = get_db_connection('app_auth')
  93. if not conn: return None
  94. with conn.cursor() as cursor:
  95. cursor.execute("SELECT id FROM users WHERE username = %s LIMIT 1", (username,))
  96. result = cursor.fetchone()
  97. conn.close()
  98. return result['id'] if result else None
  99. def get_eav_profile(username):
  100. uid = get_user_id(username)
  101. if not uid: return []
  102. conn = get_db_connection('app_auth')
  103. with conn.cursor() as cursor:
  104. cursor.execute("SELECT id, illness_health_condition_diet_dislikes_name as name, illness_health_condition_diet_dislikes_value as value FROM user_health_profiles WHERE user_id = %s", (uid,))
  105. res = cursor.fetchall()
  106. conn.close()
  107. return res
  108. def get_user_limit(username):
  109. conn = get_db_connection('app_auth')
  110. if not conn: return "50"
  111. with conn.cursor() as cursor:
  112. cursor.execute("SELECT search_limit FROM users WHERE username = %s LIMIT 1", (username,))
  113. result = cursor.fetchone()
  114. conn.close()
  115. return result['search_limit'] if (result and result['search_limit']) else "50"
  116. def register_user(username, password, email):
  117. conn = get_db_connection('app_auth')
  118. if not conn: return False
  119. hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  120. try:
  121. with conn.cursor() as cursor:
  122. cursor.execute("INSERT INTO users (username, password_hash, email) VALUES (%s, %s, %s)", (username, hashed, email))
  123. conn.commit()
  124. conn.close()
  125. send_email(email, "Welcome to Local Food AI", f"Hello {username}, your account was securely created!", to_name=username.title())
  126. return True
  127. except pymysql.err.IntegrityError:
  128. return False
  129. def send_email(to_email, subject, body, to_name="User"):
  130. msg = EmailMessage()
  131. msg.set_content(body)
  132. msg['Subject'] = subject
  133. msg['From'] = '"Clinical Food AI System" <security@localfoodai.com>'
  134. msg['To'] = f'"{to_name}" <{to_email}>'
  135. import time
  136. for attempt in range(5):
  137. try:
  138. s = smtplib.SMTP('localhost', 25)
  139. s.send_message(msg)
  140. s.quit()
  141. return True
  142. except Exception as e:
  143. if attempt == 4:
  144. return f"SMTP Delivery Failed: {str(e)}"
  145. time.sleep(2)
  146. return "Unknown Error Occurred"
  147. def reset_password(username, email):
  148. conn = get_db_connection('app_auth')
  149. if not conn: return False
  150. with conn.cursor() as cursor:
  151. cursor.execute("SELECT id, email FROM users WHERE username = %s", (username,))
  152. user = cursor.fetchone()
  153. if user and user['email'] == email:
  154. new_pass = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
  155. hashed = bcrypt.hashpw(new_pass.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  156. cursor.execute("UPDATE users SET password_hash = %s WHERE id = %s", (hashed, user['id']))
  157. conn.commit()
  158. conn.close()
  159. status = send_email(email, "Password Reset", f"Your new temporary password is: {new_pass}", to_name=username.title())
  160. if status is True:
  161. return True
  162. return status
  163. return False
  164. # UI Theming
  165. st.set_page_config(page_title="Food AI Explorer", page_icon="🍔", layout="wide")
  166. st.markdown("""
  167. <style>
  168. @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap');
  169. html, body, [class*="css"] { font-family: 'Inter', sans-serif; background-color: #0b192c; color: #e2e8f0; }
  170. h1, h2, h3 { color: #38bdf8 !important; font-weight: 600; letter-spacing: 0.5px; }
  171. div[data-testid="stSidebar"] { background: rgba(11, 25, 44, 0.95) !important; backdrop-filter: blur(10px); border-right: 1px solid #1e293b; }
  172. .stButton>button { background: linear-gradient(135deg, #0ea5e9, #0284c7); color: white; border: none; border-radius: 6px; }
  173. .stButton>button:hover { transform: scale(1.02); }
  174. .stTextInput>div>div>input, .stNumberInput>div>div>input, .stSelectbox>div>div>div { background-color: #0f172a; color: #f8fafc; border: 1px solid #38bdf8; }
  175. </style>
  176. """, unsafe_allow_html=True)
  177. if "authenticated_user" not in st.session_state:
  178. st.session_state["authenticated_user"] = None
  179. with st.sidebar:
  180. st.title("User Portal 🔐")
  181. if st.session_state["authenticated_user"]:
  182. st.success(f"Logged in as: {st.session_state['authenticated_user']}")
  183. if st.button("Logout"):
  184. st.session_state["authenticated_user"] = None
  185. st.rerun()
  186. st.markdown("---")
  187. st.subheader("🏥 Dynamic Health Profile")
  188. eav_data = get_eav_profile(st.session_state["authenticated_user"])
  189. uid = get_user_id(st.session_state["authenticated_user"])
  190. user_lim = get_user_limit(st.session_state["authenticated_user"])
  191. with st.expander("⚙️ Account Preferences"):
  192. opts = ["10", "20", "50", "100", "All"]
  193. idx = opts.index(user_lim) if user_lim in opts else 2
  194. new_lim = st.selectbox("Default Search Limit", opts, index=idx)
  195. if new_lim != user_lim:
  196. conn = get_db_connection('app_auth')
  197. with conn.cursor() as c:
  198. c.execute("UPDATE users SET search_limit = %s WHERE id = %s", (new_lim, uid))
  199. conn.commit()
  200. st.rerun()
  201. with st.expander("➕ Add Condition / Diet"):
  202. new_cat = st.selectbox("Category", ["Condition", "Illness", "Diet", "Dislike", "Allergy"])
  203. new_val = st.text_input("Value (e.g. 'vegan', 'diabetes', 'broccoli')").strip().lower()
  204. if st.button("Add to Profile") and new_val and uid:
  205. conn = get_db_connection('app_auth')
  206. with conn.cursor() as c:
  207. c.execute("INSERT INTO user_health_profiles (user_id, illness_health_condition_diet_dislikes_name, illness_health_condition_diet_dislikes_value) VALUES (%s, %s, %s)", (uid, new_cat, new_val))
  208. conn.commit()
  209. st.rerun()
  210. if eav_data:
  211. st.markdown("#### Active Flags")
  212. for e in eav_data:
  213. col1, col2 = st.columns([4, 1])
  214. col1.info(f"**{e['name']}:** {e['value'].title()}")
  215. if col2.button("X", key=f"del_eav_{e['id']}"):
  216. conn = get_db_connection('app_auth')
  217. with conn.cursor() as c:
  218. c.execute("DELETE FROM user_health_profiles WHERE id = %s", (e['id'],))
  219. conn.commit()
  220. st.rerun()
  221. else:
  222. tab1, tab2, tab3 = st.tabs(["Login", "Register", "Reset"])
  223. with tab1:
  224. l_user = st.text_input("Username", key="l_user").strip()
  225. l_pass = st.text_input("Password", type="password", key="l_pass")
  226. if st.button("Login"):
  227. if verify_login(l_user, l_pass):
  228. notifier.send_alert(f"User Login Success: {l_user}")
  229. st.session_state["authenticated_user"] = l_user
  230. st.rerun()
  231. else:
  232. notifier.send_alert(f"User Login Failed: {l_user}")
  233. st.error("Invalid login.")
  234. with tab2:
  235. r_user = st.text_input("Username", key="r_user")
  236. r_email = st.text_input("Email Address", key="r_email")
  237. r_pass = st.text_input("Password", type="password", key="r_pass")
  238. if st.button("Register"):
  239. if len(r_pass) < 6: st.error("Password too short.")
  240. elif register_user(r_user, r_pass, r_email): st.success("Registered safely!")
  241. else: st.error("Username exists.")
  242. with tab3:
  243. f_user = st.text_input("Username", key="f_user")
  244. f_email = st.text_input("Registered Email", key="f_email")
  245. if st.button("Send Reset Link"):
  246. status = reset_password(f_user, f_email)
  247. if status is True:
  248. st.success("Password reset emailed.")
  249. else:
  250. st.error(f"Failed: {status}")
  251. if not st.session_state["authenticated_user"]:
  252. st.title("🍔 Food AI Medical Explorer")
  253. st.info("Please login to interrogate the Clinical Data.")
  254. st.stop()
  255. st.title("🍔 Food AI Clinical Explorer")
  256. conn_reader = get_db_connection('app_reader')
  257. tab_chat, tab_explore, tab_plate, tab_planner = st.tabs(["💬 AI Chat", "🔬 Clinical Search", "🍽️ My Plate Builder", "🤖 AI Meal Planner"])
  258. with tab_chat:
  259. st.subheader("Chat with the Context")
  260. with st.expander("ℹ️ How to use this feature (Examples)"):
  261. st.markdown("""
  262. **Your active conditions (e.g. Pregnant, Diabetic) are automatically sent to the AI in the background. You do not need to type them out.**
  263. *Examples:*
  264. 1. "I am pregnant, diabetic, and have kidney problems. Can I eat sushi?"
  265. 2. "What is a safe snack to stabilize my blood sugar without hurting my kidneys?"
  266. 3. "Can I drink milk? I need calcium for the baby."
  267. 4. "Is it safe to eat a large steak for iron?"
  268. 5. "What foods are strictly forbidden for me?"
  269. """)
  270. if "messages" not in st.session_state:
  271. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  272. for msg in st.session_state.messages:
  273. st.chat_message(msg["role"]).write(msg["content"])
  274. if prompt := st.chat_input("Ask about the food items..."):
  275. st.session_state.messages.append({"role": "user", "content": prompt})
  276. st.chat_message("user").write(prompt)
  277. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  278. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  279. sys_prompt = f"""You are a helpful medical data analyst AI.
  280. The user has the following health profile / conditions: {profile_text}.
  281. You MUST act as a specialized clinical dietitian. Autonomously deduce what foods are recommended, forbidden, or accepted for these specific conditions and apply these rules to all your answers.
  282. ALWAYS query the local database using the search_nutrition_db tool to answer questions about food, macros, and nutrients before answering or searching the web! If it's not in the DB, you can use local_web_search.
  283. DO NOT hallucinate that a well-known food like sushi has 0 macros just because the database is missing a row. Use your medical knowledge to supplement missing database data and warn the user of biological facts (e.g. Sushi contains raw fish and carbs from rice)."""
  284. with st.spinner("Analyzing..."):
  285. try:
  286. temp_messages = [{"role": "system", "content": sys_prompt}] + [m for m in st.session_state.messages if m["role"] != "tool"]
  287. response = ollama.chat(model='llama3', messages=temp_messages, tools=[search_tool_schema, db_search_tool_schema])
  288. if response.get('message', {}).get('tool_calls'):
  289. for tool in response['message']['tool_calls']:
  290. if tool['function']['name'] == 'local_web_search':
  291. query_arg = tool['function']['arguments'].get('query')
  292. st.info(f"🔍 Web Search triggered for: '{query_arg}'")
  293. search_data = local_web_search(query_arg)
  294. st.session_state.messages.append(response['message'])
  295. st.session_state.messages.append({'role': 'tool', 'content': search_data, 'name': 'local_web_search'})
  296. elif tool['function']['name'] == 'search_nutrition_db':
  297. query_arg = tool['function']['arguments'].get('query')
  298. st.info(f"🗄️ Database Search triggered for: '{query_arg}'")
  299. db_data = search_nutrition_db(query_arg)
  300. st.session_state.messages.append(response['message'])
  301. st.session_state.messages.append({'role': 'tool', 'content': db_data, 'name': 'search_nutrition_db'})
  302. temp_messages = [{"role": "system", "content": sys_prompt}] + st.session_state.messages
  303. response = ollama.chat(model='llama3', messages=temp_messages)
  304. ai_reply = response['message']['content']
  305. except Exception as e: ai_reply = f"Hold on! Engine execution fault: {e}"
  306. st.session_state.messages.append({"role": "assistant", "content": ai_reply})
  307. st.chat_message("assistant").write(ai_reply)
  308. def highlight_medical_warnings(row):
  309. try:
  310. val = str(row.get('Medical Warning', ''))
  311. if '⚠️' in val: return ['background-color: rgba(255, 0, 0, 0.4); color: white;'] * len(row)
  312. if '💚' in val: return ['background-color: rgba(0, 255, 0, 0.3); color: white;'] * len(row)
  313. except: pass
  314. return [''] * len(row)
  315. with tab_explore:
  316. st.subheader("Clinical Data Search")
  317. with st.expander("ℹ️ How to use this feature (Examples)"):
  318. st.markdown("""
  319. **Your active conditions are automatically flagged (⚠️ or 💚) in the search results.**
  320. *Example Searches:*
  321. 1. `Cereal` *(Checks for high sugar & hidden phosphorus)*
  322. 2. `Cheese` *(Checks for unpasteurized pregnancy risks & high sodium)*
  323. 3. `Fruit Juice` *(Checks for high sugar spikes)*
  324. 4. `Deli Meat` *(Checks for Listeria risk & extreme sodium)*
  325. 5. `White Rice` *(Safe for kidneys but flags high glycemic index)*
  326. """)
  327. sq = st.text_input("Search Product Name or Ingredient")
  328. cols = st.columns(5)
  329. min_pro = cols[0].number_input("Min Protein (g)", 0, 1000, 0)
  330. min_fat = cols[1].number_input("Min Fat (g)", 0, 1000, 0)
  331. min_carb = cols[2].number_input("Min Carbs (g)", 0, 1000, 0)
  332. max_sug = cols[3].number_input("Max Sugar (g)", 0, 1000, 1000)
  333. # Load dynamically fetched limit to prevent Pandas Styler crash
  334. try:
  335. max_cells = pd.options.styler.render.max_elements
  336. except AttributeError:
  337. max_cells = 262144
  338. dynamic_max_rows = max_cells // 15 # Approx 15 columns
  339. opts = [10, 20, 50, 100, dynamic_max_rows]
  340. user_lim_str = get_user_limit(st.session_state["authenticated_user"])
  341. user_lim_val = dynamic_max_rows if user_lim_str == "All" else int(user_lim_str)
  342. if user_lim_val not in opts: user_lim_val = 50
  343. idx = opts.index(user_lim_val)
  344. limit_rc = cols[4].selectbox("Limit Results", opts, index=idx)
  345. if st.button("Search Database") and sq and conn_reader:
  346. notifier.send_alert(f"Medical DB Search Executed: {sq}")
  347. with st.spinner("Processing massive clinical query..."):
  348. try:
  349. with conn_reader.cursor() as cursor:
  350. l_str = "" if limit_rc == "All" else f"LIMIT {limit_rc}"
  351. query = f"""
  352. SELECT c.code, c.product_name, c.generic_name, c.brands, c.ingredients_text,
  353. a.allergens,
  354. m.`energy-kcal_100g`, m.proteins_100g, m.fat_100g, m.carbohydrates_100g, m.sugars_100g, m.fiber_100g, m.sodium_100g, m.salt_100g, m.cholesterol_100g,
  355. v.`vitamin-a_100g`, v.`vitamin-b1_100g`, v.`vitamin-b2_100g`, v.`vitamin-pp_100g`, v.`vitamin-b6_100g`, v.`vitamin-b9_100g`, v.`vitamin-b12_100g`, v.`vitamin-c_100g`, v.`vitamin-d_100g`, v.`vitamin-e_100g`, v.`vitamin-k_100g`,
  356. min.calcium_100g, min.iron_100g, min.magnesium_100g, min.potassium_100g, min.zinc_100g
  357. FROM food_db.products_core c
  358. LEFT JOIN food_db.products_allergens a ON c.code = a.code
  359. LEFT JOIN food_db.products_macros m ON c.code = m.code
  360. LEFT JOIN food_db.products_vitamins v ON c.code = v.code
  361. LEFT JOIN food_db.products_minerals min ON c.code = min.code
  362. WHERE MATCH(c.product_name, c.ingredients_text) AGAINST(%s IN NATURAL LANGUAGE MODE)
  363. AND c.product_name IS NOT NULL AND c.product_name != ''
  364. AND (m.proteins_100g >= %s OR m.proteins_100g IS NULL)
  365. AND (m.fat_100g >= %s OR m.fat_100g IS NULL)
  366. AND (m.carbohydrates_100g >= %s OR m.carbohydrates_100g IS NULL)
  367. AND (m.sugars_100g <= %s OR m.sugars_100g IS NULL)
  368. {l_str}
  369. """
  370. cursor.execute(query, (sq, min_pro, min_fat, min_carb, max_sug))
  371. results = cursor.fetchall()
  372. if results:
  373. # Fetch EAV Medical Profile
  374. eav_profile = get_eav_profile(st.session_state["authenticated_user"])
  375. df = pd.DataFrame(results)
  376. st.markdown("### 🛠️ Dynamic Column Display")
  377. default_columns = [
  378. 'code', 'product_name', 'generic_name', 'brands', 'allergens', 'ingredients_text',
  379. 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'sodium_100g', 'energy-kcal_100g',
  380. 'vitamin-c_100g', 'iron_100g', 'calcium_100g'
  381. ]
  382. all_fetched_cols = list(df.columns)
  383. valid_defaults = [c for c in default_columns if c in all_fetched_cols]
  384. if "selected_columns" not in st.session_state or st.button("Reset Default Columns"):
  385. st.session_state["selected_columns"] = valid_defaults
  386. st.rerun()
  387. chosen_cols = st.multiselect("Customize Dataset View", all_fetched_cols, default=st.session_state["selected_columns"], key="multi_cols")
  388. st.session_state["selected_columns"] = chosen_cols
  389. # Filter dataframe gracefully, but we retain a copy for background analytics
  390. df_display = df[chosen_cols].copy()
  391. warnings_col = []
  392. for idx, row in df.iterrows():
  393. warns = []
  394. ing_text = str(row['ingredients_text']).lower()
  395. all_text = str(row['allergens']).lower()
  396. for param in eav_profile:
  397. cat = param['name'].lower()
  398. val = param['value']
  399. # Disease Analytics
  400. if cat == 'illness':
  401. if val == 'diabetes' and pd.notnull(row.get('sugars_100g')) and float(row['sugars_100g']) > 10.0:
  402. warns.append("⚠️ High Sugar (Diabetes)")
  403. if (val == 'hypertension' or val == 'high bp') and pd.notnull(row.get('sodium_100g')) and float(row['sodium_100g']) > 1.5:
  404. warns.append("⚠️ High Salt (Hypertension)")
  405. if val == 'scurvy' and pd.notnull(row.get('vitamin-c_100g')) and float(row['vitamin-c_100g']) > 0.005:
  406. warns.append("💚 High Vitamin C (Scurvy Recommended)")
  407. if val == 'anemia' and pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  408. warns.append("💚 High Iron (Anemia Recommended)")
  409. # Condition Analytics
  410. if cat == 'condition':
  411. if val == 'pregnant':
  412. if ('cru' in ing_text or 'raw' in ing_text or 'viande crue' in ing_text):
  413. warns.append("⚠️ Raw Foods (Pregnancy Toxoplasmosis)")
  414. if pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  415. warns.append("💚 Med-High Iron (Pregnancy Health)")
  416. if val == 'low fat' and pd.notnull(row.get('fat_100g')) and float(row['fat_100g']) > 20.0:
  417. warns.append("⚠️ High Fat")
  418. if val == 'osteoporosis' and pd.notnull(row.get('calcium_100g')) and float(row['calcium_100g']) > 0.1:
  419. warns.append("💚 High Calcium (Bone Health)")
  420. if eav_data:
  421. ing_text = str(row.get('ingredients_text', '')).lower()
  422. all_text = str(row.get('allergens', '')).lower()
  423. product_name_text = str(row.get('product_name', '')).lower()
  424. for e in eav_data:
  425. cat = str(e['name']).lower()
  426. val = str(e['value']).lower()
  427. # Clinical Trace Checks...
  428. if cat == 'condition' and (val == 'pregnant' or val == 'pregnancy' or val == 'breastfeeding'):
  429. # Forbidden / High Risk (Toxoplasmosis & Listeria)
  430. if any(x in ing_text or x in product_name_text for x in ['cru', 'raw', 'viande crue', 'sushi', 'sashimi', 'poisson cru']):
  431. warns.append("⚠️ Forbidden: Raw Meat/Fish (Toxoplasmosis/Parasite Risk)")
  432. if any(x in ing_text or x in product_name_text for x in ['lait cru', 'unpasteurized', 'non pasteurisé']):
  433. warns.append("⚠️ Forbidden: Unpasteurized Dairy (Listeria Risk)")
  434. if any(x in ing_text or x in product_name_text for x in ['alcool', 'wine', 'alcohol', 'beer']):
  435. warns.append("⚠️ Forbidden: Contains Alcohol")
  436. # Recommended (Iron & Calcium)
  437. if float(row.get('iron_100g', 0) or 0) > 0.003:
  438. warns.append("💚 Recommended: High Iron (Pregnancy Health)")
  439. if float(row.get('calcium_100g', 0) or 0) > 0.120:
  440. warns.append("💚 Recommended: High Calcium (Bone Health / Breastfeeding)")
  441. if cat == 'illness' and val == 'osteoporosis':
  442. if float(row.get('calcium_100g', 0) or 0) < 0.120:
  443. warns.append("⚠️ Low Calcium (Osteoporosis Risk)")
  444. else:
  445. warns.append("💚 Recommended (High Calcium)")
  446. if cat == 'illness' and val == 'scurvy':
  447. if float(row.get('vitamin-c_100g', 0) or 0) < 0.010:
  448. warns.append("⚠️ Low Vitamin C (Scurvy Risk)")
  449. else:
  450. warns.append("💚 Recommended (High Vitamin C)")
  451. if cat == 'diet' and val in ['vegan', 'vegetarian']:
  452. if any(x in ing_text for x in ['meat', 'beef', 'chicken', 'fish', 'gelatin', 'whey', 'pork', 'porc', 'poulet']):
  453. warns.append("⚠️ Contains Animal Products")
  454. if cat == 'diet' and val == 'halal':
  455. if any(x in ing_text for x in ['pork', 'pig', 'porc', 'wine', 'alcohol', 'beer', 'vin']):
  456. warns.append("⚠️ Probable Haram Ingredients (e.g. Pork/Wine)")
  457. if cat in ['dislike', 'allergy']:
  458. if val in ing_text or val in all_text or val in product_name_text:
  459. warns.append(f"⚠️ Contains: {val.upper()}")
  460. warnings_col.append(" | ".join(list(set(warns))) if warns else "✅ Safe for Profile")
  461. df_display.insert(0, 'Medical Warning', warnings_col)
  462. styled_df = df_display.style.apply(highlight_medical_warnings, axis=1)
  463. st.success(f"Analysed {len(results)} records utilizing dynamic Partitions!")
  464. st.dataframe(styled_df, use_container_width=True)
  465. if st.button("🤖 Ask AI to Evaluate This Table"):
  466. with st.spinner("AI is dynamically evaluating these records against your profile..."):
  467. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  468. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  469. eval_prompt = f"The user has this profile: {profile_text}. Evaluate these foods and state which are highly recommended or strictly forbidden: {df_display.to_dict('records')}"
  470. try:
  471. response = ollama.chat(model='llama3', messages=[{'role': 'user', 'content': eval_prompt}])
  472. st.info(response['message']['content'])
  473. except Exception as e:
  474. st.error(f"AI Evaluation Failed: {e}")
  475. else:
  476. st.warning("No products found matching those strict terms.")
  477. except Exception as e: st.error(f"SQL/Pandas Error: {e}")
  478. with tab_plate:
  479. st.subheader("🍽️ My Plate Builder")
  480. with st.expander("ℹ️ How to use this feature (Examples)"):
  481. st.markdown("""
  482. **Mix and match ingredients to see if the combined macros exceed your profile's limits.**
  483. *Example Plates:*
  484. 1. `150g White Rice` + `50g Chicken Breast` + `100g Green Beans`
  485. 2. `200g Potatoes` + `100g Tomatoes` + `100g Beef`
  486. 3. `100g Spinach Salad` + `50g Feta Cheese`
  487. 4. `200g Lentils` + `100g Quinoa`
  488. 5. `100g Apple` + `30g Almonds`
  489. """)
  490. uid = get_user_id(st.session_state["authenticated_user"])
  491. conn = get_db_connection('app_auth')
  492. if conn and uid:
  493. with conn.cursor() as cursor:
  494. cursor.execute("SELECT id, plate_name FROM plates WHERE user_id = %s", (uid,))
  495. plates = cursor.fetchall()
  496. with st.expander("➕ Create a New Plate"):
  497. new_plate_name = st.text_input("Plate Name")
  498. if st.button("Create Plate"):
  499. cursor.execute("INSERT INTO plates (user_id, plate_name) VALUES (%s, %s)", (uid, new_plate_name))
  500. conn.commit()
  501. st.session_state["active_plate"] = new_plate_name
  502. st.rerun()
  503. if plates:
  504. plate_names = [p['plate_name'] for p in plates]
  505. default_idx = plate_names.index(st.session_state["active_plate"]) if "active_plate" in st.session_state and st.session_state["active_plate"] in plate_names else 0
  506. selected_plate = st.selectbox("Select Active Plate", plate_names, index=default_idx)
  507. st.session_state["active_plate"] = selected_plate
  508. active_p_id = next(p['id'] for p in plates if p['plate_name'] == selected_plate)
  509. cursor.execute("""
  510. SELECT i.id, i.product_code, i.quantity_grams, p.product_name, p.proteins_100g, p.fat_100g, p.carbohydrates_100g
  511. FROM plate_items i LEFT JOIN products p ON i.product_code = p.code WHERE i.plate_id = %s
  512. """, (active_p_id,))
  513. items = cursor.fetchall()
  514. if items:
  515. st.dataframe(items, use_container_width=True)
  516. total_pro = sum((float(i['proteins_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  517. total_fat = sum((float(i['fat_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  518. total_carb = sum((float(i['carbohydrates_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  519. st.info(f"**Total Protein:** {total_pro:.1f}g | **Total Fat:** {total_fat:.1f}g | **Total Carbs:** {total_carb:.1f}g")
  520. st.markdown("---")
  521. st.markdown("#### ➕ Add Food to Plate")
  522. add_search = st.text_input("Search Product Name")
  523. if add_search:
  524. cursor.execute("""
  525. SELECT c.code, c.product_name
  526. FROM food_db.products_core c
  527. JOIN food_db.products_macros m ON c.code = m.code
  528. WHERE MATCH(c.product_name, c.ingredients_text) AGAINST(%s IN NATURAL LANGUAGE MODE)
  529. AND c.product_name IS NOT NULL AND c.product_name != ''
  530. AND m.proteins_100g IS NOT NULL AND m.fat_100g IS NOT NULL AND m.carbohydrates_100g IS NOT NULL
  531. LIMIT 10
  532. """, (add_search,))
  533. search_res = cursor.fetchall()
  534. if search_res:
  535. options = {f"{r['product_name']} ({r['code']})": r for r in search_res}
  536. selected_str = st.selectbox("Select Product", list(options.keys()))
  537. selected_product = options[selected_str]
  538. add_amount_str = st.text_input("Portion Quantity (e.g., '100g', '2 tbsp', '1.5 cups', '1 pinch')", value="100g")
  539. if st.button("Add Item to Plate"):
  540. # Use UnitConverter to parse
  541. grams = UnitConverter.parse_and_convert(add_amount_str, product_name=selected_product['product_name'])
  542. if grams is not None:
  543. cursor.execute("INSERT INTO plate_items (plate_id, product_code, quantity_grams) VALUES (%s, %s, %s)",
  544. (active_p_id, selected_product['code'], grams))
  545. conn.commit()
  546. st.success(f"Added {grams}g of {selected_product['product_name']}!")
  547. st.rerun()
  548. else:
  549. st.error("Could not parse unit. Please use format like '100g' or '1 cup'.")
  550. else:
  551. st.warning("No products found.")
  552. with tab_planner:
  553. st.subheader("🤖 AI Meal Planner")
  554. with st.expander("ℹ️ How to use this feature (Examples)"):
  555. st.markdown("""
  556. **Your active conditions are automatically applied to the generated menu.**
  557. *Example Prompts:*
  558. 1. "Generate a full day meal plan for me. I am pregnant, diabetic, and have kidney disease."
  559. 2. "Plan a pregnancy-safe dinner that won't spike my blood sugar."
  560. 3. "I need a high-iron lunch that is safe for my kidneys."
  561. 4. "Plan a breakfast without dairy that is kidney-friendly."
  562. 5. "Give me a 3-day meal prep plan ensuring no raw fish, controlled protein portions, and steady complex carbs."
  563. """)
  564. p_col1, p_col2, p_col3 = st.columns(3)
  565. target_cal = p_col1.number_input("Target Daily Calories (kcal)", 1000, 5000, 2000, 50)
  566. diet_pref = p_col2.selectbox("Dietary Preference", ["Omnivore", "Vegetarian", "Vegan", "Keto", "Paleo"])
  567. meal_count = p_col3.slider("Number of Meals", 2, 6, 3)
  568. extra_notes = st.text_input("Any additional allergies or goals?")
  569. if st.button("Generate Professional Menu"):
  570. with st.spinner("AI is formulating and interrogating the local database..."):
  571. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  572. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  573. sys_prompt = f"""You are a professional clinical Dietitian planner. Target: {target_cal}kcal over {meal_count} meals.
  574. Dietary constraint: {diet_pref}. Additional notes: {extra_notes}.
  575. The user has the following health profile / conditions: {profile_text}.
  576. You MUST autonomously deduce what foods are recommended, forbidden, or accepted for these specific conditions and ensure the menu perfectly respects their medical requirements!
  577. CRITICAL INSTRUCTIONS:
  578. - YOU MUST USE the `search_nutrition_db` tool to find real products and their exact macros before constructing the menu!
  579. - If you cannot find appropriate products in the local DB, use `local_web_search`.
  580. - ALWAYS output exactly as a strict Markdown table including Columns: | Meal | Food | Calories | Salt (mg) | Fat (g) | Iron (mg) |
  581. - DO NOT output | separated text outside of standard strict markdown block.
  582. - Ensure the sum of the Calories EXACTLY matches the Target Daily Calories ({target_cal}).
  583. - You MUST append a final row at the bottom of the table named "Total" that mathematically sums up the Calories, Salt, Fat, and Iron columns.
  584. - Convert ALL cooking measurements to Grams (g). Use these equivalents STRICTLY:
  585. 1 tbsp = 15g, 1 tsp = 5g, 1 cup = 200g, 1 mustard glass = 100g. 1 cl of liquid = 10g.
  586. """
  587. temp_messages = [{'role': 'system', 'content': sys_prompt}, {'role': 'user', 'content': 'Generate my meal plan. Find real foods from the DB.'}]
  588. response = ollama.chat(model='llama3', messages=temp_messages, tools=[search_tool_schema, db_search_tool_schema])
  589. # Simple loop to handle multiple tool calls (up to 3 times to prevent infinite loops)
  590. for _ in range(3):
  591. if response.get('message', {}).get('tool_calls'):
  592. temp_messages.append(response['message'])
  593. for tool in response['message']['tool_calls']:
  594. if tool['function']['name'] == 'local_web_search':
  595. query_arg = tool['function']['arguments'].get('query')
  596. st.info(f"🔍 Planner Web Search triggered for: '{query_arg}'")
  597. search_data = local_web_search(query_arg)
  598. temp_messages.append({'role': 'tool', 'content': search_data, 'name': 'local_web_search'})
  599. elif tool['function']['name'] == 'search_nutrition_db':
  600. query_arg = tool['function']['arguments'].get('query')
  601. st.info(f"🗄️ Planner DB Search triggered for: '{query_arg}'")
  602. db_data = search_nutrition_db(query_arg)
  603. temp_messages.append({'role': 'tool', 'content': db_data, 'name': 'search_nutrition_db'})
  604. response = ollama.chat(model='llama3', messages=temp_messages, tools=[search_tool_schema, db_search_tool_schema])
  605. else:
  606. break
  607. st.markdown(response['message']['content'])
  608. if conn_reader: conn_reader.close()