1
0

app.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. # $Id$
  2. # $Author$
  3. # $log$
  4. #ident "@(#)LocalFoodAI:app.py:$Format:%D:%ci:%cN:%h$"
  5. #ident "@(#)$Format:LocalFoodAI:app.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  6. import streamlit as st
  7. import extra_streamlit_components as stx
  8. import subprocess
  9. import pymysql
  10. import bcrypt
  11. import random
  12. import string
  13. import time
  14. import os
  15. import pandas as pd
  16. import html
  17. from snmp_notifier import notifier
  18. from unit_converter import UnitConverter
  19. from fpdf import FPDF
  20. import myloginpath
  21. import ollama
  22. import requests
  23. import smtplib
  24. from email.message import EmailMessage
  25. from typing import Optional, List, Dict, Any, Tuple
  26. import threading
  27. import os
  28. ACTIVE_MODEL = os.environ.get('LLM_MODEL', 'llama3.2-vision:11b')
  29. def strip_scratchpad(text: str) -> str:
  30. import re
  31. # Strip out the XML <scratchpad> tag and everything in between, non-greedily
  32. clean_text = re.sub(r'<scratchpad>.*?</scratchpad>', '', text, flags=re.DOTALL)
  33. return clean_text.strip()
  34. def filter_scratchpad_stream(stream):
  35. buffer = ""
  36. in_scratchpad = False
  37. for chunk in stream:
  38. content = chunk['message']['content']
  39. buffer += content
  40. while True:
  41. if not in_scratchpad:
  42. start_idx = buffer.find("<scratchpad>")
  43. if start_idx != -1:
  44. yield buffer[:start_idx]
  45. buffer = buffer[start_idx:]
  46. in_scratchpad = True
  47. else:
  48. yield_len = max(0, len(buffer) - 11)
  49. if yield_len > 0:
  50. yield buffer[:yield_len]
  51. buffer = buffer[yield_len:]
  52. break
  53. else:
  54. end_idx = buffer.find("</scratchpad>")
  55. if end_idx != -1:
  56. buffer = buffer[end_idx + 13:]
  57. in_scratchpad = False
  58. else:
  59. keep_len = 12
  60. if len(buffer) > keep_len:
  61. buffer = buffer[-keep_len:]
  62. break
  63. if not in_scratchpad and buffer:
  64. yield buffer
  65. def pull_model_bg():
  66. try: ollama.pull(ACTIVE_MODEL)
  67. except: pass
  68. threading.Thread(target=pull_model_bg, daemon=True).start()
  69. def local_web_search(query: str) -> str:
  70. try:
  71. req = requests.get(f'http://127.0.0.1:8080/search', params={'q': query, 'format': 'json'})
  72. if req.status_code == 200:
  73. data = req.json()
  74. results = data.get('results', [])
  75. if not results: return f"No results found on the web for '{query}'."
  76. snippets = [f"Source: {r.get('url')}\nContent: {r.get('content')}" for r in results[:3]]
  77. return "\n\n".join(snippets)
  78. return "Search engine returned an error."
  79. except Exception as e: return f"Local search engine unreachable: {e}"
  80. search_tool_schema = {
  81. 'type': 'function',
  82. 'function': {
  83. 'name': 'local_web_search',
  84. 'description': 'Search the internet for info not in DB.',
  85. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']},
  86. },
  87. }
  88. def search_nutrition_db(query: str, user_eav=None) -> str:
  89. conn = get_db_connection('app_reader')
  90. if not conn: return "Database connection failed."
  91. try:
  92. with conn.cursor() as cursor:
  93. # Dynamically build strictly-enforced clinical SQL filters
  94. clinical_filters = ""
  95. if user_eav:
  96. for p in user_eav:
  97. name = p['name'].lower()
  98. val = p['value'].lower()
  99. if name in ['condition', 'illness']:
  100. if val == 'diabetes': clinical_filters += " AND m.sugars_100g < 5.0"
  101. elif 'kidney' in val: clinical_filters += " AND m.proteins_100g < 15.0"
  102. elif 'hypertension' in val: clinical_filters += " AND m.sodium_100g < 0.2"
  103. elif name in ['diet', 'religious', 'preference']:
  104. if val == 'kosher': clinical_filters += " AND c.ingredients_text NOT LIKE '%pork%' AND c.ingredients_text NOT LIKE '%shellfish%'"
  105. elif val == 'halal': clinical_filters += " AND c.ingredients_text NOT LIKE '%pork%' AND c.ingredients_text NOT LIKE '%wine%' AND c.ingredients_text NOT LIKE '%alcohol%'"
  106. elif val in ['christian', 'good friday', 'ash wednesday']: clinical_filters += " AND c.ingredients_text NOT LIKE '%meat%' AND c.ingredients_text NOT LIKE '%beef%' AND c.ingredients_text NOT LIKE '%chicken%' AND c.ingredients_text NOT LIKE '%pork%'"
  107. sql = f"""
  108. SELECT c.code, c.product_name, m.proteins_100g, m.fat_100g, m.carbohydrates_100g, m.sugars_100g
  109. FROM food_db.products_core c
  110. LEFT JOIN food_db.products_macros m ON c.code = m.code
  111. WHERE MATCH(c.product_name, c.ingredients_text) AGAINST(%s IN BOOLEAN MODE)
  112. AND c.product_name IS NOT NULL AND c.product_name != '' AND c.product_name != 'None'
  113. {clinical_filters}
  114. """
  115. bool_query = " ".join([f"+{w}" for w in query.split()])
  116. cursor.execute(sql, (bool_query,))
  117. results = cursor.fetchall()
  118. if not results: return f"No database records found for '{query}'."
  119. snippets = []
  120. for r in results:
  121. pro = float(r['proteins_100g'] or 0)
  122. fat = float(r['fat_100g'] or 0)
  123. carb = float(r['carbohydrates_100g'] or 0)
  124. sug = float(r['sugars_100g'] or 0)
  125. snippets.append(f"- {r['product_name']}: Protein {pro:.2f}g, Fat {fat:.2f}g, Carbs {carb:.2f}g, Sugars {sug:.2f}g (per 100g)")
  126. return "\n".join(snippets)
  127. except Exception as e:
  128. return f"Database query failed: {e}"
  129. finally:
  130. conn.close()
  131. db_search_tool_schema = {
  132. 'type': 'function',
  133. 'function': {
  134. 'name': 'search_nutrition_db',
  135. 'description': 'Search the local medical nutrition database for product macros and ingredients. ALWAYS prioritize this over web search.',
  136. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The product or food name to search for (e.g. apple, chicken, bread)'}}, 'required': ['query']},
  137. },
  138. }
  139. def get_db_connection(login_path):
  140. try:
  141. import os
  142. db_host = os.environ.get('DB_HOST')
  143. # Check if environment variables exist for this login path
  144. db_user = os.environ.get(f'{login_path.upper()}_USER') or os.environ.get('DB_USER')
  145. db_pass = os.environ.get(f'{login_path.upper()}_PASS') or os.environ.get('DB_PASS')
  146. if db_host and db_user and db_pass:
  147. return pymysql.connect(
  148. host=db_host,
  149. user=db_user,
  150. password=db_pass,
  151. database='food_db',
  152. cursorclass=pymysql.cursors.DictCursor
  153. )
  154. conf = myloginpath.parse(login_path)
  155. if not conf or not conf.get('user'):
  156. 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.")
  157. return None
  158. return pymysql.connect(
  159. host=conf.get('host', '127.0.0.1'),
  160. user=conf.get('user'),
  161. password=conf.get('password'),
  162. database='food_db',
  163. cursorclass=pymysql.cursors.DictCursor
  164. )
  165. except Exception as e:
  166. st.error(f"Connection Failed: {e}")
  167. return None
  168. from contextlib import contextmanager
  169. @contextmanager
  170. def db_cursor(login_path: str):
  171. conn = get_db_connection(login_path)
  172. if not conn:
  173. yield None
  174. return
  175. try:
  176. with conn.cursor() as cursor:
  177. yield cursor
  178. conn.commit()
  179. except Exception as e:
  180. conn.rollback()
  181. st.error(f"Database query error: {e}")
  182. raise e
  183. finally:
  184. conn.close()
  185. def verify_login(username: str, password: str) -> bool:
  186. with db_cursor('app_auth') as cursor:
  187. if not cursor: return False
  188. cursor.execute("SELECT password_hash FROM users WHERE username = %s", (username,))
  189. result = cursor.fetchone()
  190. if result: return bcrypt.checkpw(password.encode('utf-8'), result['password_hash'].encode('utf-8'))
  191. return False
  192. def get_user_id(username: str) -> Optional[int]:
  193. with db_cursor('app_auth') as cursor:
  194. if not cursor: return None
  195. cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
  196. result = cursor.fetchone()
  197. return result['id'] if result else None
  198. def get_eav_profile(username: str) -> List[Dict[str, Any]]:
  199. uid = get_user_id(username)
  200. if not uid: return []
  201. with db_cursor('app_auth') as cursor:
  202. if not cursor: return []
  203. 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,))
  204. return cursor.fetchall()
  205. def get_user_limit(username: str) -> str:
  206. with db_cursor('app_auth') as cursor:
  207. if not cursor: return "50"
  208. cursor.execute("SELECT search_limit FROM users WHERE username = %s", (username,))
  209. result = cursor.fetchone()
  210. return result['search_limit'] if (result and result['search_limit']) else "50"
  211. def register_user(username: str, password: str, email: str) -> bool:
  212. hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  213. try:
  214. with db_cursor('app_auth') as cursor:
  215. if not cursor: return False
  216. cursor.execute("INSERT INTO users (username, password_hash, email) VALUES (%s, %s, %s)", (username, hashed, email))
  217. send_email(email, "Welcome to Local Food AI", f"Hello {username}, your account was securely created!", to_name=username.title())
  218. return True
  219. except pymysql.err.IntegrityError:
  220. return False
  221. def send_email(to_email: str, subject: str, body: str, to_name: str = "User") -> Any:
  222. msg = EmailMessage()
  223. msg.set_content(body)
  224. msg['Subject'] = subject
  225. msg['From'] = '"Clinical Food AI System" <security@localfoodai.com>'
  226. msg['To'] = f'"{to_name}" <{to_email}>'
  227. for attempt in range(5):
  228. try:
  229. s = smtplib.SMTP('localhost', 25)
  230. s.send_message(msg)
  231. s.quit()
  232. return True
  233. except Exception as e:
  234. if attempt == 4:
  235. return f"SMTP Delivery Failed: {str(e)}"
  236. time.sleep(2)
  237. return "Unknown Error Occurred"
  238. def reset_password(username: str, email: str) -> Any:
  239. with db_cursor('app_auth') as cursor:
  240. if not cursor: return False
  241. cursor.execute("SELECT id, email FROM users WHERE username = %s", (username,))
  242. user = cursor.fetchone()
  243. if user and user['email'] == email:
  244. new_pass = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
  245. hashed = bcrypt.hashpw(new_pass.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  246. cursor.execute("UPDATE users SET password_hash = %s WHERE id = %s", (hashed, user['id']))
  247. status = send_email(email, "Password Reset", f"Your new temporary password is: {new_pass}", to_name=username.title())
  248. return True if status is True else status
  249. return False
  250. # UI Theming
  251. def render_version():
  252. st.markdown("---")
  253. st.caption("🚀 Version: v1.3.0")
  254. try:
  255. git_id = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip()
  256. except Exception:
  257. git_id = "Unknown"
  258. st.caption(f"📅 Git ID: {git_id}")
  259. st.set_page_config(page_title="Food AI Explorer", page_icon="🍔", layout="wide")
  260. @st.cache_resource(experimental_allow_widgets=True)
  261. def get_manager():
  262. return stx.CookieManager()
  263. cookie_manager = get_manager()
  264. if cookie_manager.get(cookie="auth_user"):
  265. st.session_state["authenticated_user"] = cookie_manager.get(cookie="auth_user")
  266. elif "authenticated_user" not in st.session_state:
  267. st.session_state["authenticated_user"] = None
  268. st.markdown("""
  269. <style>
  270. @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap');
  271. html, body, [class*="css"] { font-family: 'Inter', sans-serif; background-color: #0b192c; color: #e2e8f0; }
  272. h1, h2, h3 { color: #38bdf8 !important; font-weight: 600; letter-spacing: 0.5px; }
  273. div[data-testid="stSidebar"] { background: rgba(11, 25, 44, 0.95) !important; backdrop-filter: blur(10px); border-right: 1px solid #1e293b; }
  274. .stButton>button { background: linear-gradient(135deg, #0ea5e9, #0284c7); color: white; border: none; border-radius: 6px; }
  275. .stButton>button:hover { transform: scale(1.02); }
  276. .stTextInput>div>div>input, .stNumberInput>div>div>input, .stSelectbox>div>div>div { background-color: #0f172a; color: #f8fafc; border: 1px solid #38bdf8; caret-color: #f8fafc !important; }
  277. </style>
  278. """, unsafe_allow_html=True)
  279. if "authenticated_user" not in st.session_state:
  280. st.session_state["authenticated_user"] = None
  281. with st.sidebar:
  282. st.title("User Portal 🔐")
  283. render_version()
  284. with st.expander("ℹ️ Welcome"):
  285. st.info("Welcome to the secure Local Food AI environment.")
  286. if st.session_state["authenticated_user"]:
  287. st.success(f"Logged in as: {st.session_state['authenticated_user']}")
  288. if st.button("Logout"):
  289. st.session_state["authenticated_user"] = None
  290. cookie_manager.delete("auth_user")
  291. time.sleep(0.5)
  292. st.rerun()
  293. eav_data = get_eav_profile(st.session_state["authenticated_user"])
  294. uid = get_user_id(st.session_state["authenticated_user"])
  295. user_lim = get_user_limit(st.session_state["authenticated_user"])
  296. with st.expander("⚙️ Account Preferences"):
  297. opts = ["10", "20", "50", "100", "All"]
  298. idx = opts.index(user_lim) if user_lim in opts else 2
  299. new_lim = st.selectbox("Default Search Limit", opts, index=idx)
  300. if new_lim != user_lim:
  301. conn = get_db_connection('app_auth')
  302. with conn.cursor() as c:
  303. c.execute("UPDATE users SET search_limit = %s WHERE id = %s", (new_lim, uid))
  304. conn.commit()
  305. st.rerun()
  306. with st.expander("➕ Add Condition / Diet"):
  307. new_cat = st.selectbox("Category", ["Condition", "Illness", "Diet", "Dislike", "Allergy"])
  308. if new_cat == "Condition":
  309. new_val = st.selectbox("Value", ["Pregnant", "Breastfeeding", "Low Fat"])
  310. elif new_cat == "Illness":
  311. new_val = st.selectbox("Value", ["Diabetes", "Hypertension", "Kidney Disease", "Osteoporosis", "Scurvy", "Anemia"])
  312. elif new_cat == "Diet":
  313. new_val = st.selectbox("Value", ["Vegan", "Vegetarian", "Kosher", "Halal", "Christian", "Good Friday", "Ash Wednesday", "Keto", "Paleo"])
  314. else:
  315. new_val = st.text_input("Value (e.g. 'peanuts', 'broccoli')").strip()
  316. new_val_clean = new_val.lower()
  317. if st.button("Add to Profile") and new_val_clean and uid:
  318. conn = get_db_connection('app_auth')
  319. with conn.cursor() as c:
  320. 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.lower(), new_val_clean))
  321. conn.commit()
  322. st.rerun()
  323. if eav_data:
  324. st.markdown("#### Active Flags")
  325. for e in eav_data:
  326. col1, col2 = st.columns([4, 1])
  327. col1.info(f"**{e['name']}:** {e['value'].title()}")
  328. if col2.button("X", key=f"del_eav_{e['id']}"):
  329. conn = get_db_connection('app_auth')
  330. with conn.cursor() as c:
  331. c.execute("DELETE FROM user_health_profiles WHERE id = %s", (e['id'],))
  332. conn.commit()
  333. st.rerun()
  334. else:
  335. tab1, tab2, tab3 = st.tabs(["Login", "Register", "Reset"])
  336. with tab1:
  337. l_user = st.text_input("Username", key="l_user").strip()
  338. l_pass = st.text_input("Password", type="password", key="l_pass")
  339. if st.button("Login"):
  340. if verify_login(l_user, l_pass):
  341. notifier.send_alert(f"User Login Success: {l_user}")
  342. st.session_state["authenticated_user"] = l_user
  343. st.rerun()
  344. else:
  345. notifier.send_alert(f"User Login Failed: {l_user}")
  346. st.error("Invalid login.")
  347. with tab2:
  348. r_user = st.text_input("Username", key="r_user")
  349. r_email = st.text_input("Email Address", key="r_email")
  350. r_pass = st.text_input("Password", type="password", key="r_pass")
  351. if st.button("Register"):
  352. if len(r_pass) < 6: st.error("Password too short.")
  353. elif register_user(r_user, r_pass, r_email): st.success("Registered safely!")
  354. else: st.error("Username exists.")
  355. with tab3:
  356. f_user = st.text_input("Username", key="f_user")
  357. f_email = st.text_input("Registered Email", key="f_email")
  358. if st.button("Send Reset Link"):
  359. status = reset_password(f_user, f_email)
  360. if status is True:
  361. st.success("Password reset emailed.")
  362. else:
  363. st.error(f"Failed: {status}")
  364. if not st.session_state["authenticated_user"]:
  365. st.title("🍔 Food AI Medical Explorer")
  366. st.info("Please login to interrogate the Clinical Data.")
  367. st.stop()
  368. st.title("🍔 Food AI Clinical Explorer")
  369. conn_reader = get_db_connection('app_reader')
  370. tab_chat, tab_explore, tab_plate, tab_planner = st.tabs(["💬 AI Chat", "🔬 Clinical Search", "🍽️ My Plate Builder", "🤖 AI Meal Planner"])
  371. import re
  372. with tab_chat:
  373. c1, c2 = st.columns([4, 1])
  374. c1.subheader("Chat with the Context")
  375. if c2.button("🧹 Clear Chat"):
  376. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  377. st.rerun()
  378. st.info("""
  379. ℹ️ **How to use this feature (Examples)**
  380. **Your active conditions (e.g. Pregnant, Diabetic) are automatically sent to the AI in the background. You do not need to type them out.**
  381. *Examples:*
  382. 1. "I am pregnant, diabetic, and have kidney problems. Can I eat sushi?"
  383. 2. "What is a safe snack to stabilize my blood sugar without hurting my kidneys?"
  384. 3. "Can I drink milk? I need calcium for the baby."
  385. 4. "Is it safe to eat a large steak for iron?"
  386. 5. "What foods are strictly forbidden for me?"
  387. """)
  388. if "messages" not in st.session_state:
  389. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  390. # Display chat history, filtering out TOOL_CALLS
  391. for msg in st.session_state.messages:
  392. if msg["role"] == "tool": continue
  393. display_text = re.sub(r'\[TOOL_CALLS\]\s*\[.*?\]', '', msg["content"]).strip()
  394. if display_text:
  395. st.chat_message(msg["role"]).write(display_text)
  396. if prompt := st.chat_input("Ask a clinical question about your food..."):
  397. st.session_state.messages.append({"role": "user", "content": prompt})
  398. st.chat_message("user").write(prompt)
  399. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  400. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  401. db_context = search_nutrition_db(prompt, user_eav)
  402. searxng_context = ""
  403. if "No database records found" in db_context:
  404. try:
  405. searxng_url = os.environ.get("SEARXNG_HOST", "http://searxng:8080")
  406. resp = requests.get(f"{searxng_url}/search", params={'q': prompt, 'format': 'json'}, timeout=5)
  407. if resp.status_code == 200:
  408. results = resp.json().get('results', [])
  409. if results:
  410. snippets = [r.get('content', '') for r in results[:3]]
  411. searxng_context = "Web Search Context: " + " | ".join(snippets)
  412. except Exception as e:
  413. pass
  414. sys_prompt = f"""You are a helpful medical data analyst AI.
  415. Health profile: {profile_text}.
  416. Act as a specialized clinical dietitian. Provide a direct answer. Use Chain of Thought reasoning, and skip pleasantries.
  417. Local Database Context: {db_context}
  418. {searxng_context}
  419. """
  420. try:
  421. temp_messages = [{"role": "system", "content": sys_prompt}] + [m for m in st.session_state.messages if m["role"] != "tool"]
  422. start_llm = time.time()
  423. response_stream = ollama.chat(model=ACTIVE_MODEL, messages=temp_messages, stream=True)
  424. with st.chat_message("assistant"):
  425. ai_reply = st.write_stream(chunk['message']['content'] for chunk in response_stream)
  426. st.caption(f"⏱️ AI response generated in {time.time() - start_llm:.2f} seconds")
  427. st.session_state.messages.append({"role": "assistant", "content": ai_reply})
  428. except Exception as e:
  429. ai_reply = f"Hold on! Engine execution fault: {e}"
  430. st.session_state.messages.append({"role": "assistant", "content": ai_reply})
  431. st.chat_message("assistant").write(ai_reply)
  432. def highlight_medical_warnings(row):
  433. try:
  434. val = str(row.get('Medical Warning', ''))
  435. if '⚠️' in val: return ['background-color: rgba(255, 0, 0, 0.4); color: white;'] * len(row)
  436. if '💚' in val: return ['background-color: rgba(0, 255, 0, 0.3); color: white;'] * len(row)
  437. except: pass
  438. return [''] * len(row)
  439. with tab_explore:
  440. st.subheader("Clinical Data Search")
  441. st.info("""
  442. ℹ️ **How to use this feature (Examples)**
  443. **Your active conditions are automatically flagged (⚠️ or 💚) in the search results.**
  444. *Example Searches:*
  445. 1. `Cereal` *(Checks for high sugar & hidden phosphorus)*
  446. 2. `Cheese` *(Checks for unpasteurized pregnancy risks & high sodium)*
  447. 3. `Fruit Juice` *(Checks for high sugar spikes)*
  448. 4. `Deli Meat` *(Checks for Listeria risk & extreme sodium)*
  449. 5. `White Rice` *(Safe for kidneys but flags high glycemic index)*
  450. """)
  451. with st.form("explore_search_form"):
  452. sq = st.text_input("Search Product Name or Ingredient")
  453. cols = st.columns(5)
  454. min_pro = cols[0].number_input("Min Protein (g)", 0, 1000, 0)
  455. min_fat = cols[1].number_input("Min Fat (g)", 0, 1000, 0)
  456. min_carb = cols[2].number_input("Min Carbs (g)", 0, 1000, 0)
  457. max_sug = cols[3].number_input("Max Sugar (g)", 0, 1000, 1000)
  458. # Load dynamically fetched limit to prevent Pandas Styler crash
  459. pd.set_option("styler.render.max_elements", 5000000)
  460. opts = [10, 50, 100, 500, 1000]
  461. user_lim_str = get_user_limit(st.session_state["authenticated_user"])
  462. user_lim_val = 1000 if user_lim_str == "All" else int(user_lim_str)
  463. if user_lim_val not in opts: user_lim_val = 50
  464. idx = opts.index(user_lim_val)
  465. limit_rc = cols[4].selectbox("Limit Results", opts, index=idx)
  466. submit_search = st.form_submit_button("Search Database")
  467. if submit_search:
  468. st.session_state["trigger_search"] = True
  469. if st.session_state.get("trigger_search", False) and sq and conn_reader:
  470. notifier.send_alert(f"Medical DB Search Executed: {sq}")
  471. with st.spinner("Processing massive clinical query..."):
  472. try:
  473. with conn_reader.cursor() as cursor:
  474. l_str = "" if limit_rc == "All" else f"LIMIT {limit_rc}"
  475. query = f"""
  476. SELECT c.code, c.product_name, c.generic_name, c.brands, c.ingredients_text,
  477. a.allergens,
  478. 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,
  479. 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`,
  480. min.calcium_100g, min.iron_100g, min.magnesium_100g, min.potassium_100g, min.zinc_100g
  481. FROM (
  482. SELECT code, product_name, generic_name, brands, ingredients_text
  483. FROM food_db.products_core
  484. WHERE (MATCH(product_name, ingredients_text) AGAINST(%s IN BOOLEAN MODE) OR product_name LIKE %s)
  485. AND product_name IS NOT NULL AND product_name != '' AND product_name != 'None'
  486. ORDER BY MATCH(product_name) AGAINST(%s IN BOOLEAN MODE) DESC, MATCH(ingredients_text) AGAINST(%s IN BOOLEAN MODE) DESC
  487. {l_str}
  488. ) c
  489. LEFT JOIN food_db.products_allergens a ON c.code = a.code
  490. LEFT JOIN food_db.products_macros m ON c.code = m.code
  491. LEFT JOIN food_db.products_vitamins v ON c.code = v.code
  492. LEFT JOIN food_db.products_minerals min ON c.code = min.code
  493. WHERE (m.proteins_100g >= %s OR m.proteins_100g IS NULL)
  494. AND (m.fat_100g >= %s OR m.fat_100g IS NULL)
  495. AND (m.carbohydrates_100g >= %s OR m.carbohydrates_100g IS NULL)
  496. AND (m.sugars_100g <= %s OR m.sugars_100g IS NULL)
  497. """
  498. sq_bool = " ".join([f"+{w}" for w in sq.split()])
  499. sq_like = f"%{sq}%"
  500. start_time = time.time()
  501. cursor.execute(query, (sq_bool, sq_like, sq_bool, sq_bool, min_pro, min_fat, min_carb, max_sug))
  502. results = cursor.fetchall()
  503. elapsed = time.time() - start_time
  504. st.caption(f"⏱️ DB Query Executed in {elapsed:.3f} seconds")
  505. if results:
  506. # Fetch EAV Medical Profile
  507. eav_profile = get_eav_profile(st.session_state["authenticated_user"])
  508. df = pd.DataFrame(results)
  509. st.markdown("### 🛠️ Dynamic Column Display")
  510. default_columns = [
  511. 'code', 'product_name', 'generic_name', 'brands', 'allergens', 'ingredients_text',
  512. 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'sodium_100g', 'energy-kcal_100g',
  513. 'vitamin-c_100g', 'iron_100g', 'calcium_100g'
  514. ]
  515. all_fetched_cols = list(df.columns)
  516. valid_defaults = [c for c in default_columns if c in all_fetched_cols]
  517. if "selected_columns" not in st.session_state or st.button("Reset Default Columns"):
  518. st.session_state["selected_columns"] = valid_defaults
  519. st.rerun()
  520. chosen_cols = st.multiselect("Customize Dataset View", all_fetched_cols, default=st.session_state["selected_columns"], key="multi_cols")
  521. st.session_state["selected_columns"] = chosen_cols
  522. # Filter dataframe gracefully, but we retain a copy for background analytics
  523. df_display = df[chosen_cols].copy()
  524. warnings_col = []
  525. for idx, row in df.iterrows():
  526. warns = []
  527. ing_text = str(row['ingredients_text']).lower()
  528. all_text = str(row['allergens']).lower()
  529. for param in eav_profile:
  530. cat = param['name'].lower()
  531. val = param['value']
  532. # Disease Analytics
  533. if cat == 'illness':
  534. if val == 'diabetes' and pd.notnull(row.get('sugars_100g')) and float(row['sugars_100g']) > 10.0:
  535. warns.append("⚠️ High Sugar (Diabetes)")
  536. if (val == 'hypertension' or val == 'high bp') and pd.notnull(row.get('sodium_100g')) and float(row['sodium_100g']) > 1.5:
  537. warns.append("⚠️ High Salt (Hypertension)")
  538. if val == 'scurvy' and pd.notnull(row.get('vitamin-c_100g')) and float(row['vitamin-c_100g']) > 0.005:
  539. warns.append("💚 High Vitamin C (Scurvy Recommended)")
  540. if val == 'anemia' and pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  541. warns.append("💚 High Iron (Anemia Recommended)")
  542. # Condition Analytics
  543. if cat == 'condition':
  544. if val == 'pregnant':
  545. if ('cru' in ing_text or 'raw' in ing_text or 'viande crue' in ing_text):
  546. warns.append("⚠️ Raw Foods (Pregnancy Toxoplasmosis)")
  547. if pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  548. warns.append("💚 Med-High Iron (Pregnancy Health)")
  549. if val == 'low fat' and pd.notnull(row.get('fat_100g')) and float(row['fat_100g']) > 20.0:
  550. warns.append("⚠️ High Fat")
  551. if val == 'osteoporosis' and pd.notnull(row.get('calcium_100g')) and float(row['calcium_100g']) > 0.1:
  552. warns.append("💚 High Calcium (Bone Health)")
  553. if eav_data:
  554. ing_text = str(row.get('ingredients_text', '')).lower()
  555. all_text = str(row.get('allergens', '')).lower()
  556. product_name_text = str(row.get('product_name', '')).lower()
  557. for e in eav_data:
  558. cat = str(e['name']).lower()
  559. val = str(e['value']).lower()
  560. # Clinical Trace Checks...
  561. if cat == 'condition' and (val == 'pregnant' or val == 'pregnancy' or val == 'breastfeeding'):
  562. # Forbidden / High Risk (Toxoplasmosis & Listeria)
  563. if any(x in ing_text or x in product_name_text for x in ['cru', 'raw', 'viande crue', 'sushi', 'sashimi', 'poisson cru']):
  564. warns.append("⚠️ Forbidden: Raw Meat/Fish (Toxoplasmosis/Parasite Risk)")
  565. if any(x in ing_text or x in product_name_text for x in ['lait cru', 'unpasteurized', 'non pasteurisé']):
  566. warns.append("⚠️ Forbidden: Unpasteurized Dairy (Listeria Risk)")
  567. if any(x in ing_text or x in product_name_text for x in ['alcool', 'wine', 'alcohol', 'beer']):
  568. warns.append("⚠️ Forbidden: Contains Alcohol")
  569. # Recommended (Iron & Calcium)
  570. if float(row.get('iron_100g', 0) or 0) > 0.003:
  571. warns.append("💚 Recommended: High Iron (Pregnancy Health)")
  572. if float(row.get('calcium_100g', 0) or 0) > 0.120:
  573. warns.append("💚 Recommended: High Calcium (Bone Health / Breastfeeding)")
  574. if cat == 'illness' and val == 'osteoporosis':
  575. if float(row.get('calcium_100g', 0) or 0) < 0.120:
  576. warns.append("⚠️ Low Calcium (Osteoporosis Risk)")
  577. else:
  578. warns.append("💚 Recommended (High Calcium)")
  579. if cat == 'illness' and val == 'scurvy':
  580. if float(row.get('vitamin-c_100g', 0) or 0) < 0.010:
  581. warns.append("⚠️ Low Vitamin C (Scurvy Risk)")
  582. else:
  583. warns.append("💚 Recommended (High Vitamin C)")
  584. if cat == 'diet' and val in ['vegan', 'vegetarian']:
  585. if any(x in ing_text for x in ['meat', 'beef', 'chicken', 'fish', 'gelatin', 'whey', 'pork', 'porc', 'poulet']):
  586. warns.append("⚠️ Contains Animal Products")
  587. if cat == 'diet' and val == 'halal':
  588. if any(x in ing_text for x in ['pork', 'pig', 'porc', 'wine', 'alcohol', 'beer', 'vin']):
  589. warns.append("⚠️ Probable Haram Ingredients (e.g. Pork/Wine)")
  590. if cat in ['dislike', 'allergy']:
  591. if val in ing_text or val in all_text or val in product_name_text:
  592. warns.append(f"⚠️ Contains: {val.upper()}")
  593. warnings_col.append(" | ".join(list(set(warns))) if warns else "✅ Safe for Profile")
  594. df_display.insert(0, 'Medical Warning', warnings_col)
  595. df_display.fillna("", inplace=True)
  596. df_display.index = range(1, len(df_display) + 1)
  597. styled_df = df_display.style.apply(highlight_medical_warnings, axis=1)
  598. st.success(f"Analysed {len(results)} records utilizing dynamic Partitions!")
  599. st.dataframe(styled_df, use_container_width=True, hide_index=True)
  600. if st.button("🤖 Ask AI to Evaluate This Table"):
  601. with st.spinner("AI is dynamically evaluating these records against your profile..."):
  602. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  603. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  604. minimal_records = df_display[['product_name', 'Medical Warning']].head(10).to_dict('records')
  605. eval_prompt = f"The user has this profile: {profile_text}. Evaluate these top foods and state which are highly recommended or strictly forbidden: {minimal_records}. Provide a direct, readable clinical summary. Do not output raw JSON."
  606. try:
  607. response = ollama.chat(model=ACTIVE_MODEL, messages=[{'role': 'user', 'content': eval_prompt}], stream=True)
  608. st.write_stream(chunk['message']['content'] for chunk in response)
  609. except Exception as e:
  610. error_msg = str(e).lower()
  611. if "404" in error_msg or "not found" in error_msg:
  612. st.warning("⚠️ The AI engine is currently downloading its core models in the background. Please wait a minute and try again!")
  613. else:
  614. st.error(f"AI Evaluation Failed: {e}")
  615. else:
  616. st.warning("No products found matching those strict terms.")
  617. except Exception as e: st.error(f"SQL/Pandas Error: {e}")
  618. with tab_plate:
  619. st.subheader("🍽️ My Plate Builder")
  620. st.info("""
  621. ℹ️ **How to use this feature (Examples & Logic)**
  622. **Plate Builder Logic:**
  623. 1. Create a New Plate.
  624. 2. Search for exact food words (e.g. 'chicken', 'egg').
  625. 3. Add the food with a specific portion (e.g. '150g').
  626. 4. The system calculates the combined macros.
  627. 5. Use the 🗑️ buttons to delete incorrect items or entire plates.
  628. *Example Plates:*
  629. 1. `150g White Rice` + `50g Chicken Breast` + `100g Green Beans`
  630. 2. `200g Potatoes` + `100g Tomatoes` + `100g Beef`
  631. 3. `100g Spinach Salad` + `50g Feta Cheese`
  632. 4. `200g Lentils` + `100g Quinoa`
  633. 5. `100g Apple` + `30g Almonds`
  634. """)
  635. uid = get_user_id(st.session_state["authenticated_user"])
  636. conn = get_db_connection('app_auth')
  637. if conn and uid:
  638. with conn.cursor() as cursor:
  639. cursor.execute("SELECT id, plate_name FROM plates WHERE user_id = %s", (uid,))
  640. plates = cursor.fetchall()
  641. st.markdown("#### ➕ Create a New Plate")
  642. col_p1, col_p2 = st.columns([3, 1])
  643. new_plate_name = col_p1.text_input("Plate Name (e.g., 'Spaghetti Bolognese')", key="new_plate")
  644. if col_p2.button("Create Plate", use_container_width=True) and new_plate_name:
  645. cursor.execute("INSERT INTO plates (user_id, plate_name) VALUES (%s, %s)", (uid, new_plate_name))
  646. conn.commit()
  647. st.session_state["active_plate"] = new_plate_name
  648. st.rerun()
  649. st.markdown("---")
  650. if plates:
  651. colA, colB = st.columns([4, 1])
  652. plate_names = [p['plate_name'] for p in plates]
  653. 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
  654. selected_plate = colA.selectbox("Select Active Plate to Edit Ingredients", plate_names, index=default_idx)
  655. st.session_state["active_plate"] = selected_plate
  656. active_p_id = next(p['id'] for p in plates if p['plate_name'] == selected_plate)
  657. if colB.button("🗑️ Delete Plate"):
  658. cursor.execute("DELETE FROM plates WHERE id = %s", (active_p_id,))
  659. conn.commit()
  660. if "active_plate" in st.session_state: del st.session_state["active_plate"]
  661. st.rerun()
  662. cursor.execute("""
  663. SELECT i.id, i.product_code, MAX(i.quantity_grams) as quantity_grams, MAX(p.product_name) as product_name,
  664. MAX(m.proteins_100g) as proteins_100g, MAX(m.fat_100g) as fat_100g, MAX(m.carbohydrates_100g) as carbohydrates_100g,
  665. MAX(m.sodium_100g) as sodium_100g, MAX(m.sugars_100g) as sugars_100g, MAX(m.fiber_100g) as fiber_100g,
  666. MAX(v.`vitamin-c_100g`) as vitamin_c_100g, MAX(min.iron_100g) as iron_100g, MAX(min.calcium_100g) as calcium_100g
  667. FROM plate_items i
  668. LEFT JOIN products_core p ON i.product_code = p.code
  669. LEFT JOIN products_macros m ON i.product_code = m.code
  670. LEFT JOIN products_vitamins v ON i.product_code = v.code
  671. LEFT JOIN products_minerals min ON i.product_code = min.code
  672. WHERE i.plate_id = %s
  673. GROUP BY i.id, i.product_code
  674. """, (active_p_id,))
  675. items = cursor.fetchall()
  676. if items:
  677. for i in items:
  678. c1, c2 = st.columns([5, 1])
  679. pro = float(i['proteins_100g'] or 0) * (float(i['quantity_grams'])/100.0)
  680. fat = float(i['fat_100g'] or 0) * (float(i['quantity_grams'])/100.0)
  681. carb = float(i['carbohydrates_100g'] or 0) * (float(i['quantity_grams'])/100.0)
  682. c1.markdown(f"<li><b>{i['quantity_grams']}g</b> of {i['product_name']} (Pro: {pro:.2f}g | Fat: {fat:.2f}g | Carb: {carb:.2f}g)</li>", unsafe_allow_html=True)
  683. if c2.button("🗑️", key=f"del_item_{i['id']}"):
  684. cursor.execute("DELETE FROM plate_items WHERE id = %s", (i['id'],))
  685. conn.commit()
  686. st.rerun()
  687. total_pro = sum((float(i['proteins_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  688. total_fat = sum((float(i['fat_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  689. total_carb = sum((float(i['carbohydrates_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  690. total_sod = sum((float(i['sodium_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  691. total_sug = sum((float(i['sugars_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  692. total_fib = sum((float(i['fiber_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  693. total_vitc = sum((float(i['vitamin_c_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  694. total_iron = sum((float(i['iron_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  695. total_calc = sum((float(i['calcium_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  696. st.markdown("---")
  697. st.markdown("### Plate Totals")
  698. m1, m2, m3 = st.columns(3)
  699. m1.metric("Total Protein", f"{total_pro:.2f}g")
  700. m2.metric("Total Fat", f"{total_fat:.2f}g")
  701. m3.metric("Total Carbs", f"{total_carb:.2f}g")
  702. m4, m5, m6 = st.columns(3)
  703. m4.metric("Sodium", f"{total_sod:.3f}g")
  704. m5.metric("Sugars", f"{total_sug:.2f}g")
  705. m6.metric("Fiber", f"{total_fib:.2f}g")
  706. m7, m8, m9 = st.columns(3)
  707. m7.metric("Vitamin C", f"{total_vitc:.4f}g")
  708. m8.metric("Iron", f"{total_iron:.4f}g")
  709. m9.metric("Calcium", f"{total_calc:.4f}g")
  710. st.markdown("---")
  711. st.markdown("#### ➕ Add Food to Plate")
  712. with st.form("plate_add_form"):
  713. add_search = st.text_input("Search Exact Product Name (e.g. 'chicken', 'egg')")
  714. col_scope, col_comp = st.columns(2)
  715. search_scope = col_scope.radio("Search Scope", ["Auto (Cascaded)", "Product Name Only", "Both (Product & Ingredients)", "Ingredients Only"], horizontal=True)
  716. comp_reqs = col_comp.multiselect("Require Nutrients (Sorts by highest)", ["Iron", "Vitamin C", "Calcium", "Proteins", "Fiber"])
  717. submit_add_search = st.form_submit_button("Search Food")
  718. if add_search and submit_add_search:
  719. bool_search = " ".join([f"+{w}" for w in add_search.split()])
  720. start_time = time.time()
  721. def execute_search(match_col_override=None):
  722. m_col = "product_name"
  723. if match_col_override: m_col = match_col_override
  724. elif "Both" in search_scope: m_col = "product_name, ingredients_text"
  725. elif "Ingredients" in search_scope: m_col = "ingredients_text"
  726. join_min = "LEFT JOIN food_db.products_minerals min ON c.code = min.code" if any(n in comp_reqs for n in ["Iron", "Calcium"]) else ""
  727. join_vit = "LEFT JOIN food_db.products_vitamins v ON c.code = v.code" if "Vitamin C" in comp_reqs else ""
  728. r_clauses, o_clauses = [], []
  729. if "Iron" in comp_reqs: r_clauses.append("min.iron_100g > 0"); o_clauses.append("min.iron_100g DESC")
  730. if "Vitamin C" in comp_reqs: r_clauses.append("v.`vitamin-c_100g` > 0"); o_clauses.append("v.`vitamin-c_100g` DESC")
  731. if "Calcium" in comp_reqs: r_clauses.append("min.calcium_100g > 0"); o_clauses.append("min.calcium_100g DESC")
  732. if "Proteins" in comp_reqs: r_clauses.append("m.proteins_100g > 0"); o_clauses.append("m.proteins_100g DESC")
  733. if "Fiber" in comp_reqs: r_clauses.append("m.fiber_100g > 0"); o_clauses.append("m.fiber_100g DESC")
  734. wh_comp = " AND " + " AND ".join(r_clauses) if r_clauses else ""
  735. order_by = "ORDER BY " + ", ".join(o_clauses) if o_clauses else ""
  736. sql = f"""
  737. SELECT c.code, c.product_name
  738. FROM (
  739. SELECT code, product_name
  740. FROM food_db.products_core
  741. WHERE MATCH({m_col}) AGAINST(%s IN BOOLEAN MODE)
  742. AND product_name IS NOT NULL AND product_name != '' AND product_name != 'None'
  743. ORDER BY LENGTH(product_name) ASC
  744. ) c
  745. JOIN food_db.products_macros m ON c.code = m.code
  746. {join_min}
  747. {join_vit}
  748. WHERE m.proteins_100g IS NOT NULL AND m.fat_100g IS NOT NULL AND m.carbohydrates_100g IS NOT NULL
  749. {wh_comp}
  750. {order_by}
  751. """
  752. cursor.execute(sql, (bool_search,))
  753. return cursor.fetchall()
  754. search_res = execute_search()
  755. if not search_res and search_scope == "Auto (Cascaded)":
  756. st.warning("No product found in names, so I am looking into the ingredients...")
  757. search_res = execute_search("ingredients_text")
  758. elapsed = time.time() - start_time
  759. st.caption(f"⏱️ Plate Search Executed in {elapsed:.3f} seconds")
  760. if search_res:
  761. options = {f"{r['product_name']} ({r['code']})": r for r in search_res}
  762. selected_str = st.selectbox("Select Product", list(options.keys()))
  763. selected_product = options[selected_str]
  764. add_amount_str = st.text_input("Portion Quantity (e.g., '100g', '2 tbsp', '1.5 cups', '1 pinch')", value="100g")
  765. if st.button("Add Item to Plate"):
  766. # Use UnitConverter to parse
  767. grams = UnitConverter.parse_and_convert(add_amount_str, product_name=selected_product['product_name'])
  768. if grams is not None:
  769. cursor.execute("INSERT INTO plate_items (plate_id, product_code, quantity_grams) VALUES (%s, %s, %s)",
  770. (active_p_id, selected_product['code'], grams))
  771. conn.commit()
  772. st.success(f"Added {grams}g of {selected_product['product_name']}!")
  773. st.rerun()
  774. else:
  775. st.error("Could not parse unit. Please use format like '100g' or '1 cup'.")
  776. else:
  777. st.warning("No products found.")
  778. with tab_planner:
  779. st.subheader("🤖 AI Meal Planner")
  780. st.info("""
  781. ℹ️ **How to use this feature (Examples)**
  782. **Your active conditions are automatically applied to the generated menu.**
  783. *Example Prompts:*
  784. 1. "Generate a full day meal plan for me. I am pregnant, diabetic, and have kidney disease."
  785. 2. "Plan a pregnancy-safe dinner that won't spike my blood sugar."
  786. 3. "I need a high-iron lunch that is safe for my kidneys."
  787. 4. "Plan a breakfast without dairy that is kidney-friendly."
  788. 5. "Give me a 3-day meal prep plan ensuring no raw fish, controlled protein portions, and steady complex carbs."
  789. """)
  790. p_col1, p_col2, p_col3 = st.columns(3)
  791. target_cal = p_col1.number_input("Target Daily Calories (kcal)", 1000, 5000, 2000, 50)
  792. diet_pref = p_col2.selectbox("Dietary Preference", ["Omnivore", "Vegetarian", "Vegan", "Keto", "Paleo"])
  793. meal_count = p_col3.slider("Number of Meals", 1, 6, 3)
  794. extra_notes = st.text_input("Any additional allergies or goals?")
  795. if st.button("Generate Professional Menu"):
  796. with st.spinner("Executing Lightning-Fast Context RAG..."):
  797. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  798. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  799. # Pre-fetch database context directly without using AI tools!
  800. # Enforce the strict clinical constraints directly via SQL
  801. db_context = search_nutrition_db(diet_pref, user_eav)
  802. meal_names = ["Breakfast", "Lunch", "Dinner", "Morning Snack", "Afternoon Snack", "Evening Snack"]
  803. selected_meals = ", ".join(meal_names[:int(meal_count)])
  804. sys_prompt = f"""You are a professional clinical Dietitian planner. Target: {target_cal}kcal.
  805. You MUST generate EXACTLY {meal_count} meals and NO MORE. Failure to respect the meal count is a critical clinical error.
  806. The allowed meal(s) are strictly: {selected_meals}.
  807. Dietary constraint: {diet_pref}. Additional notes: {extra_notes}.
  808. Health profile: {profile_text}.
  809. COGNITIVE SCRATCHPAD INSTRUCTIONS:
  810. - You MUST perform all your intermediate thinking, unit conversions (e.g. converting cups, tablespoons, or ounces to exact metric grams based on food density), and calorie/protein mathematical additions inside a `<scratchpad>` tag.
  811. - Format:
  812. <scratchpad>
  813. Calculations:
  814. - 1.5 cups of Cheese = X grams (density Y). Calories = A, Protein = B, Carbs = C, Fat = D.
  815. - 2 tbsp of Peanut Butter = Z grams (density C). Calories = D, Protein = E, Carbs = F, Fat = G.
  816. - Summation: Total Calories = A + D = Z kcal (vs target {target_cal}kcal). Total Protein = B + E = Fg.
  817. </scratchpad>
  818. | Meal Time | Exact Food | Portion Size | Calories | Protein | Carbs | Fat |
  819. | --- | --- | --- | --- | --- | --- | --- |
  820. ...
  821. | Global Total | All Meals | | Total Calories | Total Protein | Total Carbs | Total Fat |
  822. CRITICAL FORMATTING INSTRUCTIONS:
  823. - After the </scratchpad> closing tag, you MUST strictly output the menu formatted as a Markdown Table.
  824. - The table MUST contain exactly 7 columns separated by pipes (|): | Meal Time | Exact Food | Portion Size | Calories | Protein | Carbs | Fat |
  825. - The Portion Size MUST be reported in exactly metric grams (e.g. 200g) and NEVER in cups or oz.
  826. - The items in the table MUST be selected strictly from: {db_context}
  827. - Do NOT output JSON. Do NOT use tool calls. Skip pleasantries.
  828. """
  829. st.info("🧠 AI is analyzing nutritional synergies and generating your plan...")
  830. # Stream the response instantly!
  831. try:
  832. start_llm = time.time()
  833. response = ollama.chat(model=ACTIVE_MODEL, messages=[
  834. {'role': 'system', 'content': sys_prompt},
  835. {'role': 'user', 'content': 'Generate my meal plan as a markdown table.'}
  836. ], stream=True)
  837. clean_stream = filter_scratchpad_stream(response)
  838. ai_reply = st.write_stream(clean_stream)
  839. st.caption(f"⏱️ AI Meal Plan generated in {time.time() - start_llm:.2f} seconds")
  840. # PDF Generation
  841. def generate_pdf(text):
  842. import re
  843. # Aggressive sanitization: if a table row has 4 columns and the last contains a comma or space before 'g', split it
  844. sanitized_lines = []
  845. for line in text.split('\\n'):
  846. line = line.strip()
  847. if line.startswith('|') and line.endswith('|') and '---' not in line:
  848. cols = [c.strip() for c in line.strip('|').split('|')]
  849. # If exactly 4 columns and the last one contains calories and protein merged
  850. if len(cols) == 4 and any(char.isdigit() for char in cols[3]):
  851. # Attempt to split by comma or 'kcal'
  852. if ',' in cols[3]:
  853. split_last = cols[3].split(',', 1)
  854. cols = cols[:3] + [split_last[0].strip(), split_last[1].strip()]
  855. elif 'kcal' in cols[3].lower():
  856. split_last = re.split(r'(?<=kcal)\s+', cols[3], flags=re.IGNORECASE, maxsplit=1)
  857. if len(split_last) == 2:
  858. cols = cols[:3] + [split_last[0].strip(), split_last[1].strip()]
  859. sanitized_lines.append('| ' + ' | '.join(cols) + ' |')
  860. else:
  861. sanitized_lines.append(line)
  862. text = '\\n'.join(sanitized_lines)
  863. pdf = FPDF()
  864. pdf.add_page()
  865. pdf.set_font("Helvetica", 'B', 16)
  866. pdf.cell(0, 10, "Strict Clinical Meal Plan", new_x="LMARGIN", new_y="NEXT", align='C')
  867. pdf.ln(h=5)
  868. in_table = False
  869. table_data = []
  870. def flush_table():
  871. if not table_data: return
  872. pdf.set_font("Helvetica", size=9)
  873. # Auto-calculate col_widths based on 5 columns if present
  874. cw = (20, 40, 15, 10, 15) if len(table_data[0]) == 5 else (20, 30, 15, 10, 10, 10, 10) if len(table_data[0]) >= 7 else None
  875. try:
  876. with pdf.table(text_align="LEFT", col_widths=cw) as table:
  877. for row_data in table_data:
  878. row = table.row()
  879. for datum in row_data:
  880. row.cell(str(datum).encode('latin-1', 'replace').decode('latin-1'))
  881. except Exception as e:
  882. pdf.multi_cell(0, 8, "Table Render Error: " + str(e))
  883. table_data.clear()
  884. pdf.ln(h=5)
  885. for line in text.split('\n'):
  886. line = line.strip()
  887. if not line:
  888. flush_table()
  889. pdf.ln(h=2)
  890. continue
  891. if line.startswith('|') and line.endswith('|'):
  892. if '---' in line: continue
  893. cols = [col.strip() for col in line.strip('|').split('|')]
  894. # Normalize column length to prevent FPDF table crashing
  895. if table_data:
  896. target_len = len(table_data[0])
  897. while len(cols) < target_len: cols.append("")
  898. cols = cols[:target_len]
  899. table_data.append(cols)
  900. else:
  901. flush_table()
  902. pdf.set_font("Helvetica", size=11)
  903. clean_line = str(line).encode('latin-1', 'replace').decode('latin-1')
  904. pdf.multi_cell(0, 8, clean_line)
  905. flush_table()
  906. pdf_path = "/tmp/meal_plan.pdf"
  907. pdf.output(pdf_path)
  908. with open(pdf_path, "rb") as f:
  909. return f.read()
  910. st.download_button(
  911. label="📄 Download PDF Export",
  912. data=generate_pdf(strip_scratchpad(ai_reply)),
  913. file_name="Clinical_Meal_Plan.pdf",
  914. mime="application/pdf",
  915. type="primary"
  916. )
  917. except Exception as e:
  918. error_msg = str(e).lower()
  919. if "404" in error_msg or "not found" in error_msg:
  920. st.warning("⚠️ The AI engine is currently downloading its core models in the background. Please wait a minute and try again!")
  921. else:
  922. st.error(f"AI Generation Failed: {e}")
  923. if conn_reader: conn_reader.close()