app.py 85 KB

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