app.py 79 KB

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