app.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. # $Id$
  2. # $Author$
  3. # $log$
  4. import streamlit as st
  5. import pymysql
  6. import myloginpath
  7. import ollama
  8. import bcrypt
  9. import requests
  10. import string
  11. import random
  12. import smtplib
  13. from email.message import EmailMessage
  14. import pandas as pd
  15. from unit_converter import UnitConverter
  16. from snmp_notifier import notifier
  17. import time
  18. def local_web_search(query: str) -> str:
  19. try:
  20. req = requests.get(f'http://127.0.0.1:8080/search', params={'q': query, 'format': 'json'})
  21. if req.status_code == 200:
  22. data = req.json()
  23. results = data.get('results', [])
  24. if not results: return f"No results found on the web for '{query}'."
  25. snippets = [f"Source: {r.get('url')}\nContent: {r.get('content')}" for r in results[:3]]
  26. return "\n\n".join(snippets)
  27. return "Search engine returned an error."
  28. except Exception as e: return f"Local search engine unreachable: {e}"
  29. search_tool_schema = {
  30. 'type': 'function',
  31. 'function': {
  32. 'name': 'local_web_search',
  33. 'description': 'Search the internet for info not in DB.',
  34. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']},
  35. },
  36. }
  37. def search_nutrition_db(query: str) -> str:
  38. conn = get_db_connection('app_reader')
  39. if not conn: return "Database connection failed."
  40. try:
  41. with conn.cursor() as cursor:
  42. # Query products view via natural language match on core table
  43. sql = """
  44. SELECT c.code, MAX(c.product_name) as product_name, MAX(m.proteins_100g) as proteins_100g, MAX(m.fat_100g) as fat_100g, MAX(m.carbohydrates_100g) as carbohydrates_100g, MAX(m.sugars_100g) as sugars_100g
  45. FROM food_db.products_core c
  46. LEFT JOIN food_db.products_macros m ON c.code = m.code
  47. WHERE MATCH(c.product_name, c.ingredients_text) AGAINST(%s IN BOOLEAN MODE)
  48. AND c.product_name IS NOT NULL AND c.product_name != '' AND c.product_name != 'None'
  49. GROUP BY c.code
  50. LIMIT 5
  51. """
  52. bool_query = " ".join([f"+{w}" for w in query.split()])
  53. cursor.execute(sql, (bool_query,))
  54. results = cursor.fetchall()
  55. if not results: return f"No database records found for '{query}'."
  56. snippets = []
  57. for r in results:
  58. snippets.append(f"- {r['product_name']}: Protein {r['proteins_100g']}g, Fat {r['fat_100g']}g, Carbs {r['carbohydrates_100g']}g, Sugars {r['sugars_100g']}g (per 100g)")
  59. return "\n".join(snippets)
  60. except Exception as e:
  61. return f"Database query failed: {e}"
  62. finally:
  63. conn.close()
  64. db_search_tool_schema = {
  65. 'type': 'function',
  66. 'function': {
  67. 'name': 'search_nutrition_db',
  68. 'description': 'Search the local medical nutrition database for product macros and ingredients. ALWAYS prioritize this over web search.',
  69. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The product or food name to search for (e.g. apple, chicken, bread)'}}, 'required': ['query']},
  70. },
  71. }
  72. def get_db_connection(login_path):
  73. try:
  74. import os
  75. db_host = os.environ.get('DB_HOST')
  76. # Check if environment variables exist for this login path
  77. db_user = os.environ.get(f'{login_path.upper()}_USER') or os.environ.get('DB_USER')
  78. db_pass = os.environ.get(f'{login_path.upper()}_PASS') or os.environ.get('DB_PASS')
  79. if db_host and db_user and db_pass:
  80. return pymysql.connect(
  81. host=db_host,
  82. user=db_user,
  83. password=db_pass,
  84. database='food_db',
  85. cursorclass=pymysql.cursors.DictCursor
  86. )
  87. conf = myloginpath.parse(login_path)
  88. if not conf or not conf.get('user'):
  89. 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.")
  90. return None
  91. return pymysql.connect(
  92. host=conf.get('host', '127.0.0.1'),
  93. user=conf.get('user'),
  94. password=conf.get('password'),
  95. database='food_db',
  96. cursorclass=pymysql.cursors.DictCursor
  97. )
  98. except Exception as e:
  99. st.error(f"Connection Failed: {e}")
  100. return None
  101. def verify_login(username, password):
  102. conn = get_db_connection('app_auth')
  103. if not conn: return False
  104. with conn.cursor() as cursor:
  105. cursor.execute("SELECT password_hash FROM users WHERE username = %s LIMIT 1", (username,))
  106. result = cursor.fetchone()
  107. conn.close()
  108. if result: return bcrypt.checkpw(password.encode('utf-8'), result['password_hash'].encode('utf-8'))
  109. return False
  110. def get_user_id(username):
  111. conn = get_db_connection('app_auth')
  112. if not conn: return None
  113. with conn.cursor() as cursor:
  114. cursor.execute("SELECT id FROM users WHERE username = %s LIMIT 1", (username,))
  115. result = cursor.fetchone()
  116. conn.close()
  117. return result['id'] if result else None
  118. def get_eav_profile(username):
  119. uid = get_user_id(username)
  120. if not uid: return []
  121. conn = get_db_connection('app_auth')
  122. with conn.cursor() as cursor:
  123. 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,))
  124. res = cursor.fetchall()
  125. conn.close()
  126. return res
  127. def get_user_limit(username):
  128. conn = get_db_connection('app_auth')
  129. if not conn: return "50"
  130. with conn.cursor() as cursor:
  131. cursor.execute("SELECT search_limit FROM users WHERE username = %s LIMIT 1", (username,))
  132. result = cursor.fetchone()
  133. conn.close()
  134. return result['search_limit'] if (result and result['search_limit']) else "50"
  135. def register_user(username, password, email):
  136. conn = get_db_connection('app_auth')
  137. if not conn: return False
  138. hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  139. try:
  140. with conn.cursor() as cursor:
  141. cursor.execute("INSERT INTO users (username, password_hash, email) VALUES (%s, %s, %s)", (username, hashed, email))
  142. conn.commit()
  143. conn.close()
  144. send_email(email, "Welcome to Local Food AI", f"Hello {username}, your account was securely created!", to_name=username.title())
  145. return True
  146. except pymysql.err.IntegrityError:
  147. return False
  148. def send_email(to_email, subject, body, to_name="User"):
  149. msg = EmailMessage()
  150. msg.set_content(body)
  151. msg['Subject'] = subject
  152. msg['From'] = '"Clinical Food AI System" <security@localfoodai.com>'
  153. msg['To'] = f'"{to_name}" <{to_email}>'
  154. for attempt in range(5):
  155. try:
  156. s = smtplib.SMTP('localhost', 25)
  157. s.send_message(msg)
  158. s.quit()
  159. return True
  160. except Exception as e:
  161. if attempt == 4:
  162. return f"SMTP Delivery Failed: {str(e)}"
  163. time.sleep(2)
  164. return "Unknown Error Occurred"
  165. def reset_password(username, email):
  166. conn = get_db_connection('app_auth')
  167. if not conn: return False
  168. with conn.cursor() as cursor:
  169. cursor.execute("SELECT id, email FROM users WHERE username = %s", (username,))
  170. user = cursor.fetchone()
  171. if user and user['email'] == email:
  172. new_pass = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
  173. hashed = bcrypt.hashpw(new_pass.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  174. cursor.execute("UPDATE users SET password_hash = %s WHERE id = %s", (hashed, user['id']))
  175. conn.commit()
  176. conn.close()
  177. status = send_email(email, "Password Reset", f"Your new temporary password is: {new_pass}", to_name=username.title())
  178. if status is True:
  179. return True
  180. return status
  181. return False
  182. # UI Theming
  183. def render_version():
  184. st.markdown("---")
  185. st.caption("🚀 Version: v1.3.0")
  186. st.caption(f"📅 Git ID: $Id$")
  187. st.set_page_config(page_title="Food AI Explorer", page_icon="🍔", layout="wide")
  188. st.markdown("""
  189. <style>
  190. @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap');
  191. html, body, [class*="css"] { font-family: 'Inter', sans-serif; background-color: #0b192c; color: #e2e8f0; }
  192. h1, h2, h3 { color: #38bdf8 !important; font-weight: 600; letter-spacing: 0.5px; }
  193. div[data-testid="stSidebar"] { background: rgba(11, 25, 44, 0.95) !important; backdrop-filter: blur(10px); border-right: 1px solid #1e293b; }
  194. .stButton>button { background: linear-gradient(135deg, #0ea5e9, #0284c7); color: white; border: none; border-radius: 6px; }
  195. .stButton>button:hover { transform: scale(1.02); }
  196. .stTextInput>div>div>input, .stNumberInput>div>div>input, .stSelectbox>div>div>div { background-color: #0f172a; color: #f8fafc; border: 1px solid #38bdf8; }
  197. </style>
  198. """, unsafe_allow_html=True)
  199. if "authenticated_user" not in st.session_state:
  200. st.session_state["authenticated_user"] = None
  201. with st.sidebar:
  202. st.title("User Portal 🔐")
  203. render_version()
  204. with st.expander("🛠️ Diagnostic: App Database View"):
  205. conn = get_db_connection('app_auth')
  206. if conn:
  207. with conn.cursor() as c:
  208. c.execute("DESCRIBE users;")
  209. st.json(c.fetchall())
  210. c.execute("SELECT DATABASE(), CURRENT_USER();")
  211. st.json(c.fetchall())
  212. conn.close()
  213. if st.session_state["authenticated_user"]:
  214. st.success(f"Logged in as: {st.session_state['authenticated_user']}")
  215. if st.button("Logout"):
  216. st.session_state["authenticated_user"] = None
  217. st.rerun()
  218. eav_data = get_eav_profile(st.session_state["authenticated_user"])
  219. uid = get_user_id(st.session_state["authenticated_user"])
  220. user_lim = get_user_limit(st.session_state["authenticated_user"])
  221. with st.expander("⚙️ Account Preferences"):
  222. opts = ["10", "20", "50", "100", "All"]
  223. idx = opts.index(user_lim) if user_lim in opts else 2
  224. new_lim = st.selectbox("Default Search Limit", opts, index=idx)
  225. if new_lim != user_lim:
  226. conn = get_db_connection('app_auth')
  227. with conn.cursor() as c:
  228. c.execute("UPDATE users SET search_limit = %s WHERE id = %s", (new_lim, uid))
  229. conn.commit()
  230. st.rerun()
  231. with st.expander("➕ Add Condition / Diet"):
  232. new_cat = st.selectbox("Category", ["Condition", "Illness", "Diet", "Dislike", "Allergy"])
  233. new_val = st.text_input("Value (e.g. 'vegan', 'diabetes', 'broccoli')").strip().lower()
  234. if st.button("Add to Profile") and new_val and uid:
  235. conn = get_db_connection('app_auth')
  236. with conn.cursor() as c:
  237. 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, new_val))
  238. conn.commit()
  239. st.rerun()
  240. if eav_data:
  241. st.markdown("#### Active Flags")
  242. for e in eav_data:
  243. col1, col2 = st.columns([4, 1])
  244. col1.info(f"**{e['name']}:** {e['value'].title()}")
  245. if col2.button("X", key=f"del_eav_{e['id']}"):
  246. conn = get_db_connection('app_auth')
  247. with conn.cursor() as c:
  248. c.execute("DELETE FROM user_health_profiles WHERE id = %s", (e['id'],))
  249. conn.commit()
  250. st.rerun()
  251. else:
  252. tab1, tab2, tab3 = st.tabs(["Login", "Register", "Reset"])
  253. with tab1:
  254. l_user = st.text_input("Username", key="l_user").strip()
  255. l_pass = st.text_input("Password", type="password", key="l_pass")
  256. if st.button("Login"):
  257. if verify_login(l_user, l_pass):
  258. notifier.send_alert(f"User Login Success: {l_user}")
  259. st.session_state["authenticated_user"] = l_user
  260. st.rerun()
  261. else:
  262. notifier.send_alert(f"User Login Failed: {l_user}")
  263. st.error("Invalid login.")
  264. with tab2:
  265. r_user = st.text_input("Username", key="r_user")
  266. r_email = st.text_input("Email Address", key="r_email")
  267. r_pass = st.text_input("Password", type="password", key="r_pass")
  268. if st.button("Register"):
  269. if len(r_pass) < 6: st.error("Password too short.")
  270. elif register_user(r_user, r_pass, r_email): st.success("Registered safely!")
  271. else: st.error("Username exists.")
  272. with tab3:
  273. f_user = st.text_input("Username", key="f_user")
  274. f_email = st.text_input("Registered Email", key="f_email")
  275. if st.button("Send Reset Link"):
  276. status = reset_password(f_user, f_email)
  277. if status is True:
  278. st.success("Password reset emailed.")
  279. else:
  280. st.error(f"Failed: {status}")
  281. if not st.session_state["authenticated_user"]:
  282. st.title("🍔 Food AI Medical Explorer")
  283. st.info("Please login to interrogate the Clinical Data.")
  284. st.stop()
  285. st.title("🍔 Food AI Clinical Explorer")
  286. conn_reader = get_db_connection('app_reader')
  287. tab_chat, tab_explore, tab_plate, tab_planner = st.tabs(["💬 AI Chat", "🔬 Clinical Search", "🍽️ My Plate Builder", "🤖 AI Meal Planner"])
  288. import re
  289. with tab_chat:
  290. c1, c2 = st.columns([4, 1])
  291. c1.subheader("Chat with the Context")
  292. if c2.button("🧹 Clear Chat"):
  293. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  294. st.rerun()
  295. st.info("""
  296. ℹ️ **How to use this feature (Examples)**
  297. **Your active conditions (e.g. Pregnant, Diabetic) are automatically sent to the AI in the background. You do not need to type them out.**
  298. *Examples:*
  299. 1. "I am pregnant, diabetic, and have kidney problems. Can I eat sushi?"
  300. 2. "What is a safe snack to stabilize my blood sugar without hurting my kidneys?"
  301. 3. "Can I drink milk? I need calcium for the baby."
  302. 4. "Is it safe to eat a large steak for iron?"
  303. 5. "What foods are strictly forbidden for me?"
  304. """)
  305. if "messages" not in st.session_state:
  306. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  307. # Display chat history, filtering out TOOL_CALLS
  308. for msg in st.session_state.messages:
  309. if msg["role"] == "tool": continue
  310. display_text = re.sub(r'\[TOOL_CALLS\]\s*\[.*?\]', '', msg["content"]).strip()
  311. if display_text:
  312. st.chat_message(msg["role"]).write(display_text)
  313. if prompt := st.chat_input("Ask a clinical question about your food..."):
  314. st.session_state.messages.append({"role": "user", "content": prompt})
  315. st.chat_message("user").write(prompt)
  316. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  317. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  318. sys_prompt = f"""You are a helpful medical data analyst AI.
  319. The user has the following health profile / conditions: {profile_text}.
  320. You MUST act as a specialized clinical dietitian. Autonomously deduce what foods are recommended, forbidden, or accepted for these specific conditions and apply these rules to all your answers.
  321. ALWAYS query the local database using the search_nutrition_db tool to answer questions about food, macros, and nutrients before answering or searching the web! If it's not in the DB, you can use local_web_search.
  322. DO NOT hallucinate that a well-known food like sushi has 0 macros just because the database is missing a row. Use your medical knowledge to supplement missing database data and warn the user of biological facts (e.g. Sushi contains raw fish and carbs from rice)."""
  323. with st.spinner("Analyzing..."):
  324. try:
  325. temp_messages = [{"role": "system", "content": sys_prompt}] + [m for m in st.session_state.messages if m["role"] != "tool"]
  326. response = ollama.chat(model='llama3.1', messages=temp_messages, tools=[search_tool_schema, db_search_tool_schema])
  327. if response.get('message', {}).get('tool_calls'):
  328. for tool in response['message']['tool_calls']:
  329. if tool['function']['name'] == 'local_web_search':
  330. query_arg = tool['function']['arguments'].get('query')
  331. st.info(f"🔍 Web Search triggered for: '{query_arg}'")
  332. search_data = local_web_search(query_arg)
  333. st.session_state.messages.append(response['message'])
  334. st.session_state.messages.append({'role': 'tool', 'content': search_data, 'name': 'local_web_search'})
  335. elif tool['function']['name'] == 'search_nutrition_db':
  336. query_arg = tool['function']['arguments'].get('query')
  337. st.info(f"🗄️ Database Search triggered for: '{query_arg}'")
  338. db_data = search_nutrition_db(query_arg)
  339. st.session_state.messages.append(response['message'])
  340. st.session_state.messages.append({'role': 'tool', 'content': db_data, 'name': 'search_nutrition_db'})
  341. temp_messages = [{"role": "system", "content": sys_prompt}] + st.session_state.messages
  342. response = ollama.chat(model='llama3', messages=temp_messages)
  343. ai_reply = response['message']['content']
  344. ai_reply = re.sub(r'\[TOOL_CALLS\]\s*\[.*?\]', '', ai_reply).strip()
  345. except Exception as e: ai_reply = f"Hold on! Engine execution fault: {e}"
  346. st.session_state.messages.append({"role": "assistant", "content": ai_reply})
  347. st.chat_message("assistant").write(ai_reply)
  348. def highlight_medical_warnings(row):
  349. try:
  350. val = str(row.get('Medical Warning', ''))
  351. if '⚠️' in val: return ['background-color: rgba(255, 0, 0, 0.4); color: white;'] * len(row)
  352. if '💚' in val: return ['background-color: rgba(0, 255, 0, 0.3); color: white;'] * len(row)
  353. except: pass
  354. return [''] * len(row)
  355. with tab_explore:
  356. st.subheader("Clinical Data Search")
  357. st.info("""
  358. ℹ️ **How to use this feature (Examples)**
  359. **Your active conditions are automatically flagged (⚠️ or 💚) in the search results.**
  360. *Example Searches:*
  361. 1. `Cereal` *(Checks for high sugar & hidden phosphorus)*
  362. 2. `Cheese` *(Checks for unpasteurized pregnancy risks & high sodium)*
  363. 3. `Fruit Juice` *(Checks for high sugar spikes)*
  364. 4. `Deli Meat` *(Checks for Listeria risk & extreme sodium)*
  365. 5. `White Rice` *(Safe for kidneys but flags high glycemic index)*
  366. """)
  367. sq = st.text_input("Search Product Name or Ingredient")
  368. cols = st.columns(5)
  369. min_pro = cols[0].number_input("Min Protein (g)", 0, 1000, 0)
  370. min_fat = cols[1].number_input("Min Fat (g)", 0, 1000, 0)
  371. min_carb = cols[2].number_input("Min Carbs (g)", 0, 1000, 0)
  372. max_sug = cols[3].number_input("Max Sugar (g)", 0, 1000, 1000)
  373. # Load dynamically fetched limit to prevent Pandas Styler crash
  374. pd.set_option("styler.render.max_elements", 5000000)
  375. opts = [10, 50, 100, 500, 1000]
  376. user_lim_str = get_user_limit(st.session_state["authenticated_user"])
  377. user_lim_val = 1000 if user_lim_str == "All" else int(user_lim_str)
  378. if user_lim_val not in opts: user_lim_val = 50
  379. idx = opts.index(user_lim_val)
  380. limit_rc = cols[4].selectbox("Limit Results", opts, index=idx)
  381. if st.button("Search Database") and sq and conn_reader:
  382. notifier.send_alert(f"Medical DB Search Executed: {sq}")
  383. with st.spinner("Processing massive clinical query..."):
  384. try:
  385. with conn_reader.cursor() as cursor:
  386. l_str = "" if limit_rc == "All" else f"LIMIT {limit_rc}"
  387. query = f"""
  388. SELECT c.code, c.product_name, MAX(c.generic_name) as generic_name, MAX(c.brands) as brands, MAX(c.ingredients_text) as ingredients_text,
  389. MAX(a.allergens) as allergens,
  390. MAX(m.`energy-kcal_100g`) as `energy-kcal_100g`, MAX(m.proteins_100g) as proteins_100g, MAX(m.fat_100g) as fat_100g, MAX(m.carbohydrates_100g) as carbohydrates_100g, MAX(m.sugars_100g) as sugars_100g, MAX(m.fiber_100g) as fiber_100g, MAX(m.sodium_100g) as sodium_100g, MAX(m.salt_100g) as salt_100g, MAX(m.cholesterol_100g) as cholesterol_100g,
  391. MAX(v.`vitamin-a_100g`) as `vitamin-a_100g`, MAX(v.`vitamin-b1_100g`) as `vitamin-b1_100g`, MAX(v.`vitamin-b2_100g`) as `vitamin-b2_100g`, MAX(v.`vitamin-pp_100g`) as `vitamin-pp_100g`, MAX(v.`vitamin-b6_100g`) as `vitamin-b6_100g`, MAX(v.`vitamin-b9_100g`) as `vitamin-b9_100g`, MAX(v.`vitamin-b12_100g`) as `vitamin-b12_100g`, MAX(v.`vitamin-c_100g`) as `vitamin-c_100g`, MAX(v.`vitamin-d_100g`) as `vitamin-d_100g`, MAX(v.`vitamin-e_100g`) as `vitamin-e_100g`, MAX(v.`vitamin-k_100g`) as `vitamin-k_100g`,
  392. MAX(min.calcium_100g) as calcium_100g, MAX(min.iron_100g) as iron_100g, MAX(min.magnesium_100g) as magnesium_100g, MAX(min.potassium_100g) as potassium_100g, MAX(min.zinc_100g) as zinc_100g
  393. FROM (
  394. SELECT code, MAX(product_name) as product_name, MAX(generic_name) as generic_name, MAX(brands) as brands, MAX(ingredients_text) as ingredients_text
  395. FROM food_db.products_core
  396. WHERE MATCH(product_name, ingredients_text) AGAINST(%s IN BOOLEAN MODE)
  397. AND product_name IS NOT NULL AND product_name != '' AND product_name != 'None'
  398. GROUP BY code
  399. {l_str}
  400. ) c
  401. LEFT JOIN food_db.products_allergens a ON c.code = a.code
  402. LEFT JOIN food_db.products_macros m ON c.code = m.code
  403. LEFT JOIN food_db.products_vitamins v ON c.code = v.code
  404. LEFT JOIN food_db.products_minerals min ON c.code = min.code
  405. WHERE (m.proteins_100g >= %s OR m.proteins_100g IS NULL)
  406. AND (m.fat_100g >= %s OR m.fat_100g IS NULL)
  407. AND (m.carbohydrates_100g >= %s OR m.carbohydrates_100g IS NULL)
  408. AND (m.sugars_100g <= %s OR m.sugars_100g IS NULL)
  409. GROUP BY c.code, c.product_name
  410. """
  411. sq_bool = " ".join([f"+{w}" for w in sq.split()])
  412. start_time = time.time()
  413. cursor.execute(query, (sq_bool, min_pro, min_fat, min_carb, max_sug))
  414. results = cursor.fetchall()
  415. elapsed = time.time() - start_time
  416. st.caption(f"⏱️ DB Query Executed in {elapsed:.3f} seconds")
  417. if results:
  418. # Fetch EAV Medical Profile
  419. eav_profile = get_eav_profile(st.session_state["authenticated_user"])
  420. df = pd.DataFrame(results)
  421. st.markdown("### 🛠️ Dynamic Column Display")
  422. default_columns = [
  423. 'code', 'product_name', 'generic_name', 'brands', 'allergens', 'ingredients_text',
  424. 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'sodium_100g', 'energy-kcal_100g',
  425. 'vitamin-c_100g', 'iron_100g', 'calcium_100g'
  426. ]
  427. all_fetched_cols = list(df.columns)
  428. valid_defaults = [c for c in default_columns if c in all_fetched_cols]
  429. if "selected_columns" not in st.session_state or st.button("Reset Default Columns"):
  430. st.session_state["selected_columns"] = valid_defaults
  431. st.rerun()
  432. chosen_cols = st.multiselect("Customize Dataset View", all_fetched_cols, default=st.session_state["selected_columns"], key="multi_cols")
  433. st.session_state["selected_columns"] = chosen_cols
  434. # Filter dataframe gracefully, but we retain a copy for background analytics
  435. df_display = df[chosen_cols].copy()
  436. warnings_col = []
  437. for idx, row in df.iterrows():
  438. warns = []
  439. ing_text = str(row['ingredients_text']).lower()
  440. all_text = str(row['allergens']).lower()
  441. for param in eav_profile:
  442. cat = param['name'].lower()
  443. val = param['value']
  444. # Disease Analytics
  445. if cat == 'illness':
  446. if val == 'diabetes' and pd.notnull(row.get('sugars_100g')) and float(row['sugars_100g']) > 10.0:
  447. warns.append("⚠️ High Sugar (Diabetes)")
  448. if (val == 'hypertension' or val == 'high bp') and pd.notnull(row.get('sodium_100g')) and float(row['sodium_100g']) > 1.5:
  449. warns.append("⚠️ High Salt (Hypertension)")
  450. if val == 'scurvy' and pd.notnull(row.get('vitamin-c_100g')) and float(row['vitamin-c_100g']) > 0.005:
  451. warns.append("💚 High Vitamin C (Scurvy Recommended)")
  452. if val == 'anemia' and pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  453. warns.append("💚 High Iron (Anemia Recommended)")
  454. # Condition Analytics
  455. if cat == 'condition':
  456. if val == 'pregnant':
  457. if ('cru' in ing_text or 'raw' in ing_text or 'viande crue' in ing_text):
  458. warns.append("⚠️ Raw Foods (Pregnancy Toxoplasmosis)")
  459. if pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  460. warns.append("💚 Med-High Iron (Pregnancy Health)")
  461. if val == 'low fat' and pd.notnull(row.get('fat_100g')) and float(row['fat_100g']) > 20.0:
  462. warns.append("⚠️ High Fat")
  463. if val == 'osteoporosis' and pd.notnull(row.get('calcium_100g')) and float(row['calcium_100g']) > 0.1:
  464. warns.append("💚 High Calcium (Bone Health)")
  465. if eav_data:
  466. ing_text = str(row.get('ingredients_text', '')).lower()
  467. all_text = str(row.get('allergens', '')).lower()
  468. product_name_text = str(row.get('product_name', '')).lower()
  469. for e in eav_data:
  470. cat = str(e['name']).lower()
  471. val = str(e['value']).lower()
  472. # Clinical Trace Checks...
  473. if cat == 'condition' and (val == 'pregnant' or val == 'pregnancy' or val == 'breastfeeding'):
  474. # Forbidden / High Risk (Toxoplasmosis & Listeria)
  475. if any(x in ing_text or x in product_name_text for x in ['cru', 'raw', 'viande crue', 'sushi', 'sashimi', 'poisson cru']):
  476. warns.append("⚠️ Forbidden: Raw Meat/Fish (Toxoplasmosis/Parasite Risk)")
  477. if any(x in ing_text or x in product_name_text for x in ['lait cru', 'unpasteurized', 'non pasteurisé']):
  478. warns.append("⚠️ Forbidden: Unpasteurized Dairy (Listeria Risk)")
  479. if any(x in ing_text or x in product_name_text for x in ['alcool', 'wine', 'alcohol', 'beer']):
  480. warns.append("⚠️ Forbidden: Contains Alcohol")
  481. # Recommended (Iron & Calcium)
  482. if float(row.get('iron_100g', 0) or 0) > 0.003:
  483. warns.append("💚 Recommended: High Iron (Pregnancy Health)")
  484. if float(row.get('calcium_100g', 0) or 0) > 0.120:
  485. warns.append("💚 Recommended: High Calcium (Bone Health / Breastfeeding)")
  486. if cat == 'illness' and val == 'osteoporosis':
  487. if float(row.get('calcium_100g', 0) or 0) < 0.120:
  488. warns.append("⚠️ Low Calcium (Osteoporosis Risk)")
  489. else:
  490. warns.append("💚 Recommended (High Calcium)")
  491. if cat == 'illness' and val == 'scurvy':
  492. if float(row.get('vitamin-c_100g', 0) or 0) < 0.010:
  493. warns.append("⚠️ Low Vitamin C (Scurvy Risk)")
  494. else:
  495. warns.append("💚 Recommended (High Vitamin C)")
  496. if cat == 'diet' and val in ['vegan', 'vegetarian']:
  497. if any(x in ing_text for x in ['meat', 'beef', 'chicken', 'fish', 'gelatin', 'whey', 'pork', 'porc', 'poulet']):
  498. warns.append("⚠️ Contains Animal Products")
  499. if cat == 'diet' and val == 'halal':
  500. if any(x in ing_text for x in ['pork', 'pig', 'porc', 'wine', 'alcohol', 'beer', 'vin']):
  501. warns.append("⚠️ Probable Haram Ingredients (e.g. Pork/Wine)")
  502. if cat in ['dislike', 'allergy']:
  503. if val in ing_text or val in all_text or val in product_name_text:
  504. warns.append(f"⚠️ Contains: {val.upper()}")
  505. warnings_col.append(" | ".join(list(set(warns))) if warns else "✅ Safe for Profile")
  506. df_display.insert(0, 'Medical Warning', warnings_col)
  507. styled_df = df_display.style.apply(highlight_medical_warnings, axis=1)
  508. st.success(f"Analysed {len(results)} records utilizing dynamic Partitions!")
  509. st.dataframe(styled_df, use_container_width=True)
  510. if st.button("🤖 Ask AI to Evaluate This Table"):
  511. with st.spinner("AI is dynamically evaluating these records against your profile..."):
  512. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  513. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  514. eval_prompt = f"The user has this profile: {profile_text}. Evaluate these foods and state which are highly recommended or strictly forbidden: {df_display.to_dict('records')}"
  515. try:
  516. response = ollama.chat(model='llama3', messages=[{'role': 'user', 'content': eval_prompt}])
  517. st.info(response['message']['content'])
  518. except Exception as e:
  519. st.error(f"AI Evaluation Failed: {e}")
  520. else:
  521. st.warning("No products found matching those strict terms.")
  522. except Exception as e: st.error(f"SQL/Pandas Error: {e}")
  523. with tab_plate:
  524. st.subheader("🍽️ My Plate Builder")
  525. st.info("""
  526. ℹ️ **How to use this feature (Examples & Logic)**
  527. **Plate Builder Logic:**
  528. 1. Create a New Plate.
  529. 2. Search for exact food words (e.g. 'chicken', 'egg').
  530. 3. Add the food with a specific portion (e.g. '150g').
  531. 4. The system calculates the combined macros.
  532. 5. Use the 🗑️ buttons to delete incorrect items or entire plates.
  533. *Example Plates:*
  534. 1. `150g White Rice` + `50g Chicken Breast` + `100g Green Beans`
  535. 2. `200g Potatoes` + `100g Tomatoes` + `100g Beef`
  536. 3. `100g Spinach Salad` + `50g Feta Cheese`
  537. 4. `200g Lentils` + `100g Quinoa`
  538. 5. `100g Apple` + `30g Almonds`
  539. """)
  540. uid = get_user_id(st.session_state["authenticated_user"])
  541. conn = get_db_connection('app_auth')
  542. if conn and uid:
  543. with conn.cursor() as cursor:
  544. cursor.execute("SELECT id, plate_name FROM plates WHERE user_id = %s", (uid,))
  545. plates = cursor.fetchall()
  546. with st.expander("➕ Create a New Plate"):
  547. new_plate_name = st.text_input("Plate Name")
  548. if st.button("Create Plate"):
  549. cursor.execute("INSERT INTO plates (user_id, plate_name) VALUES (%s, %s)", (uid, new_plate_name))
  550. conn.commit()
  551. st.session_state["active_plate"] = new_plate_name
  552. st.rerun()
  553. if plates:
  554. colA, colB = st.columns([4, 1])
  555. plate_names = [p['plate_name'] for p in plates]
  556. 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
  557. selected_plate = colA.selectbox("Select Active Plate", plate_names, index=default_idx)
  558. st.session_state["active_plate"] = selected_plate
  559. active_p_id = next(p['id'] for p in plates if p['plate_name'] == selected_plate)
  560. if colB.button("🗑️ Delete Plate"):
  561. cursor.execute("DELETE FROM plates WHERE id = %s", (active_p_id,))
  562. conn.commit()
  563. if "active_plate" in st.session_state: del st.session_state["active_plate"]
  564. st.rerun()
  565. cursor.execute("""
  566. SELECT i.id, i.product_code, MAX(i.quantity_grams) as quantity_grams, MAX(p.product_name) as product_name, MAX(m.proteins_100g) as proteins_100g, MAX(m.fat_100g) as fat_100g, MAX(m.carbohydrates_100g) as carbohydrates_100g
  567. FROM plate_items i LEFT JOIN products_core p ON i.product_code = p.code LEFT JOIN products_macros m ON i.product_code = m.code WHERE i.plate_id = %s
  568. GROUP BY i.id, i.product_code
  569. """, (active_p_id,))
  570. items = cursor.fetchall()
  571. if items:
  572. for i in items:
  573. c1, c2 = st.columns([5, 1])
  574. c1.markdown(f"<li><b>{i['quantity_grams']}g</b> of {i['product_name']} (Pro: {i['proteins_100g'] or 0}g)</li>", unsafe_allow_html=True)
  575. if c2.button("🗑️", key=f"del_item_{i['id']}"):
  576. cursor.execute("DELETE FROM plate_items WHERE id = %s", (i['id'],))
  577. conn.commit()
  578. st.rerun()
  579. total_pro = sum((float(i['proteins_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  580. total_fat = sum((float(i['fat_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  581. total_carb = sum((float(i['carbohydrates_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  582. st.info(f"**Total Protein:** {total_pro:.1f}g | **Total Fat:** {total_fat:.1f}g | **Total Carbs:** {total_carb:.1f}g")
  583. st.markdown("---")
  584. st.markdown("#### ➕ Add Food to Plate")
  585. add_search = st.text_input("Search Exact Product Name (e.g. 'chicken', 'egg')")
  586. if add_search:
  587. bool_search = " ".join([f"+{w}" for w in add_search.split()])
  588. start_time = time.time()
  589. cursor.execute("""
  590. SELECT c.code, c.product_name
  591. FROM (
  592. SELECT code, MAX(product_name) as product_name
  593. FROM food_db.products_core
  594. WHERE MATCH(product_name, ingredients_text) AGAINST(%s IN BOOLEAN MODE)
  595. AND product_name IS NOT NULL AND product_name != '' AND product_name != 'None'
  596. GROUP BY code
  597. LIMIT 10
  598. ) c
  599. JOIN food_db.products_macros m ON c.code = m.code
  600. WHERE m.proteins_100g IS NOT NULL AND m.fat_100g IS NOT NULL AND m.carbohydrates_100g IS NOT NULL
  601. GROUP BY c.code, c.product_name
  602. """, (bool_search,))
  603. search_res = cursor.fetchall()
  604. elapsed = time.time() - start_time
  605. st.caption(f"⏱️ Plate Search Executed in {elapsed:.3f} seconds")
  606. if search_res:
  607. options = {f"{r['product_name']} ({r['code']})": r for r in search_res}
  608. selected_str = st.selectbox("Select Product", list(options.keys()))
  609. selected_product = options[selected_str]
  610. add_amount_str = st.text_input("Portion Quantity (e.g., '100g', '2 tbsp', '1.5 cups', '1 pinch')", value="100g")
  611. if st.button("Add Item to Plate"):
  612. # Use UnitConverter to parse
  613. grams = UnitConverter.parse_and_convert(add_amount_str, product_name=selected_product['product_name'])
  614. if grams is not None:
  615. cursor.execute("INSERT INTO plate_items (plate_id, product_code, quantity_grams) VALUES (%s, %s, %s)",
  616. (active_p_id, selected_product['code'], grams))
  617. conn.commit()
  618. st.success(f"Added {grams}g of {selected_product['product_name']}!")
  619. st.rerun()
  620. else:
  621. st.error("Could not parse unit. Please use format like '100g' or '1 cup'.")
  622. else:
  623. st.warning("No products found.")
  624. with tab_planner:
  625. st.subheader("🤖 AI Meal Planner")
  626. st.info("""
  627. ℹ️ **How to use this feature (Examples)**
  628. **Your active conditions are automatically applied to the generated menu.**
  629. *Example Prompts:*
  630. 1. "Generate a full day meal plan for me. I am pregnant, diabetic, and have kidney disease."
  631. 2. "Plan a pregnancy-safe dinner that won't spike my blood sugar."
  632. 3. "I need a high-iron lunch that is safe for my kidneys."
  633. 4. "Plan a breakfast without dairy that is kidney-friendly."
  634. 5. "Give me a 3-day meal prep plan ensuring no raw fish, controlled protein portions, and steady complex carbs."
  635. """)
  636. p_col1, p_col2, p_col3 = st.columns(3)
  637. target_cal = p_col1.number_input("Target Daily Calories (kcal)", 1000, 5000, 2000, 50)
  638. diet_pref = p_col2.selectbox("Dietary Preference", ["Omnivore", "Vegetarian", "Vegan", "Keto", "Paleo"])
  639. meal_count = p_col3.slider("Number of Meals", 2, 6, 3)
  640. extra_notes = st.text_input("Any additional allergies or goals?")
  641. if st.button("Generate Professional Menu"):
  642. with st.spinner("AI is formulating and interrogating the local database..."):
  643. user_eav = get_eav_profile(st.session_state["authenticated_user"])
  644. profile_text = ", ".join([f"{p['name']}: {p['value']}" for p in user_eav]) if user_eav else "None"
  645. sys_prompt = f"""You are a professional clinical Dietitian planner. Target: {target_cal}kcal over {meal_count} meals.
  646. Dietary constraint: {diet_pref}. Additional notes: {extra_notes}.
  647. The user has the following health profile / conditions: {profile_text}.
  648. You MUST autonomously deduce what foods are recommended, forbidden, or accepted for these specific conditions and ensure the menu perfectly respects their medical requirements!
  649. CRITICAL INSTRUCTIONS:
  650. - YOU MUST USE the `search_nutrition_db` tool to find real products and their exact macros before constructing the menu!
  651. - If you cannot find appropriate products in the local DB, you MUST use the `local_web_search` tool.
  652. - ALWAYS output exactly as a JSON array of objects. DO NOT OUTPUT MARKDOWN. DO NOT OUTPUT ANY TEXT EXCEPT JSON.
  653. - JSON Format required:
  654. [
  655. {{"meal": "Breakfast", "food": "100g Oatmeal with 50g berries", "calories": 300, "salt_mg": 10, "fat_g": 5, "iron_mg": 2}}
  656. ]
  657. - Ensure the total calories sum up closely to {target_cal}.
  658. """
  659. temp_messages = [{'role': 'system', 'content': sys_prompt}, {'role': 'user', 'content': 'Generate my meal plan. Find real foods from the DB.'}]
  660. response = ollama.chat(model='llama3.1', messages=temp_messages, tools=[search_tool_schema, db_search_tool_schema])
  661. # Simple loop to handle multiple tool calls (up to 3 times to prevent infinite loops)
  662. for _ in range(3):
  663. if response.get('message', {}).get('tool_calls'):
  664. temp_messages.append(response['message'])
  665. for tool in response['message']['tool_calls']:
  666. if tool['function']['name'] == 'local_web_search':
  667. query_arg = tool['function']['arguments'].get('query')
  668. st.info(f"🔍 Planner Web Search triggered for: '{query_arg}'")
  669. search_data = local_web_search(query_arg)
  670. temp_messages.append({'role': 'tool', 'content': search_data, 'name': 'local_web_search'})
  671. elif tool['function']['name'] == 'search_nutrition_db':
  672. query_arg = tool['function']['arguments'].get('query')
  673. st.info(f"🗄️ Planner DB Search triggered for: '{query_arg}'")
  674. db_data = search_nutrition_db(query_arg)
  675. temp_messages.append({'role': 'tool', 'content': db_data, 'name': 'search_nutrition_db'})
  676. response = ollama.chat(model='llama3.1', messages=temp_messages, tools=[search_tool_schema, db_search_tool_schema])
  677. else:
  678. break
  679. import json
  680. raw_text = response['message']['content']
  681. raw_text = re.sub(r'\[TOOL_CALLS\]\s*\[.*?\]', '', raw_text).strip()
  682. try:
  683. start_idx = raw_text.find('[')
  684. end_idx = raw_text.rfind(']') + 1
  685. if start_idx != -1 and end_idx != -1:
  686. json_data = json.loads(raw_text[start_idx:end_idx])
  687. df_plan = pd.DataFrame(json_data)
  688. total_cals = df_plan['calories'].sum() if 'calories' in df_plan else 0
  689. total_salt = df_plan['salt_mg'].sum() if 'salt_mg' in df_plan else 0
  690. total_fat = df_plan['fat_g'].sum() if 'fat_g' in df_plan else 0
  691. total_iron = df_plan['iron_mg'].sum() if 'iron_mg' in df_plan else 0
  692. total_row = pd.DataFrame([{"meal": "TOTAL", "food": "---", "calories": total_cals, "salt_mg": total_salt, "fat_g": total_fat, "iron_mg": total_iron}])
  693. df_plan = pd.concat([df_plan, total_row], ignore_index=True)
  694. st.dataframe(df_plan, use_container_width=True)
  695. if abs(total_cals - target_cal) > 200:
  696. st.warning(f"Note: Total calories ({total_cals}) differ from your target ({target_cal}).")
  697. else:
  698. st.error("AI failed to output valid JSON. Raw output:")
  699. st.text(raw_text)
  700. except Exception as e:
  701. st.error(f"Failed to parse AI output: {e}")
  702. st.text(raw_text)
  703. if conn_reader: conn_reader.close()