app.py 67 KB

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