1
0

app.py 54 KB

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