1
0

app.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import streamlit as st
  2. import pymysql
  3. import myloginpath
  4. import ollama
  5. import bcrypt
  6. import requests
  7. import string
  8. import random
  9. import smtplib
  10. from email.message import EmailMessage
  11. import pandas as pd
  12. def local_web_search(query: str) -> str:
  13. try:
  14. req = requests.get(f'http://127.0.0.1:8080/search', params={'q': query, 'format': 'json'})
  15. if req.status_code == 200:
  16. data = req.json()
  17. results = data.get('results', [])
  18. if not results: return f"No results found on the web for '{query}'."
  19. snippets = [f"Source: {r.get('url')}\nContent: {r.get('content')}" for r in results[:3]]
  20. return "\n\n".join(snippets)
  21. return "Search engine returned an error."
  22. except Exception as e: return f"Local search engine unreachable: {e}"
  23. search_tool_schema = {
  24. 'type': 'function',
  25. 'function': {
  26. 'name': 'local_web_search',
  27. 'description': 'Search the internet for info not in DB.',
  28. 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']},
  29. },
  30. }
  31. def get_db_connection(login_path):
  32. try:
  33. conf = myloginpath.parse(login_path)
  34. return pymysql.connect(
  35. host=conf.get('host', '127.0.0.1'),
  36. user=conf.get('user'),
  37. password=conf.get('password'),
  38. database='food_db',
  39. cursorclass=pymysql.cursors.DictCursor
  40. )
  41. except Exception as e:
  42. st.error(f"Connection Failed: {e}")
  43. return None
  44. def verify_login(username, password):
  45. conn = get_db_connection('app_auth')
  46. if not conn: return False
  47. with conn.cursor() as cursor:
  48. cursor.execute("SELECT password_hash FROM users WHERE username = %s LIMIT 1", (username,))
  49. result = cursor.fetchone()
  50. conn.close()
  51. if result: return bcrypt.checkpw(password.encode('utf-8'), result['password_hash'].encode('utf-8'))
  52. return False
  53. def get_user_id(username):
  54. conn = get_db_connection('app_auth')
  55. if not conn: return None
  56. with conn.cursor() as cursor:
  57. cursor.execute("SELECT id FROM users WHERE username = %s LIMIT 1", (username,))
  58. result = cursor.fetchone()
  59. conn.close()
  60. return result['id'] if result else None
  61. def get_eav_profile(username):
  62. uid = get_user_id(username)
  63. if not uid: return []
  64. conn = get_db_connection('app_auth')
  65. with conn.cursor() as cursor:
  66. 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,))
  67. res = cursor.fetchall()
  68. conn.close()
  69. return res
  70. def get_user_limit(username):
  71. conn = get_db_connection('app_auth')
  72. if not conn: return "50"
  73. with conn.cursor() as cursor:
  74. cursor.execute("SELECT search_limit FROM users WHERE username = %s LIMIT 1", (username,))
  75. result = cursor.fetchone()
  76. conn.close()
  77. return result['search_limit'] if (result and result['search_limit']) else "50"
  78. def register_user(username, password, email):
  79. conn = get_db_connection('app_auth')
  80. if not conn: return False
  81. hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  82. try:
  83. with conn.cursor() as cursor:
  84. cursor.execute("INSERT INTO users (username, password_hash, email) VALUES (%s, %s, %s)", (username, hashed, email))
  85. conn.commit()
  86. conn.close()
  87. send_email(email, "Welcome to Local Food AI", f"Hello {username}, your account was securely created!", to_name=username.title())
  88. return True
  89. except pymysql.err.IntegrityError:
  90. return False
  91. def send_email(to_email, subject, body, to_name="User"):
  92. msg = EmailMessage()
  93. msg.set_content(body)
  94. msg['Subject'] = subject
  95. msg['From'] = '"Clinical Food AI System" <security@localfoodai.com>'
  96. msg['To'] = f'"{to_name}" <{to_email}>'
  97. import time
  98. for attempt in range(5):
  99. try:
  100. s = smtplib.SMTP('localhost', 25)
  101. s.send_message(msg)
  102. s.quit()
  103. return True
  104. except Exception as e:
  105. if attempt == 4:
  106. return f"SMTP Delivery Failed: {str(e)}"
  107. time.sleep(2)
  108. return "Unknown Error Occurred"
  109. def reset_password(username, email):
  110. conn = get_db_connection('app_auth')
  111. if not conn: return False
  112. with conn.cursor() as cursor:
  113. cursor.execute("SELECT id, email FROM users WHERE username = %s", (username,))
  114. user = cursor.fetchone()
  115. if user and user['email'] == email:
  116. new_pass = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
  117. hashed = bcrypt.hashpw(new_pass.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  118. cursor.execute("UPDATE users SET password_hash = %s WHERE id = %s", (hashed, user['id']))
  119. conn.commit()
  120. conn.close()
  121. status = send_email(email, "Password Reset", f"Your new temporary password is: {new_pass}", to_name=username.title())
  122. if status is True:
  123. return True
  124. return status
  125. return False
  126. # UI Theming
  127. st.set_page_config(page_title="Food AI Explorer", page_icon="🍔", layout="wide")
  128. st.markdown("""
  129. <style>
  130. @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap');
  131. html, body, [class*="css"] { font-family: 'Inter', sans-serif; background-color: #0b192c; color: #e2e8f0; }
  132. h1, h2, h3 { color: #38bdf8 !important; font-weight: 600; letter-spacing: 0.5px; }
  133. div[data-testid="stSidebar"] { background: rgba(11, 25, 44, 0.95) !important; backdrop-filter: blur(10px); border-right: 1px solid #1e293b; }
  134. .stButton>button { background: linear-gradient(135deg, #0ea5e9, #0284c7); color: white; border: none; border-radius: 6px; }
  135. .stButton>button:hover { transform: scale(1.02); }
  136. .stTextInput>div>div>input, .stNumberInput>div>div>input, .stSelectbox>div>div>div { background-color: #0f172a; color: #f8fafc; border: 1px solid #38bdf8; }
  137. </style>
  138. """, unsafe_allow_html=True)
  139. if "authenticated_user" not in st.session_state:
  140. st.session_state["authenticated_user"] = None
  141. with st.sidebar:
  142. st.title("User Portal 🔐")
  143. if st.session_state["authenticated_user"]:
  144. st.success(f"Logged in as: {st.session_state['authenticated_user']}")
  145. if st.button("Logout"):
  146. st.session_state["authenticated_user"] = None
  147. st.rerun()
  148. st.markdown("---")
  149. st.subheader("🏥 Dynamic Health Profile")
  150. eav_data = get_eav_profile(st.session_state["authenticated_user"])
  151. uid = get_user_id(st.session_state["authenticated_user"])
  152. user_lim = get_user_limit(st.session_state["authenticated_user"])
  153. with st.expander("⚙️ Account Preferences"):
  154. opts = ["10", "20", "50", "100", "All"]
  155. idx = opts.index(user_lim) if user_lim in opts else 2
  156. new_lim = st.selectbox("Default Search Limit", opts, index=idx)
  157. if new_lim != user_lim:
  158. conn = get_db_connection('app_auth')
  159. with conn.cursor() as c:
  160. c.execute("UPDATE users SET search_limit = %s WHERE id = %s", (new_lim, uid))
  161. conn.commit()
  162. st.rerun()
  163. with st.expander("➕ Add Condition / Diet"):
  164. new_cat = st.selectbox("Category", ["Condition", "Illness", "Diet", "Dislike", "Allergy"])
  165. new_val = st.text_input("Value (e.g. 'vegan', 'diabetes', 'broccoli')").strip().lower()
  166. if st.button("Add to Profile") and new_val and uid:
  167. conn = get_db_connection('app_auth')
  168. with conn.cursor() as c:
  169. 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))
  170. conn.commit()
  171. st.rerun()
  172. if eav_data:
  173. st.markdown("#### Active Flags")
  174. for e in eav_data:
  175. col1, col2 = st.columns([4, 1])
  176. col1.info(f"**{e['name']}:** {e['value'].title()}")
  177. if col2.button("X", key=f"del_eav_{e['id']}"):
  178. conn = get_db_connection('app_auth')
  179. with conn.cursor() as c:
  180. c.execute("DELETE FROM user_health_profiles WHERE id = %s", (e['id'],))
  181. conn.commit()
  182. st.rerun()
  183. else:
  184. tab1, tab2, tab3 = st.tabs(["Login", "Register", "Reset"])
  185. with tab1:
  186. l_user = st.text_input("Username", key="l_user")
  187. l_pass = st.text_input("Password", type="password", key="l_pass")
  188. if st.button("Login"):
  189. if verify_login(l_user, l_pass):
  190. st.session_state["authenticated_user"] = l_user
  191. st.rerun()
  192. else: st.error("Invalid login.")
  193. with tab2:
  194. r_user = st.text_input("Username", key="r_user")
  195. r_email = st.text_input("Email Address", key="r_email")
  196. r_pass = st.text_input("Password", type="password", key="r_pass")
  197. if st.button("Register"):
  198. if len(r_pass) < 6: st.error("Password too short.")
  199. elif register_user(r_user, r_pass, r_email): st.success("Registered safely!")
  200. else: st.error("Username exists.")
  201. with tab3:
  202. f_user = st.text_input("Username", key="f_user")
  203. f_email = st.text_input("Registered Email", key="f_email")
  204. if st.button("Send Reset Link"):
  205. status = reset_password(f_user, f_email)
  206. if status is True:
  207. st.success("Password reset emailed.")
  208. else:
  209. st.error(f"Failed: {status}")
  210. if not st.session_state["authenticated_user"]:
  211. st.title("🍔 Food AI Medical Explorer")
  212. st.info("Please login to interrogate the Clinical Data.")
  213. st.stop()
  214. st.title("🍔 Food AI Clinical Explorer")
  215. conn_reader = get_db_connection('app_reader')
  216. tab_chat, tab_explore, tab_plate, tab_planner = st.tabs(["💬 AI Chat", "🔬 Clinical Search", "🍽️ My Plate Builder", "🤖 AI Meal Planner"])
  217. with tab_chat:
  218. st.subheader("Chat with the Context")
  219. if "messages" not in st.session_state:
  220. st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you analyze the food data today?"}]
  221. for msg in st.session_state.messages:
  222. st.chat_message(msg["role"]).write(msg["content"])
  223. if prompt := st.chat_input("Ask about the food items..."):
  224. st.session_state.messages.append({"role": "user", "content": prompt})
  225. st.chat_message("user").write(prompt)
  226. sys_prompt = "You are a helpful data analyst AI. Answer strictly using local data contexts. If you need external data, use the local_web_search tool!"
  227. with st.spinner("Analyzing..."):
  228. try:
  229. temp_messages = [{"role": "system", "content": sys_prompt}] + [m for m in st.session_state.messages if m["role"] != "tool"]
  230. response = ollama.chat(model='mistral', messages=temp_messages, tools=[search_tool_schema])
  231. if response.get('message', {}).get('tool_calls'):
  232. for tool in response['message']['tool_calls']:
  233. if tool['function']['name'] == 'local_web_search':
  234. query_arg = tool['function']['arguments'].get('query')
  235. st.info(f"🔍 Web Search triggered for: '{query_arg}'")
  236. search_data = local_web_search(query_arg)
  237. st.session_state.messages.append(response['message'])
  238. st.session_state.messages.append({'role': 'tool', 'content': search_data, 'name': 'local_web_search'})
  239. temp_messages = [{"role": "system", "content": sys_prompt}] + st.session_state.messages
  240. response = ollama.chat(model='mistral', messages=temp_messages)
  241. ai_reply = response['message']['content']
  242. except Exception as e: ai_reply = f"Hold on! Engine execution fault: {e}"
  243. st.session_state.messages.append({"role": "assistant", "content": ai_reply})
  244. st.chat_message("assistant").write(ai_reply)
  245. def highlight_medical_warnings(row):
  246. try:
  247. val = str(row.get('Medical Warning', ''))
  248. if '⚠️' in val: return ['background-color: rgba(255, 0, 0, 0.4); color: white;'] * len(row)
  249. if '💚' in val: return ['background-color: rgba(0, 255, 0, 0.3); color: white;'] * len(row)
  250. except: pass
  251. return [''] * len(row)
  252. with tab_explore:
  253. st.subheader("Clinical Data Search")
  254. sq = st.text_input("Search Product Name or Ingredient")
  255. cols = st.columns(5)
  256. min_pro = cols[0].number_input("Min Protein (g)", 0, 1000, 0)
  257. min_fat = cols[1].number_input("Min Fat (g)", 0, 1000, 0)
  258. min_carb = cols[2].number_input("Min Carbs (g)", 0, 1000, 0)
  259. max_sug = cols[3].number_input("Max Sugar (g)", 0, 1000, 1000)
  260. # Load dynamically fetched limit as index
  261. opts = [10, 20, 50, 100, "All"]
  262. user_lim_str = get_user_limit(st.session_state["authenticated_user"])
  263. user_lim_val = "All" if user_lim_str == "All" else int(user_lim_str)
  264. idx = opts.index(user_lim_val) if user_lim_val in opts else 2
  265. limit_rc = cols[4].selectbox("Limit Results", opts, index=idx)
  266. if st.button("Search Database") and sq and conn_reader:
  267. with st.spinner("Processing massive clinical query..."):
  268. try:
  269. with conn_reader.cursor() as cursor:
  270. l_str = "" if limit_rc == "All" else f"LIMIT {limit_rc}"
  271. query = f"""
  272. SELECT *
  273. FROM products
  274. WHERE MATCH(product_name, ingredients_text) AGAINST(%s IN NATURAL LANGUAGE MODE)
  275. AND (proteins_100g >= %s OR proteins_100g IS NULL)
  276. AND (fat_100g >= %s OR fat_100g IS NULL)
  277. AND (carbohydrates_100g >= %s OR carbohydrates_100g IS NULL)
  278. AND (sugars_100g <= %s OR sugars_100g IS NULL)
  279. {l_str}
  280. """
  281. cursor.execute(query, (sq, min_pro, min_fat, min_carb, max_sug))
  282. results = cursor.fetchall()
  283. if results:
  284. # Fetch EAV Medical Profile
  285. eav_profile = get_eav_profile(st.session_state["authenticated_user"])
  286. df = pd.DataFrame(results)
  287. st.markdown("### 🛠️ Dynamic Column Display")
  288. default_columns = [
  289. 'code', 'product_name', 'generic_name', 'brands', 'allergens', 'ingredients_text',
  290. 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'sodium_100g', 'energy-kcal_100g',
  291. 'vitamin-c_100g', 'iron_100g', 'calcium_100g'
  292. ]
  293. all_fetched_cols = list(df.columns)
  294. valid_defaults = [c for c in default_columns if c in all_fetched_cols]
  295. if "selected_columns" not in st.session_state or st.button("Reset Default Columns"):
  296. st.session_state["selected_columns"] = valid_defaults
  297. st.rerun()
  298. chosen_cols = st.multiselect("Customize Dataset View", all_fetched_cols, default=st.session_state["selected_columns"], key="multi_cols")
  299. st.session_state["selected_columns"] = chosen_cols
  300. # Filter dataframe gracefully, but we retain a copy for background analytics
  301. df_display = df[chosen_cols].copy()
  302. warnings_col = []
  303. for idx, row in df.iterrows():
  304. warns = []
  305. ing_text = str(row['ingredients_text']).lower()
  306. all_text = str(row['allergens']).lower()
  307. for param in eav_profile:
  308. cat = param['name'].lower()
  309. val = param['value']
  310. # Disease Analytics
  311. if cat == 'illness':
  312. if val == 'diabetes' and pd.notnull(row.get('sugars_100g')) and float(row['sugars_100g']) > 10.0:
  313. warns.append("⚠️ High Sugar (Diabetes)")
  314. if (val == 'hypertension' or val == 'high bp') and pd.notnull(row.get('sodium_100g')) and float(row['sodium_100g']) > 1.5:
  315. warns.append("⚠️ High Salt (Hypertension)")
  316. if val == 'scurvy' and pd.notnull(row.get('vitamin-c_100g')) and float(row['vitamin-c_100g']) > 0.005:
  317. warns.append("💚 High Vitamin C (Scurvy Recommended)")
  318. if val == 'anemia' and pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  319. warns.append("💚 High Iron (Anemia Recommended)")
  320. # Condition Analytics
  321. if cat == 'condition':
  322. if val == 'pregnant':
  323. if ('cru' in ing_text or 'raw' in ing_text or 'viande crue' in ing_text):
  324. warns.append("⚠️ Raw Foods (Pregnancy Toxoplasmosis)")
  325. if pd.notnull(row.get('iron_100g')) and float(row['iron_100g']) > 0.002:
  326. warns.append("💚 Med-High Iron (Pregnancy Health)")
  327. if val == 'low fat' and pd.notnull(row.get('fat_100g')) and float(row['fat_100g']) > 20.0:
  328. warns.append("⚠️ High Fat")
  329. if val == 'osteoporosis' and pd.notnull(row.get('calcium_100g')) and float(row['calcium_100g']) > 0.1:
  330. warns.append("💚 High Calcium (Bone Health)")
  331. if eav_data:
  332. ing_text = str(row.get('ingredients_text', '')).lower()
  333. all_text = str(row.get('allergens', '')).lower()
  334. for e in eav_data:
  335. cat = str(e['name']).lower()
  336. val = str(e['value']).lower()
  337. # Clinical Trace Checks...
  338. if cat == 'condition' and val == 'pregnant':
  339. if float(row.get('iron_100g', 0) or 0) < 0.003:
  340. warns.append("⚠️ Low Iron (Pregnancy Risk)")
  341. else:
  342. warns.append("💚 Recommended (High Iron)")
  343. if cat == 'illness' and val == 'osteoporosis':
  344. if float(row.get('calcium_100g', 0) or 0) < 0.120:
  345. warns.append("⚠️ Low Calcium (Osteoporosis Risk)")
  346. else:
  347. warns.append("💚 Recommended (High Calcium)")
  348. if cat == 'illness' and val == 'scurvy':
  349. if float(row.get('vitamin-c_100g', 0) or 0) < 0.010:
  350. warns.append("⚠️ Low Vitamin C (Scurvy Risk)")
  351. else:
  352. warns.append("💚 Recommended (High Vitamin C)")
  353. if cat == 'diet' and val in ['vegan', 'vegetarian']:
  354. if any(x in ing_text for x in ['meat', 'beef', 'chicken', 'fish', 'gelatin', 'whey']):
  355. warns.append("⚠️ Contains Animal Products")
  356. if cat == 'diet' and val == 'halal':
  357. if any(x in ing_text for x in ['pork', 'pig', 'wine', 'alcohol', 'beer']):
  358. warns.append("⚠️ Probable Haram Ingredients (e.g. Pork/Wine)")
  359. if cat in ['dislike', 'allergy']:
  360. if val in ing_text or val in all_text:
  361. warns.append(f"⚠️ Contains: {val.upper()}")
  362. warnings_col.append(" | ".join(list(set(warns))) if warns else "✅ Safe for Profile")
  363. df_display.insert(0, 'Medical Warning', warnings_col)
  364. styled_df = df_display.style.apply(highlight_medical_warnings, axis=1)
  365. st.success(f"Analysed {len(results)} records utilizing dynamic Partitions!")
  366. st.dataframe(styled_df, use_container_width=True)
  367. else:
  368. st.warning("No products found matching those strict terms.")
  369. except Exception as e: st.error(f"SQL/Pandas Error: {e}")
  370. with tab_plate:
  371. st.subheader("🍽️ My Plate Builder")
  372. uid = get_user_id(st.session_state["authenticated_user"])
  373. conn = get_db_connection('app_auth')
  374. if conn and uid:
  375. with conn.cursor() as cursor:
  376. cursor.execute("SELECT id, plate_name FROM plates WHERE user_id = %s", (uid,))
  377. plates = cursor.fetchall()
  378. with st.expander("➕ Create a New Plate"):
  379. new_plate_name = st.text_input("Plate Name")
  380. if st.button("Create Plate"):
  381. cursor.execute("INSERT INTO plates (user_id, plate_name) VALUES (%s, %s)", (uid, new_plate_name))
  382. conn.commit()
  383. st.rerun()
  384. if plates:
  385. selected_plate = st.selectbox("Select Active Plate", [p['plate_name'] for p in plates])
  386. active_p_id = next(p['id'] for p in plates if p['plate_name'] == selected_plate)
  387. cursor.execute("""
  388. SELECT i.id, i.product_code, i.quantity_grams, p.product_name, p.proteins_100g, p.fat_100g, p.carbohydrates_100g
  389. FROM plate_items i LEFT JOIN products p ON i.product_code = p.code WHERE i.plate_id = %s
  390. """, (active_p_id,))
  391. items = cursor.fetchall()
  392. if items:
  393. st.dataframe(items, use_container_width=True)
  394. total_pro = sum((float(i['proteins_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  395. total_fat = sum((float(i['fat_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  396. total_carb = sum((float(i['carbohydrates_100g'] or 0) * (float(i['quantity_grams'])/100.0)) for i in items)
  397. st.info(f"**Total Protein:** {total_pro:.1f}g | **Total Fat:** {total_fat:.1f}g | **Total Carbs:** {total_carb:.1f}g")
  398. st.markdown("---")
  399. add_code = st.text_input("Enter exact Product `code`")
  400. add_grams = st.number_input("Portion Quantity (Grams)", min_value=1.0, value=100.0)
  401. if st.button("Add Item"):
  402. cursor.execute("INSERT INTO plate_items (plate_id, product_code, quantity_grams) VALUES (%s, %s, %s)",
  403. (active_p_id, add_code, add_grams))
  404. conn.commit()
  405. st.rerun()
  406. with tab_planner:
  407. st.subheader("🤖 AI Meal Planner")
  408. p_col1, p_col2, p_col3 = st.columns(3)
  409. target_cal = p_col1.number_input("Target Daily Calories (kcal)", 1000, 5000, 2000, 50)
  410. diet_pref = p_col2.selectbox("Dietary Preference", ["Omnivore", "Vegetarian", "Vegan", "Keto", "Paleo"])
  411. meal_count = p_col3.slider("Number of Meals", 2, 6, 3)
  412. extra_notes = st.text_input("Any additional allergies or goals?")
  413. if st.button("Generate Professional Menu"):
  414. with st.spinner("AI is formulating..."):
  415. sys_prompt = f"""You are a professional Dietitian planner. Target: {target_cal}kcal over {meal_count} meals.
  416. Dietary constraint: {diet_pref}. Additional notes: {extra_notes}.
  417. CRITICAL INSTRUCTIONS:
  418. - ALWAYS output exactly as a strict Markdown table including Columns: | Meal | Food | Calories | Salt | Fat | Iron |
  419. - DO NOT output | separated text outside of standard strict markdown block ` ```markdown ` or standard rendering.
  420. - Convert ALL cooking measurements to Grams (g). Use these equivalents STRICTLY:
  421. 1 tbsp = 15g, 1 tsp = 5g, 1 cup = 200g, 1 mustard glass = 100g. 1 cl of liquid = 10g.
  422. """
  423. response = ollama.chat(model='mistral', messages=[{'role': 'system', 'content': sys_prompt}, {'role': 'user', 'content': 'Generate menu'}])
  424. st.markdown(response['message']['content'])
  425. if conn_reader: conn_reader.close()