1
0

app.py 51 KB

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