app.py 76 KB

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