Update pages/4_Diet_Plan.py
#1
by Sreehitha-V - opened
- pages/4_Diet_Plan.py +148 -81
pages/4_Diet_Plan.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
import streamlit as st
|
| 3 |
-
import os, sys
|
| 4 |
from datetime import date
|
| 5 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 6 |
from auth_token import logout
|
|
@@ -54,6 +54,95 @@ def cuisine_instruction():
|
|
| 54 |
instr += " Use NO red meat (no beef, pork, lamb, mutton). Only chicken, eggs or fish are allowed as proteins."
|
| 55 |
return instr
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# Pick background based on dietary type
|
| 58 |
if dietary_type == "nonveg":
|
| 59 |
bg_url = "https://images.unsplash.com/photo-1544025162-d76538b2a681?w=1800&q=80&auto=format&fit=crop"
|
|
@@ -330,7 +419,6 @@ with wc2:
|
|
| 330 |
st.rerun()
|
| 331 |
|
| 332 |
# FEATURE CARDS β collapsible expanders
|
| 333 |
-
import re as _re, json as _json
|
| 334 |
st.markdown("<div style='height:12px'></div>", unsafe_allow_html=True)
|
| 335 |
fe1, fe2, fe3 = st.columns(3)
|
| 336 |
|
|
@@ -494,106 +582,85 @@ for tab, day_data in zip(tabs, sdays):
|
|
| 494 |
icon = MEAL_ICONS.get(meal, "🍽️")
|
| 495 |
ck = "meal_d" + str(dn) + "_" + meal
|
| 496 |
done = st.session_state.get(ck, False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
strike = "text-decoration:line-through;opacity:0.40;" if done else ""
|
| 498 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
mc_top, mc_btn = st.columns([4,1])
|
| 500 |
with mc_top:
|
| 501 |
st.markdown(
|
| 502 |
"<div class='meal-card'>"
|
| 503 |
"<div class='meal-label'>"
|
| 504 |
"<span style='color:" + accent + "'>" + icon + " " + meal.upper() + "</span>"
|
|
|
|
| 505 |
+ (" <span style='color:" + accent + ";font-size:0.75rem'>✓ Done</span>" if done else "") +
|
| 506 |
"</div>"
|
| 507 |
-
"<div class='meal-text' style='" + strike + "'>" + str(
|
| 508 |
"</div>",
|
| 509 |
unsafe_allow_html=True
|
| 510 |
)
|
| 511 |
with mc_btn:
|
| 512 |
st.markdown("<div style='height:14px'></div>", unsafe_allow_html=True)
|
| 513 |
st.markdown("<div class='swap-mini'>", unsafe_allow_html=True)
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 535 |
st.markdown("</div>", unsafe_allow_html=True)
|
| 536 |
|
| 537 |
-
#
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
if
|
| 541 |
-
chosen = st.session_state.get(chosen_key, "original")
|
| 542 |
st.markdown(
|
| 543 |
-
"<div style='
|
| 544 |
-
"
|
| 545 |
-
"<div style='font-size:0.72rem;font-weight:700;letter-spacing:2px;text-transform:uppercase;"
|
| 546 |
-
"color:rgba(229,9,20,0.85);margin-bottom:8px'>🤖 Choose Your " + meal.title() + "</div>"
|
| 547 |
-
"<div style='display:flex;gap:8px;flex-wrap:wrap'>"
|
| 548 |
-
"<div style='flex:1;min-width:140px;background:" + ("rgba(229,9,20,0.25);border:2px solid #E50914" if chosen=="original" else "rgba(255,255,255,0.07);border:1.5px solid rgba(255,255,255,0.15)") + ";"
|
| 549 |
-
"border-radius:10px;padding:10px 12px;cursor:pointer'>"
|
| 550 |
-
"<div style='font-size:0.72rem;font-weight:700;letter-spacing:2px;text-transform:uppercase;"
|
| 551 |
-
"color:" + ("rgba(229,9,20,0.90)" if chosen=="original" else "rgba(255,255,255,0.45)") + ";margin-bottom:4px'>🌟 Original</div>"
|
| 552 |
-
"<div style='font-size:0.80rem;color:#fff;line-height:1.5'>" + str(desc) + "</div>"
|
| 553 |
-
"</div>"
|
| 554 |
-
"<div style='flex:1;min-width:140px;background:" + ("rgba(34,197,94,0.20);border:2px solid #22c55e" if chosen=="swap" else "rgba(255,255,255,0.07);border:1.5px solid rgba(255,255,255,0.15)") + ";"
|
| 555 |
-
"border-radius:10px;padding:10px 12px;cursor:pointer'>"
|
| 556 |
-
"<div style='font-size:0.72rem;font-weight:700;letter-spacing:2px;text-transform:uppercase;"
|
| 557 |
-
"color:" + ("rgba(34,197,94,0.90)" if chosen=="swap" else "rgba(255,255,255,0.45)") + ";margin-bottom:4px'>🤖 AI Alternative</div>"
|
| 558 |
-
"<div style='font-size:0.80rem;color:#fff;line-height:1.5'>" + swap_res + "</div>"
|
| 559 |
-
"</div>"
|
| 560 |
-
"</div></div>",
|
| 561 |
unsafe_allow_html=True
|
| 562 |
)
|
| 563 |
-
pick1, pick2, pick3 = st.columns([2,2,1])
|
| 564 |
-
with pick1:
|
| 565 |
-
if st.button(
|
| 566 |
-
("✓ Original" if chosen=="original" else "Keep Original"),
|
| 567 |
-
key="pick_orig_" + str(dn) + "_" + meal,
|
| 568 |
-
use_container_width=True
|
| 569 |
-
):
|
| 570 |
-
st.session_state[chosen_key] = "original"
|
| 571 |
-
st.rerun()
|
| 572 |
-
with pick2:
|
| 573 |
-
if st.button(
|
| 574 |
-
("✓ AI Swap" if chosen=="swap" else "Use AI Swap"),
|
| 575 |
-
key="pick_swap_" + str(dn) + "_" + meal,
|
| 576 |
-
use_container_width=True
|
| 577 |
-
):
|
| 578 |
-
st.session_state[chosen_key] = "swap"
|
| 579 |
-
st.rerun()
|
| 580 |
-
with pick3:
|
| 581 |
-
if st.button("✕", key="dismiss_swap_" + str(dn) + "_" + meal, use_container_width=True):
|
| 582 |
-
st.session_state.pop("swap_result_" + str(dn) + "_" + meal, None)
|
| 583 |
-
st.session_state.pop(chosen_key, None)
|
| 584 |
-
st.rerun()
|
| 585 |
-
if chosen == "swap":
|
| 586 |
-
st.markdown(
|
| 587 |
-
"<div style='font-size:0.72rem;color:rgba(34,197,94,0.85);font-weight:600;"
|
| 588 |
-
"padding:4px 0'>🤖 AI Alternative selected for today</div>",
|
| 589 |
-
unsafe_allow_html=True
|
| 590 |
-
)
|
| 591 |
-
else:
|
| 592 |
-
st.markdown(
|
| 593 |
-
"<div style='font-size:0.72rem;color:rgba(229,9,20,0.75);padding:4px 0'>"
|
| 594 |
-
"🌟 Original meal selected</div>",
|
| 595 |
-
unsafe_allow_html=True
|
| 596 |
-
)
|
| 597 |
|
| 598 |
# Checkbox
|
| 599 |
if st.checkbox("Mark as done", value=done, key=ck+"_cb"):
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
import streamlit as st
|
| 3 |
+
import os, sys, json as _json, re as _re
|
| 4 |
from datetime import date
|
| 5 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 6 |
from auth_token import logout
|
|
|
|
| 54 |
instr += " Use NO red meat (no beef, pork, lamb, mutton). Only chicken, eggs or fish are allowed as proteins."
|
| 55 |
return instr
|
| 56 |
|
| 57 |
+
# ββ TASK 4: Helper to convert AI JSON response β clean readable text ββββββββββ
|
| 58 |
+
def _clean_swap_response(raw: str) -> str:
|
| 59 |
+
"""
|
| 60 |
+
Converts any AI response (JSON array/object or plain text) into
|
| 61 |
+
a clean human-readable meal description string.
|
| 62 |
+
Never returns raw JSON brackets or quotes in the UI.
|
| 63 |
+
"""
|
| 64 |
+
if not raw:
|
| 65 |
+
return ""
|
| 66 |
+
raw = raw.strip()
|
| 67 |
+
|
| 68 |
+
# Try to parse as JSON first
|
| 69 |
+
# Strip code fences if present
|
| 70 |
+
raw_stripped = _re.sub(r"```[a-z]*", "", raw).strip().rstrip("```").strip()
|
| 71 |
+
|
| 72 |
+
parsed = None
|
| 73 |
+
if raw_stripped.startswith("[") or raw_stripped.startswith("{"):
|
| 74 |
+
try:
|
| 75 |
+
parsed = _json.loads(raw_stripped)
|
| 76 |
+
except Exception:
|
| 77 |
+
# Try to fix common issues: trailing commas, single quotes
|
| 78 |
+
try:
|
| 79 |
+
fixed = raw_stripped.replace("'", '"')
|
| 80 |
+
parsed = _json.loads(fixed)
|
| 81 |
+
except Exception:
|
| 82 |
+
parsed = None
|
| 83 |
+
|
| 84 |
+
if parsed is not None:
|
| 85 |
+
# Handle array of objects: [{"Avocado Toast": {"bread": "2 slices", ...}}, ...]
|
| 86 |
+
# or [{"name": "...", "ingredients": {...}}, ...]
|
| 87 |
+
# or a flat dict: {"name": "...", "ingredients": "..."}
|
| 88 |
+
parts = []
|
| 89 |
+
|
| 90 |
+
def _flatten_dict(d):
|
| 91 |
+
"""Flatten a dict of ingredient:amount pairs into a readable string."""
|
| 92 |
+
if isinstance(d, dict):
|
| 93 |
+
items = []
|
| 94 |
+
for k, v in d.items():
|
| 95 |
+
if isinstance(v, (dict, list)):
|
| 96 |
+
items.append(f"{k}: {_flatten_dict(v)}")
|
| 97 |
+
else:
|
| 98 |
+
items.append(f"{v} {k}".strip())
|
| 99 |
+
return ", ".join(items)
|
| 100 |
+
elif isinstance(d, list):
|
| 101 |
+
return ", ".join(str(x) for x in d)
|
| 102 |
+
else:
|
| 103 |
+
return str(d)
|
| 104 |
+
|
| 105 |
+
items_to_process = parsed if isinstance(parsed, list) else [parsed]
|
| 106 |
+
for item in items_to_process:
|
| 107 |
+
if isinstance(item, dict):
|
| 108 |
+
# Check for standard keys first
|
| 109 |
+
name = item.get("name") or item.get("meal") or item.get("dish") or ""
|
| 110 |
+
ingredients = item.get("ingredients") or item.get("items") or item.get("components") or {}
|
| 111 |
+
if name and ingredients:
|
| 112 |
+
if isinstance(ingredients, dict):
|
| 113 |
+
ing_str = _flatten_dict(ingredients)
|
| 114 |
+
elif isinstance(ingredients, list):
|
| 115 |
+
ing_str = ", ".join(str(x) for x in ingredients)
|
| 116 |
+
else:
|
| 117 |
+
ing_str = str(ingredients)
|
| 118 |
+
parts.append(f"{name} ({ing_str})")
|
| 119 |
+
elif name:
|
| 120 |
+
parts.append(name)
|
| 121 |
+
else:
|
| 122 |
+
# The dict key IS the meal name, value is the ingredients dict
|
| 123 |
+
for meal_name, meal_details in item.items():
|
| 124 |
+
if isinstance(meal_details, dict):
|
| 125 |
+
ing_str = _flatten_dict(meal_details)
|
| 126 |
+
parts.append(f"{meal_name} ({ing_str})")
|
| 127 |
+
elif isinstance(meal_details, str):
|
| 128 |
+
parts.append(f"{meal_name}: {meal_details}")
|
| 129 |
+
else:
|
| 130 |
+
parts.append(str(meal_name))
|
| 131 |
+
elif isinstance(item, str):
|
| 132 |
+
parts.append(item)
|
| 133 |
+
|
| 134 |
+
if parts:
|
| 135 |
+
return "; ".join(parts)
|
| 136 |
+
|
| 137 |
+
# If not JSON or parsing failed, return cleaned plain text
|
| 138 |
+
# Remove any remaining JSON artifacts
|
| 139 |
+
clean = _re.sub(r'[\[\]\{\}"]', '', raw_stripped)
|
| 140 |
+
clean = _re.sub(r'\s+', ' ', clean).strip()
|
| 141 |
+
# Remove leading/trailing punctuation artifacts
|
| 142 |
+
clean = clean.strip(",;: ")
|
| 143 |
+
return clean if clean else raw.strip()
|
| 144 |
+
|
| 145 |
+
|
| 146 |
# Pick background based on dietary type
|
| 147 |
if dietary_type == "nonveg":
|
| 148 |
bg_url = "https://images.unsplash.com/photo-1544025162-d76538b2a681?w=1800&q=80&auto=format&fit=crop"
|
|
|
|
| 419 |
st.rerun()
|
| 420 |
|
| 421 |
# FEATURE CARDS β collapsible expanders
|
|
|
|
| 422 |
st.markdown("<div style='height:12px'></div>", unsafe_allow_html=True)
|
| 423 |
fe1, fe2, fe3 = st.columns(3)
|
| 424 |
|
|
|
|
| 582 |
icon = MEAL_ICONS.get(meal, "🍽️")
|
| 583 |
ck = "meal_d" + str(dn) + "_" + meal
|
| 584 |
done = st.session_state.get(ck, False)
|
| 585 |
+
|
| 586 |
+
# ββ TASK 5: Determine which meal content to show ββββββββββββββ
|
| 587 |
+
# If user selected "Use AI Swap", show that content in the same card
|
| 588 |
+
chosen_key = "meal_choice_" + str(dn) + "_" + meal
|
| 589 |
+
swap_res_key = "swap_result_" + str(dn) + "_" + meal
|
| 590 |
+
swap_res = st.session_state.get(swap_res_key, "")
|
| 591 |
+
chosen = st.session_state.get(chosen_key, "original")
|
| 592 |
+
|
| 593 |
+
# The displayed meal content: original or swapped
|
| 594 |
+
display_desc = swap_res if (chosen == "swap" and swap_res) else desc
|
| 595 |
+
is_swapped = chosen == "swap" and bool(swap_res)
|
| 596 |
+
|
| 597 |
strike = "text-decoration:line-through;opacity:0.40;" if done else ""
|
| 598 |
|
| 599 |
+
# ββ TASK 5: Single meal card that shows either original or swapped content ββ
|
| 600 |
+
swap_badge = ""
|
| 601 |
+
if is_swapped:
|
| 602 |
+
swap_badge = "<span style='font-size:0.62rem;font-weight:700;letter-spacing:1px;text-transform:uppercase;background:rgba(34,197,94,0.18);border:1px solid rgba(34,197,94,0.40);border-radius:100px;padding:2px 8px;color:rgba(34,197,94,0.90);margin-left:6px'>π€ AI Swap</span>"
|
| 603 |
+
|
| 604 |
mc_top, mc_btn = st.columns([4,1])
|
| 605 |
with mc_top:
|
| 606 |
st.markdown(
|
| 607 |
"<div class='meal-card'>"
|
| 608 |
"<div class='meal-label'>"
|
| 609 |
"<span style='color:" + accent + "'>" + icon + " " + meal.upper() + "</span>"
|
| 610 |
+
+ swap_badge
|
| 611 |
+ (" <span style='color:" + accent + ";font-size:0.75rem'>✓ Done</span>" if done else "") +
|
| 612 |
"</div>"
|
| 613 |
+
"<div class='meal-text' style='" + strike + "'>" + str(display_desc) + "</div>"
|
| 614 |
"</div>",
|
| 615 |
unsafe_allow_html=True
|
| 616 |
)
|
| 617 |
with mc_btn:
|
| 618 |
st.markdown("<div style='height:14px'></div>", unsafe_allow_html=True)
|
| 619 |
st.markdown("<div class='swap-mini'>", unsafe_allow_html=True)
|
| 620 |
+
|
| 621 |
+
# If currently showing swapped, allow reverting to original
|
| 622 |
+
if is_swapped:
|
| 623 |
+
if st.button("β© Revert", key="revert_" + str(dn) + "_" + meal, use_container_width=True):
|
| 624 |
+
st.session_state[chosen_key] = "original"
|
| 625 |
+
st.rerun()
|
| 626 |
+
else:
|
| 627 |
+
if st.button("π€ Swap", key="swap_" + str(dn) + "_" + meal, use_container_width=True):
|
| 628 |
+
with st.spinner("Getting swap..."):
|
| 629 |
+
try:
|
| 630 |
+
from model_api import query_model
|
| 631 |
+
d_label = {"veg":"Vegetarian","nonveg":"Non-Vegetarian","both":"Flexible"}.get(dietary_type,"")
|
| 632 |
+
|
| 633 |
+
# ββ TASK 3 & 4: Cuisine-aware swap prompt ββββββββββββββ
|
| 634 |
+
# Force plain text response β explicitly forbid JSON
|
| 635 |
+
prompt = (
|
| 636 |
+
"Suggest 1 alternative " + meal + " meal for a "
|
| 637 |
+
+ d_label + " person (goal: " + data.get("goal","Fitness") + ")."
|
| 638 |
+
+ cuisine_instruction()
|
| 639 |
+
+ " Current meal: " + str(desc)
|
| 640 |
+
+ " Respond with ONLY a plain text description like: "
|
| 641 |
+
+ "MealName (ingredient1 quantity, ingredient2 quantity). "
|
| 642 |
+
+ "Do NOT use JSON, brackets, or lists. One sentence only."
|
| 643 |
+
)
|
| 644 |
+
raw_result = query_model(prompt, max_tokens=100)
|
| 645 |
+
# ββ TASK 4: Always clean the response ββ
|
| 646 |
+
clean_result = _clean_swap_response(raw_result)
|
| 647 |
+
st.session_state[swap_res_key] = clean_result
|
| 648 |
+
# ββ TASK 5: Immediately set choice to "swap" so it replaces in-place ββ
|
| 649 |
+
st.session_state[chosen_key] = "swap"
|
| 650 |
+
st.rerun()
|
| 651 |
+
except Exception as e:
|
| 652 |
+
st.error(str(e))
|
| 653 |
st.markdown("</div>", unsafe_allow_html=True)
|
| 654 |
|
| 655 |
+
# ββ TASK 5: No separate "Choose Your Breakfast" panel needed ββ
|
| 656 |
+
# The swap replaces directly in the card above.
|
| 657 |
+
# Only show a subtle undo confirmation if recently swapped.
|
| 658 |
+
if is_swapped:
|
|
|
|
| 659 |
st.markdown(
|
| 660 |
+
"<div style='font-size:0.72rem;color:rgba(34,197,94,0.85);font-weight:600;"
|
| 661 |
+
"padding:2px 0 6px 2px'>π€ AI Alternative active β click β© Revert to restore original</div>",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 662 |
unsafe_allow_html=True
|
| 663 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 664 |
|
| 665 |
# Checkbox
|
| 666 |
if st.checkbox("Mark as done", value=done, key=ck+"_cb"):
|