app.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. # $Id$
  2. # $Author$
  3. # $log$
  4. #ident "@(#)LocalFoodAI:app.py:$Format:%D:%ci:%cN:%h$"
  5. import streamlit as st
  6. import pymysql
  7. import myloginpath
  8. import ollama
  9. import bcrypt
  10. import requests
  11. import string
  12. import random
  13. import smtplib
  14. from email.message import EmailMessage
  15. import pandas as pd
  16. from unit_converter import UnitConverter
  17. from snmp_notifier import notifier
  18. import time
  19. import threading
  20. def pull_model_bg():
  21. try: ollama.pull('llama3.2:1b')
  22. except: pass
  23. threading.Thread(target=pull_model_bg, daemon=True).start()
  24. def local_web_search(query: str) -> str:
  25. try:
  26. req = requests.get(f'http://127.0.0.1:8080/search', params={'q': query, 'format': 'json'})
  27. if req.status_code == 200:
  28. data = req.json()
  29. results = data.get('results', [])
  30. if not results: return f"No results found on the web for '{query}'."
  31. snippets = [f"Source: {r.get('url')}\nContent: {r.get('content')}" for r in results[:3]]
  32. return "\n\n".join(snippets)
  33. return "Search engine returned an error."
  34. except Exception as e: return f"Local search engine unreachable: {e}"
  35. search_tool_schema = {
  36. 'type': 'function',
  37. 'function': {
  38. 'name': 'local_web_search',
  39. 'description': 'Search the internet for info not in DB.',
  40. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']},
  41. },
  42. }
  43. def search_nutrition_db(query: str, user_eav=None) -> str:
  44. conn = get_db_connection('app_reader')
  45. if not conn: return "Database connection failed."
  46. try:
  47. with conn.cursor() as cursor:
  48. # Dynamically build strictly-enforced clinical SQL filters
  49. clinical_filters = ""
  50. if user_eav:
  51. for p in user_eav:
  52. name = p['name'].lower()
  53. val = p['value'].lower()
  54. if name in ['condition', 'illness']:
  55. if val == 'diabetes': clinical_filters += " AND m.sugars_100g < 5.0"
  56. elif 'kidney' in val: clinical_filters += " AND m.proteins_100g < 15.0"
  57. elif 'hypertension' in val: clinical_filters += " AND m.sodium_100g < 0.2"
  58. elif name in ['diet', 'religious', 'preference']:
  59. if val == 'kosher': clinical_filters += " AND c.ingredients_text NOT LIKE '%pork%' AND c.ingredients_text NOT LIKE '%shellfish%'"
  60. 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%'"
  61. 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%'"
  62. sql = f"""
  63. SELECT c.code, c.product_name, m.proteins_100g, m.fat_100g, m.carbohydrates_100g, m.sugars_100g
  64. FROM food_db.products_core c
  65. LEFT JOIN food_db.products_macros m ON c.code = m.code
  66. WHERE MATCH(c.product_name, c.ingredients_text) AGAINST(%s IN BOOLEAN MODE)
  67. AND c.product_name IS NOT NULL AND c.product_name != '' AND c.product_name != 'None'
  68. {clinical_filters}
  69. LIMIT 15
  70. """
  71. bool_query = " ".join([f"+{w}" for w in query.split()])
  72. cursor.execute(sql, (bool_query,))
  73. results = cursor.fetchall()
  74. if not results: return f"No database records found for '{query}'."
  75. snippets = []
  76. for r in results:
  77. snippets.append(f"- {r['product_name']}: Protein {r['proteins_100g']}g, Fat {r['fat_100g']}g, Carbs {r['carbohydrates_100g']}g, Sugars {r['sugars_100g']}g (per 100g)")
  78. return "\n".join(snippets)
  79. except Exception as e:
  80. return f"Database query failed: {e}"
  81. finally:
  82. conn.close()
  83. db_search_tool_schema = {
  84. 'type': 'function',
  85. 'function': {
  86. 'name': 'search_nutrition_db',
  87. 'description': 'Search the local medical nutrition database for product macros and ingredients. ALWAYS prioritize this over web search.',
  88. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The product or food name to search for (e.g. apple, chicken, bread)'}}, 'required': ['query']},
  89. },
  90. }
  91. def get_db_connection(login_path):
  92. try:
  93. import os
  94. db_host = os.environ.get('DB_HOST')
  95. # Check if environment variables exist for this login path
  96. db_user = os.environ.get(f'{login_path.upper()}_USER') or os.environ.get('DB_USER')
  97. db_pass = os.environ.get(f'{login_path.upper()}_PASS') or os.environ.get('DB_PASS')
  98. if db_host and db_user and db_pass:
  99. return pymysql.connect(
  100. host=db_host,
  101. user=db_user,
  102. password=db_pass,
  103. database='food_db',
  104. cursorclass=pymysql.cursors.DictCursor
  105. )
  106. conf = myloginpath.parse(login_path)
  107. if not conf or not conf.get('user'):
  108. 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.")
  109. return None
  110. return pymysql.connect(
  111. host=conf.get('host', '127.0.0.1'),
  112. user=conf.get('user'),
  113. password=conf.get('password'),
  114. database='food_db',
  115. cursorclass=pymysql.cursors.DictCursor
  116. )
  117. except Exception as e:
  118. st.error(f"Connection Failed: {e}")
  119. return None
  120. def verify_login(username, password):
  121. conn = get_db_connection('app_auth')
  122. if not conn: return False
  123. with conn.cursor() as cursor:
  124. cursor.execute("SELECT password_hash FROM users WHERE username = %s LIMIT 1", (username,))
  125. result = cursor.fetchone()
  126. conn.close()
  127. if result: return bcrypt.checkpw(password.encode('utf-8'), result['password_hash'].encode('utf-8'))
  128. return False
  129. def get_user_id(username):
  130. conn = get_db_connection('app_auth')
  131. if not conn: return None
  132. with conn.cursor() as cursor:
  133. cursor.execute("SELECT id FROM users WHERE username = %s LIMIT 1", (username,))
  134. result = cursor.fetchone()
  135. conn.close()
  136. return result['id'] if result else None
  137. def get_eav_profile(username):
  138. uid = get_user_id(username)
  139. if not uid: return []
  140. conn = get_db_connection('app_auth')
  141. with conn.cursor() as cursor:
  142. 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,))
  143. res = cursor.fetchall()
  144. conn.close()
  145. return res
  146. def get_user_limit(username):
  147. conn = get_db_connection('app_auth')
  148. if not conn: return "50"
  149. with conn.cursor() as cursor:
  150. cursor.execute("SELECT search_limit FROM users WHERE username = %s LIMIT 1", (username,))
  151. result = cursor.fetchone()
  152. conn.close()
  153. return result['search_limit'] if (result and result['search_limit']) else "50"
  154. def register_user(username, password, email):
  155. conn = get_db_connection('app_auth')
  156. if not conn: return False
  157. hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  158. try:
  159. with conn.cursor() as cursor:
  160. cursor.execute("INSERT INTO users (username, password_hash, email) VALUES (%s, %s, %s)", (username, hashed, email))
  161. conn.commit()
  162. conn.close()
  163. send_email(email, "Welcome to Local Food AI", f"Hello {username}, your account was securely created!", to_name=username.title())
  164. return True
  165. except pymysql.err.IntegrityError:
  166. return False
  167. def send_email(to_email, subject, body, to_name="User"):
  168. msg = EmailMessage()
  169. msg.set_content(body)
  170. msg['Subject'] = subject
  171. msg['From'] = '"Clinical Food AI System" <security@localfoodai.com>'
  172. msg['To'] = f'"{to_name}" <{to_email}>'
  173. for attempt in range(5):
  174. try:
  175. s = smtplib.SMTP('localhost', 25)
  176. s.send_message(msg)
  177. s.quit()
  178. return True
  179. except Exception as e:
  180. if attempt == 4:
  181. return f"SMTP Delivery Failed: {str(e)}"
  182. time.sleep(2)
  183. return "Unknown Error Occurred"
  184. def reset_password(username, email):
  185. conn = get_db_connection('app_auth')
  186. if not conn: return False
  187. with conn.cursor() as cursor:
  188. cursor.execute("SELECT id, email FROM users WHERE username = %s", (username,))
  189. user = cursor.fetchone()
  190. if user and user['email'] == email:
  191. new_pass = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
  192. hashed = bcrypt.hashpw(new_pass.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  193. cursor.execute("UPDATE users SET password_hash = %s WHERE id = %s", (hashed, user['id']))
  194. conn.commit()
  195. conn.close()
  196. status = send_email(email, "Password Reset", f"Your new temporary password is: {new_pass}", to_name=username.title())
  197. if status is True:
  198. return True
  199. return status
  200. return False
  201. # UI Theming
  202. def render_version():
  203. st.markdown("---")
  204. st.caption("🚀 Version: v1.3.0")
  205. st.caption(f"📅 Git ID: $Id$")
  206. st.set_page_config(page_title="Food AI Explorer", page_icon="🍔", layout="wide")
  207. st.markdown("""
  208. <style>
  209. @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap');
  210. html, body, [class*="css"] { font-family: 'Inter', sans-serif; background-color: #0b192c; color: #e2e8f0; }
  211. h1, h2, h3 { color: #38bdf8 !important; font-weight: 600; letter-spacing: 0.5px; }
  212. div[data-testid="stSidebar"] { background: rgba(11, 25, 44, 0.95) !important; backdrop-filter: blur(10px); border-right: 1px solid #1e293b; }
  213. .stButton>button { background: linear-gradient(135deg, #0ea5e9, #0284c7); color: white; border: none; border-radius: 6px; }
  214. .stButton>button:hover { transform: scale(1.02); }
  215. .stTextInput>div>div>input, .stNumberInput>div>div>input, .stSelectbox>div>div>div { background-color: #0f172a; color: #f8fafc; border: 1px solid #38bdf8; }
  216. </style>
  217. """, unsafe_allow_html=True)
  218. if "authenticated_user" not in st.session_state:
  219. st.session_state["authenticated_user"] = None
  220. with st.sidebar:
  221. st.title("User Portal 🔐")
  222. render_version()
  223. with st.expander("🛠️ Diagnostic: App Database View"):
  224. conn = get_db_connection('app_auth')
  225. if conn:
  226. with conn.cursor() as c:
  227. c.execute("DESCRIBE users;")
  228. st.json(c.fetchall())
  229. c.execute("SELECT DATABASE(), CURRENT_USER();")
  230. st.json(c.fetchall())
  231. conn.close()
  232. if st.session_state["authenticated_user"]:
  233. st.success(f"Logged in as: {st.session_state['authenticated_user']}")
  234. if st.button("Logout"):
  235. st.session_state["authenticated_user"] = None
  236. st.rerun()
  237. eav_data = get_eav_profile(st.session_state["authenticated_user"])
  238. uid = get_user_id(st.session_state["authenticated_user"])
  239. user_lim = get_user_limit(st.session_state["authenticated_user"])
  240. with st.expander("⚙️ Account Preferences"):
  241. opts = ["10", "20", "50", "100", "All"]
  242. idx = opts.index(user_lim) if user_lim in opts else 2
  243. new_lim = st.selectbox("Default Search Limit", opts, index=idx)
  244. if new_lim != user_lim:
  245. conn = get_db_connection('app_auth')
  246. with conn.cursor() as c:
  247. c.execute("UPDATE users SET search_limit = %s WHERE id = %s", (new_lim, uid))
  248. conn.commit()
  249. st.rerun()
  250. with st.expander("➕ Add Condition / Diet"):
  251. new_cat = st.selectbox("Category", ["Condition", "Illness", "Diet", "Dislike", "Allergy"])
  252. new_val = st.text_input("Value (e.g. 'vegan', 'diabetes', 'broccoli')").strip().lower()
  253. if st.button("Add to Profile") and new_val and uid:
  254. conn = get_db_connection('app_auth')
  255. with conn.cursor() as c:
  256. c.execute("INSERT INTO user_health_profiles (user_id, illness_health_condition_diet_dislikes_name, illness_health_condition_diet_dislikes_value) VALUES (%s, %s, %s)", (uid, new_cat, new_val))
  257. conn.commit()
  258. st.rerun()
  259. if eav_data:
  260. st.markdown("#### Active Flags")
  261. for e in eav_data:
  262. col1, col2 = st.columns([4, 1])
  263. col1.info(f"**{e['name']}:** {e['value'].title()}")
  264. if col2.button("X", key=f"del_eav_{e['id']}"):
  265. conn = get_db_connection('app_auth')
  266. with conn.cursor() as c:
  267. c.execute("DELETE FROM user_health_profiles WHERE id = %s", (e['id'],))
  268. conn.commit()
  269. st.rerun()
  270. else:
  271. tab1, tab2, tab3 = st.tabs(["Login", "Register", "Reset"])
  272. with tab1:
  273. l_user = st.text_input("Username", key="l_user").strip()
  274. l_pass = st.text_input("Password", type="password", key="l_pass")
  275. if st.button("Login"):
  276. if verify_login(l_user, l_pass):
  277. notifier.send_alert(f"User Login Success: {l_user}")
  278. st.session_state["authenticated_user"] = l_user
  279. st.rerun()
  280. else:
  281. notifier.send_alert(f"User Login Failed: {l_user}")
  282. st.error("Invalid login.")
  283. with tab2:
  284. r_user = st.text_input("Username", key="r_user")
  285. r_email = st.text_input("Email Address", key="r_email")
  286. r_pass = st.text_input("Password", type="password", key="r_pass")
  287. if st.button("Register"):
  288. if len(r_pass) < 6: st.error("Password too short.")
  289. elif register_user(r_user, r_pass, r_email): st.success("Registered safely!")
  290. else: st.error("Username exists.")
  291. with tab3:
  292. f_user = st.text_input("Username", key="f_user")
  293. f_email = st.text_input("Registered Email", key="f_email")
  294. if st.button("Send Reset Link"):
  295. status = reset_password(f_user, f_email)
  296. if status is True:
  297. st.success("Password reset emailed.")
  298. else:
  299. st.error(f"Failed: {status}")
  300. if not st.session_state["authenticated_user"]:
  301. st.title("🍔 Food AI Medical Explorer")
  302. st.info("Please login to interrogate the Clinical Data.")
  303. st.stop()
  304. st.title("🍔 Food AI Clinical Explorer")
  305. conn_reader = get_db_connection('app_reader')
  306. tab_chat, tab_explore, tab_plate, tab_planner = st.tabs(["💬 AI Chat", "🔬 Clinical Search", "🍽️ My Plate Builder", "🤖 AI Meal Planner"])
  307. import re
  308. with tab_chat:
  309. c1, c2 = st.columns([4, 1])
  310. c1.subheader("Chat with the Context")
  311. if c2.button("🧹 Clear Chat"):
  312. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  313. st.rerun()
  314. st.info("""
  315. ℹ️ **How to use this feature (Examples)**
  316. **Your active conditions (e.g. Pregnant, Diabetic) are automatically sent to the AI in the background. You do not need to type them out.**
  317. *Examples:*
  318. 1. "I am pregnant, diabetic, and have kidney problems. Can I eat sushi?"
  319. 2. "What is a safe snack to stabilize my blood sugar without hurting my kidneys?"
  320. 3. "Can I drink milk? I need calcium for the baby."
  321. 4. "Is it safe to eat a large steak for iron?"
  322. 5. "What foods are strictly forbidden for me?"
  323. """)
  324. if "messages" not in st.session_state:
  325. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  326. # Display chat history, filtering out TOOL_CALLS
  327. for msg in st.session_state.messages:
  328. if msg["role"] == "tool": continue
  329. display_text = re.sub(r'\[TOOL_CALLS\]\s*\[.*?\]', '', msg["content"]).strip()
  330. if display_text:
  331. st.chat_message(msg["role"]).write(display_text)
  332. if prompt := st.chat_input("Ask a clinical question about your food..."):
  333. st.session_state.messages.append({"role": "user", "content": prompt})
  334. st.chat_message("user").write(prompt)
  335. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  336. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  337. sys_prompt = f"""You are a helpful medical data analyst AI.
  338. Health profile: {profile_text}.
  339. Act as a specialized clinical dietitian. Provide a direct answer. Skip all thinking, reasoning, and pleasantries.
  340. Use this database context if relevant to the user's question: {search_nutrition_db(prompt)}
  341. """
  342. try:
  343. temp_messages = [{"role": "system", "content": sys_prompt}] + [m for m in st.session_state.messages if m["role"] != "tool"]
  344. response_stream = ollama.chat(model='llama3.2:1b', messages=temp_messages, stream=True)
  345. with st.chat_message("assistant"):
  346. ai_reply = st.write_stream(chunk['message']['content'] for chunk in response_stream)
  347. st.session_state.messages.append({"role": "assistant", "content": ai_reply})
  348. except Exception as e:
  349. ai_reply = f"Hold on! Engine execution fault: {e}"
  350. st.session_state.messages.append({"role": "assistant", "content": ai_reply})
  351. st.chat_message("assistant").write(ai_reply)
  352. def highlight_medical_warnings(row):
  353. try:
  354. val = str(row.get('Medical Warning', ''))
  355. if '⚠️' in val: return ['background-color: rgba(255, 0, 0, 0.4); color: white;'] * len(row)
  356. if '💚' in val: return ['background-color: rgba(0, 255, 0, 0.3); color: white;'] * len(row)
  357. except: pass
  358. return [''] * len(row)
  359. with tab_explore:
  360. st.subheader("Clinical Data Search")
  361. st.info("""
  362. ℹ️ **How to use this feature (Examples)**
  363. **Your active conditions are automatically flagged (⚠️ or 💚) in the search results.**
  364. *Example Searches:*
  365. 1. `Cereal` *(Checks for high sugar & hidden phosphorus)*
  366. 2. `Cheese` *(Checks for unpasteurized pregnancy risks & high sodium)*
  367. 3. `Fruit Juice` *(Checks for high sugar spikes)*
  368. 4. `Deli Meat` *(Checks for Listeria risk & extreme sodium)*
  369. 5. `White Rice` *(Safe for kidneys but flags high glycemic index)*
  370. """)
  371. sq = st.text_input("Search Product Name or Ingredient")
  372. cols = st.columns(5)
  373. min_pro = cols[0].number_input("Min Protein (g)", 0, 1000, 0)
  374. min_fat = cols[1].number_input("Min Fat (g)", 0, 1000, 0)
  375. min_carb = cols[2].number_input("Min Carbs (g)", 0, 1000, 0)
  376. max_sug = cols[3].number_input("Max Sugar (g)", 0, 1000, 1000)
  377. # Load dynamically fetched limit to prevent Pandas Styler crash
  378. pd.set_option("styler.render.max_elements", 5000000)
  379. opts = [10, 50, 100, 500, 1000]
  380. user_lim_str = get_user_limit(st.session_state["authenticated_user"])
  381. user_lim_val = 1000 if user_lim_str == "All" else int(user_lim_str)
  382. if user_lim_val not in opts: user_lim_val = 50
  383. idx = opts.index(user_lim_val)
  384. limit_rc = cols[4].selectbox("Limit Results", opts, index=idx)
  385. if st.button("Search Database") and sq and conn_reader:
  386. notifier.send_alert(f"Medical DB Search Executed: {sq}")
  387. with st.spinner("Processing massive clinical query..."):
  388. try:
  389. with conn_reader.cursor() as cursor:
  390. l_str = "" if limit_rc == "All" else f"LIMIT {limit_rc}"
  391. query = f"""
  392. SELECT c.code, c.product_name, c.generic_name, c.brands, c.ingredients_text,
  393. a.allergens,
  394. 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,
  395. 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`,
  396. min.calcium_100g, min.iron_100g, min.magnesium_100g, min.potassium_100g, min.zinc_100g
  397. FROM (
  398. SELECT code, product_name, generic_name, brands, ingredients_text
  399. FROM food_db.products_core
  400. WHERE MATCH(product_name, ingredients_text) AGAINST(%s IN BOOLEAN MODE)
  401. AND product_name IS NOT NULL AND product_name != '' AND product_name != 'None'
  402. {l_str}
  403. ) c
  404. LEFT JOIN food_db.products_allergens a ON c.code = a.code
  405. LEFT JOIN food_db.products_macros m ON c.code = m.code
  406. LEFT JOIN food_db.products_vitamins v ON c.code = v.code
  407. LEFT JOIN food_db.products_minerals min ON c.code = min.code
  408. WHERE (m.proteins_100g >= %s OR m.proteins_100g IS NULL)
  409. AND (m.fat_100g >= %s OR m.fat_100g IS NULL)
  410. AND (m.carbohydrates_100g >= %s OR m.carbohydrates_100g IS NULL)
  411. AND (m.sugars_100g <= %s OR m.sugars_100g IS NULL)
  412. """
  413. sq_bool = " ".join([f"+{w}" for w in sq.split()])
  414. start_time = time.time()
  415. cursor.execute(query, (sq_bool, min_pro, min_fat, min_carb, max_sug))
  416. results = cursor.fetchall()
  417. elapsed = time.time() - start_time
  418. st.caption(f"⏱️ DB Query Executed in {elapsed:.3f} seconds")
  419. if results:
  420. # Fetch EAV Medical Profile
  421. eav_profile = get_eav_profile(st.session_state["authenticated_user"])
  422. df = pd.DataFrame(results)
  423. st.markdown("### 🛠️ Dynamic Column Display")
  424. default_columns = [
  425. 'code', 'product_name', 'generic_name', 'brands', 'allergens', 'ingredients_text',
  426. 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'sodium_100g', 'energy-kcal_100g',
  427. 'vitamin-c_100g', 'iron_100g', 'calcium_100g'
  428. ]
  429. all_fetched_cols = list(df.columns)
  430. valid_defaults = [c for c in default_columns if c in all_fetched_cols]
  431. if "selected_columns" not in st.session_state or st.button("Reset Default Columns"):
  432. st.session_state["selected_columns"] = valid_defaults
  433. st.rerun()
  434. chosen_cols = st.multiselect("Customize Dataset View", all_fetched_cols, default=st.session_state["selected_columns"], key="multi_cols")
  435. st.session_state["selected_columns"] = chosen_cols
  436. # Filter dataframe gracefully, but we retain a copy for background analytics
  437. df_display = df[chosen_cols].copy()
  438. warnings_col = []
  439. for idx, row in df.iterrows():
  440. warns = []
  441. ing_text = str(row['ingredients_text']).lower()
  442. all_text = str(row['allergens']).lower()
  443. for param in eav_profile:
  444. cat = param['name'].lower()
  445. val = param['value']
  446. # Disease Analytics
  447. if cat == 'illness':
  448. if val == 'diabetes' and pd.notnull(row.get('sugars_100g')) and float(row['sugars_100g']) > 10.0:
  449. warns.append("⚠️ High Sugar (Diabetes)")
  450. if (val == 'hypertension' or val == 'high bp') and pd.notnull(row.get('sodium_100g')) and float(row['sodium_100g']) > 1.5:
  451. warns.append("⚠️ High Salt (Hypertension)")
  452. if val == 'scurvy' and pd.notnull(row.get('vitamin-c_100g')) and float(row['vitamin-c_100g']) > 0.005:
  453. warns.append("💚 High Vitamin C (Scurvy Recommended)")
  454. if val == 'anemia' and pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  455. warns.append("💚 High Iron (Anemia Recommended)")
  456. # Condition Analytics
  457. if cat == 'condition':
  458. if val == 'pregnant':
  459. if ('cru' in ing_text or 'raw' in ing_text or 'viande crue' in ing_text):
  460. warns.append("⚠️ Raw Foods (Pregnancy Toxoplasmosis)")
  461. if pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  462. warns.append("💚 Med-High Iron (Pregnancy Health)")
  463. if val == 'low fat' and pd.notnull(row.get('fat_100g')) and float(row['fat_100g']) > 20.0:
  464. warns.append("⚠️ High Fat")
  465. if val == 'osteoporosis' and pd.notnull(row.get('calcium_100g')) and float(row['calcium_100g']) > 0.1:
  466. warns.append("💚 High Calcium (Bone Health)")
  467. if eav_data:
  468. ing_text = str(row.get('ingredients_text', '')).lower()
  469. all_text = str(row.get('allergens', '')).lower()
  470. product_name_text = str(row.get('product_name', '')).lower()
  471. for e in eav_data:
  472. cat = str(e['name']).lower()
  473. val = str(e['value']).lower()
  474. # Clinical Trace Checks...
  475. if cat == 'condition' and (val == 'pregnant' or val == 'pregnancy' or val == 'breastfeeding'):
  476. # Forbidden / High Risk (Toxoplasmosis & Listeria)
  477. if any(x in ing_text or x in product_name_text for x in ['cru', 'raw', 'viande crue', 'sushi', 'sashimi', 'poisson cru']):
  478. warns.append("⚠️ Forbidden: Raw Meat/Fish (Toxoplasmosis/Parasite Risk)")
  479. if any(x in ing_text or x in product_name_text for x in ['lait cru', 'unpasteurized', 'non pasteurisé']):
  480. warns.append("⚠️ Forbidden: Unpasteurized Dairy (Listeria Risk)")
  481. if any(x in ing_text or x in product_name_text for x in ['alcool', 'wine', 'alcohol', 'beer']):
  482. warns.append("⚠️ Forbidden: Contains Alcohol")
  483. # Recommended (Iron & Calcium)
  484. if float(row.get('iron_100g', 0) or 0) > 0.003:
  485. warns.append("💚 Recommended: High Iron (Pregnancy Health)")
  486. if float(row.get('calcium_100g', 0) or 0) > 0.120:
  487. warns.append("💚 Recommended: High Calcium (Bone Health / Breastfeeding)")
  488. if cat == 'illness' and val == 'osteoporosis':
  489. if float(row.get('calcium_100g', 0) or 0) < 0.120:
  490. warns.append("⚠️ Low Calcium (Osteoporosis Risk)")
  491. else:
  492. warns.append("💚 Recommended (High Calcium)")
  493. if cat == 'illness' and val == 'scurvy':
  494. if float(row.get('vitamin-c_100g', 0) or 0) < 0.010:
  495. warns.append("⚠️ Low Vitamin C (Scurvy Risk)")
  496. else:
  497. warns.append("💚 Recommended (High Vitamin C)")
  498. if cat == 'diet' and val in ['vegan', 'vegetarian']:
  499. if any(x in ing_text for x in ['meat', 'beef', 'chicken', 'fish', 'gelatin', 'whey', 'pork', 'porc', 'poulet']):
  500. warns.append("⚠️ Contains Animal Products")
  501. if cat == 'diet' and val == 'halal':
  502. if any(x in ing_text for x in ['pork', 'pig', 'porc', 'wine', 'alcohol', 'beer', 'vin']):
  503. warns.append("⚠️ Probable Haram Ingredients (e.g. Pork/Wine)")
  504. if cat in ['dislike', 'allergy']:
  505. if val in ing_text or val in all_text or val in product_name_text:
  506. warns.append(f"⚠️ Contains: {val.upper()}")
  507. warnings_col.append(" | ".join(list(set(warns))) if warns else "✅ Safe for Profile")
  508. df_display.insert(0, 'Medical Warning', warnings_col)
  509. styled_df = df_display.style.apply(highlight_medical_warnings, axis=1)
  510. st.success(f"Analysed {len(results)} records utilizing dynamic Partitions!")
  511. st.dataframe(styled_df, use_container_width=True)
  512. if st.button("🤖 Ask AI to Evaluate This Table"):
  513. with st.spinner("AI is dynamically evaluating these records against your profile..."):
  514. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  515. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  516. eval_prompt = f"The user has this profile: {profile_text}. Evaluate these foods and state which are highly recommended or strictly forbidden: {df_display.to_dict('records')}. Provide a direct answer. Skip all thinking, reasoning, and pleasantries."
  517. try:
  518. response_stream = ollama.chat(model='llama3.2:1b', messages=[{'role': 'user', 'content': eval_prompt}], stream=True)
  519. st.write_stream(chunk['message']['content'] for chunk in response_stream)
  520. except Exception as e:
  521. error_msg = str(e).lower()
  522. if "404" in error_msg or "not found" in error_msg:
  523. st.warning("⚠️ The AI engine is currently downloading its core models in the background. Please wait a minute and try again!")
  524. else:
  525. st.error(f"AI Evaluation Failed: {e}")
  526. else:
  527. st.warning("No products found matching those strict terms.")
  528. except Exception as e: st.error(f"SQL/Pandas Error: {e}")
  529. with tab_plate:
  530. st.subheader("🍽️ My Plate Builder")
  531. st.info("""
  532. ℹ️ **How to use this feature (Examples & Logic)**
  533. **Plate Builder Logic:**
  534. 1. Create a New Plate.
  535. 2. Search for exact food words (e.g. 'chicken', 'egg').
  536. 3. Add the food with a specific portion (e.g. '150g').
  537. 4. The system calculates the combined macros.
  538. 5. Use the 🗑️ buttons to delete incorrect items or entire plates.
  539. *Example Plates:*
  540. 1. `150g White Rice` + `50g Chicken Breast` + `100g Green Beans`
  541. 2. `200g Potatoes` + `100g Tomatoes` + `100g Beef`
  542. 3. `100g Spinach Salad` + `50g Feta Cheese`
  543. 4. `200g Lentils` + `100g Quinoa`
  544. 5. `100g Apple` + `30g Almonds`
  545. """)
  546. uid = get_user_id(st.session_state["authenticated_user"])
  547. conn = get_db_connection('app_auth')
  548. if conn and uid:
  549. with conn.cursor() as cursor:
  550. cursor.execute("SELECT id, plate_name FROM plates WHERE user_id = %s", (uid,))
  551. plates = cursor.fetchall()
  552. with st.expander("➕ Create a New Plate"):
  553. new_plate_name = st.text_input("Plate Name")
  554. if st.button("Create Plate"):
  555. cursor.execute("INSERT INTO plates (user_id, plate_name) VALUES (%s, %s)", (uid, new_plate_name))
  556. conn.commit()
  557. st.session_state["active_plate"] = new_plate_name
  558. st.rerun()
  559. if plates:
  560. colA, colB = st.columns([4, 1])
  561. plate_names = [p['plate_name'] for p in plates]
  562. 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
  563. selected_plate = colA.selectbox("Select Active Plate", plate_names, index=default_idx)
  564. st.session_state["active_plate"] = selected_plate
  565. active_p_id = next(p['id'] for p in plates if p['plate_name'] == selected_plate)
  566. if colB.button("🗑️ Delete Plate"):
  567. cursor.execute("DELETE FROM plates WHERE id = %s", (active_p_id,))
  568. conn.commit()
  569. if "active_plate" in st.session_state: del st.session_state["active_plate"]
  570. st.rerun()
  571. cursor.execute("""
  572. SELECT i.id, i.product_code, MAX(i.quantity_grams) as quantity_grams, MAX(p.product_name) as product_name, MAX(m.proteins_100g) as proteins_100g, MAX(m.fat_100g) as fat_100g, MAX(m.carbohydrates_100g) as carbohydrates_100g
  573. FROM plate_items i LEFT JOIN products_core p ON i.product_code = p.code LEFT JOIN products_macros m ON i.product_code = m.code WHERE i.plate_id = %s
  574. GROUP BY i.id, i.product_code
  575. """, (active_p_id,))
  576. items = cursor.fetchall()
  577. if items:
  578. for i in items:
  579. c1, c2 = st.columns([5, 1])
  580. c1.markdown(f"<li><b>{i['quantity_grams']}g</b> of {i['product_name']} (Pro: {i['proteins_100g'] or 0}g)</li>", unsafe_allow_html=True)
  581. if c2.button("🗑️", key=f"del_item_{i['id']}"):
  582. cursor.execute("DELETE FROM plate_items WHERE id = %s", (i['id'],))
  583. conn.commit()
  584. st.rerun()
  585. total_pro = sum((float(i['proteins_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  586. total_fat = sum((float(i['fat_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  587. total_carb = sum((float(i['carbohydrates_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  588. st.info(f"**Total Protein:** {total_pro:.1f}g | **Total Fat:** {total_fat:.1f}g | **Total Carbs:** {total_carb:.1f}g")
  589. st.markdown("---")
  590. st.markdown("#### ➕ Add Food to Plate")
  591. add_search = st.text_input("Search Exact Product Name (e.g. 'chicken', 'egg')")
  592. col_scope, col_comp = st.columns(2)
  593. search_scope = col_scope.radio("Search Scope", ["Auto (Cascaded)", "Product Name Only", "Both (Product & Ingredients)", "Ingredients Only"], horizontal=True)
  594. comp_reqs = col_comp.multiselect("Require Nutrients (Sorts by highest)", ["Iron", "Vitamin C", "Calcium", "Proteins", "Fiber"])
  595. if add_search:
  596. bool_search = " ".join([f"+{w}" for w in add_search.split()])
  597. start_time = time.time()
  598. def execute_search(match_col_override=None):
  599. m_col = "product_name"
  600. if match_col_override: m_col = match_col_override
  601. elif "Both" in search_scope: m_col = "product_name, ingredients_text"
  602. elif "Ingredients" in search_scope: m_col = "ingredients_text"
  603. 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 ""
  604. join_vit = "LEFT JOIN food_db.products_vitamins v ON c.code = v.code" if "Vitamin C" in comp_reqs else ""
  605. r_clauses, o_clauses = [], []
  606. if "Iron" in comp_reqs: r_clauses.append("min.iron_100g > 0"); o_clauses.append("min.iron_100g DESC")
  607. if "Vitamin C" in comp_reqs: r_clauses.append("v.`vitamin-c_100g` > 0"); o_clauses.append("v.`vitamin-c_100g` DESC")
  608. if "Calcium" in comp_reqs: r_clauses.append("min.calcium_100g > 0"); o_clauses.append("min.calcium_100g DESC")
  609. if "Proteins" in comp_reqs: r_clauses.append("m.proteins_100g > 0"); o_clauses.append("m.proteins_100g DESC")
  610. if "Fiber" in comp_reqs: r_clauses.append("m.fiber_100g > 0"); o_clauses.append("m.fiber_100g DESC")
  611. wh_comp = " AND " + " AND ".join(r_clauses) if r_clauses else ""
  612. order_by = "ORDER BY " + ", ".join(o_clauses) if o_clauses else ""
  613. sql = f"""
  614. SELECT c.code, c.product_name
  615. FROM (
  616. SELECT code, product_name
  617. FROM food_db.products_core
  618. WHERE MATCH({m_col}) AGAINST(%s IN BOOLEAN MODE)
  619. AND product_name IS NOT NULL AND product_name != '' AND product_name != 'None'
  620. LIMIT 100
  621. ) c
  622. JOIN food_db.products_macros m ON c.code = m.code
  623. {join_min}
  624. {join_vit}
  625. WHERE m.proteins_100g IS NOT NULL AND m.fat_100g IS NOT NULL AND m.carbohydrates_100g IS NOT NULL
  626. {wh_comp}
  627. {order_by}
  628. LIMIT 15
  629. """
  630. cursor.execute(sql, (bool_search,))
  631. return cursor.fetchall()
  632. search_res = execute_search()
  633. if not search_res and search_scope == "Auto (Cascaded)":
  634. st.warning("No product found in names, so I am looking into the ingredients...")
  635. search_res = execute_search("ingredients_text")
  636. elapsed = time.time() - start_time
  637. st.caption(f"⏱️ Plate Search Executed in {elapsed:.3f} seconds")
  638. if search_res:
  639. options = {f"{r['product_name']} ({r['code']})": r for r in search_res}
  640. selected_str = st.selectbox("Select Product", list(options.keys()))
  641. selected_product = options[selected_str]
  642. add_amount_str = st.text_input("Portion Quantity (e.g., '100g', '2 tbsp', '1.5 cups', '1 pinch')", value="100g")
  643. if st.button("Add Item to Plate"):
  644. # Use UnitConverter to parse
  645. grams = UnitConverter.parse_and_convert(add_amount_str, product_name=selected_product['product_name'])
  646. if grams is not None:
  647. cursor.execute("INSERT INTO plate_items (plate_id, product_code, quantity_grams) VALUES (%s, %s, %s)",
  648. (active_p_id, selected_product['code'], grams))
  649. conn.commit()
  650. st.success(f"Added {grams}g of {selected_product['product_name']}!")
  651. st.rerun()
  652. else:
  653. st.error("Could not parse unit. Please use format like '100g' or '1 cup'.")
  654. else:
  655. st.warning("No products found.")
  656. with tab_planner:
  657. st.subheader("🤖 AI Meal Planner")
  658. st.info("""
  659. ℹ️ **How to use this feature (Examples)**
  660. **Your active conditions are automatically applied to the generated menu.**
  661. *Example Prompts:*
  662. 1. "Generate a full day meal plan for me. I am pregnant, diabetic, and have kidney disease."
  663. 2. "Plan a pregnancy-safe dinner that won't spike my blood sugar."
  664. 3. "I need a high-iron lunch that is safe for my kidneys."
  665. 4. "Plan a breakfast without dairy that is kidney-friendly."
  666. 5. "Give me a 3-day meal prep plan ensuring no raw fish, controlled protein portions, and steady complex carbs."
  667. """)
  668. p_col1, p_col2, p_col3 = st.columns(3)
  669. target_cal = p_col1.number_input("Target Daily Calories (kcal)", 1000, 5000, 2000, 50)
  670. diet_pref = p_col2.selectbox("Dietary Preference", ["Omnivore", "Vegetarian", "Vegan", "Keto", "Paleo"])
  671. meal_count = p_col3.slider("Number of Meals", 2, 6, 3)
  672. extra_notes = st.text_input("Any additional allergies or goals?")
  673. if st.button("Generate Professional Menu"):
  674. with st.spinner("Executing Lightning-Fast Context RAG..."):
  675. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  676. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  677. # Pre-fetch database context directly without using AI tools!
  678. # Enforce the strict clinical constraints directly via SQL
  679. db_context = search_nutrition_db(diet_pref, user_eav)
  680. sys_prompt = f"""You are a professional clinical Dietitian planner. Target: {target_cal}kcal over {meal_count} meals.
  681. Dietary constraint: {diet_pref}. Additional notes: {extra_notes}.
  682. Health profile: {profile_text}.
  683. CRITICAL INSTRUCTIONS:
  684. - You MUST formulate the menu using ONLY the following real database items retrieved for you: {db_context}
  685. - Output the menu beautifully formatted as a Markdown Table.
  686. - Columns MUST be: | Meal Time | Exact Food | Portion Size | Calories | Protein |
  687. - Do NOT output JSON. Do NOT use tool calls.
  688. - Provide a direct answer. Skip all thinking, reasoning, and pleasantries.
  689. """
  690. temp_messages = [{'role': 'system', 'content': sys_prompt}, {'role': 'user', 'content': 'Generate my meal plan as a markdown table.'}]
  691. # Stream the response instantly!
  692. try:
  693. response_stream = ollama.chat(model='llama3.2:1b', messages=temp_messages, stream=True)
  694. st.markdown("### 📋 Your Professional Meal Plan")
  695. st.write_stream(chunk['message']['content'] for chunk in response_stream)
  696. except Exception as e:
  697. error_msg = str(e).lower()
  698. if "404" in error_msg or "not found" in error_msg:
  699. st.warning("⚠️ The AI engine is currently downloading its core models in the background. Please wait a minute and try again!")
  700. else:
  701. st.error(f"AI Generation Failed: {e}")
  702. if conn_reader: conn_reader.close()