Add structured ingredient controls and hard validation
Browse files- README.md +12 -6
- app.py +222 -62
- biobite_logic.py +101 -1
README.md
CHANGED
|
@@ -15,19 +15,19 @@ short_description: Turn wearable recovery data into a meal and a next-day plan
|
|
| 15 |
|
| 16 |
Your smartwatch tells you that you slept 5 hours and hit a strain of 18/21. **So what should you eat?**
|
| 17 |
|
| 18 |
-
Bio-Bite closes the gap between *seeing* your recovery numbers and *knowing what to do with them*. Describe your day in plain language and
|
| 19 |
|
| 20 |
## How it works
|
| 21 |
|
| 22 |
```
|
| 23 |
-
USER INPUT (free text + wearable numbers)
|
| 24 |
↓
|
| 25 |
hybrid route to 1 of 6 recovery states
|
| 26 |
(65% semantic retrieval + 35% wearable-range fit)
|
| 27 |
↓
|
| 28 |
embed query → FAISS search over 10,000 recipes
|
| 29 |
↓
|
| 30 |
-
3
|
| 31 |
↓
|
| 32 |
AI OUTPUT: new recipe · why it works · tomorrow's plan
|
| 33 |
```
|
|
@@ -43,9 +43,15 @@ AI OUTPUT: new recipe · why it works · tomorrow's plan
|
|
| 43 |
|
| 44 |
The recovery guidance is **encoded in code**, not invented by the model. Each of
|
| 45 |
the six recovery states maps to cautious guidance. The language model creates the
|
| 46 |
-
new recipe, but every result must pass structure,
|
| 47 |
-
preparation-time checks before it is shown.
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
The app deliberately uses cautious language for uncertain relationships. For
|
| 51 |
example, magnesium-rich foods may support nutritional adequacy, but the app does
|
|
|
|
| 15 |
|
| 16 |
Your smartwatch tells you that you slept 5 hours and hit a strain of 18/21. **So what should you eat?**
|
| 17 |
|
| 18 |
+
Bio-Bite closes the gap between *seeing* your recovery numbers and *knowing what to do with them*. Describe your day in plain language, then select a main ingredient, up to three additional ingredients, exclusions and a diet. It returns three matched recovery meals, one brand-new recipe that is guaranteed to contain the selected ingredients, the science behind it, and a plan for tomorrow.
|
| 19 |
|
| 20 |
## How it works
|
| 21 |
|
| 22 |
```
|
| 23 |
+
USER INPUT (free text + wearable numbers + structured food choices)
|
| 24 |
↓
|
| 25 |
hybrid route to 1 of 6 recovery states
|
| 26 |
(65% semantic retrieval + 35% wearable-range fit)
|
| 27 |
↓
|
| 28 |
embed query → FAISS search over 10,000 recipes
|
| 29 |
↓
|
| 30 |
+
ingredient-aware 3 recommendations + RAG generation
|
| 31 |
↓
|
| 32 |
AI OUTPUT: new recipe · why it works · tomorrow's plan
|
| 33 |
```
|
|
|
|
| 43 |
|
| 44 |
The recovery guidance is **encoded in code**, not invented by the model. Each of
|
| 45 |
the six recovery states maps to cautious guidance. The language model creates the
|
| 46 |
+
new recipe, but every result must pass structure, required-ingredient,
|
| 47 |
+
excluded-ingredient, diet and preparation-time checks before it is shown.
|
| 48 |
+
Impossible choices such as `vegan + steak` or requiring and excluding eggs at the
|
| 49 |
+
same time are blocked before generation. Scientific wording and the next-day plan
|
| 50 |
+
are supplied deterministically from code.
|
| 51 |
+
|
| 52 |
+
If the free ZeroGPU generator is unavailable, the deterministic fallback still
|
| 53 |
+
honours selected ingredients, exclusions, diet and maximum preparation time. This
|
| 54 |
+
keeps the app usable without silently ignoring the user's request.
|
| 55 |
|
| 56 |
The app deliberately uses cautious language for uncertain relationships. For
|
| 57 |
example, magnesium-rich foods may support nutritional adequacy, but the app does
|
app.py
CHANGED
|
@@ -32,9 +32,11 @@ from biobite_logic import (
|
|
| 32 |
find_metric_conflicts,
|
| 33 |
grounded_explanation,
|
| 34 |
grounded_plan,
|
|
|
|
| 35 |
metric_category_scores,
|
| 36 |
optional_number,
|
| 37 |
parse_json_object,
|
|
|
|
| 38 |
validate_generation,
|
| 39 |
)
|
| 40 |
|
|
@@ -79,6 +81,19 @@ EMB_FILE = os.environ.get("BIOBITE_EMBEDDINGS_FILE", "biobite_embeddings.parquet
|
|
| 79 |
GUIDANCE_FILE = "recovery_guidance.json"
|
| 80 |
SPOONACULAR_KEY = os.environ.get("SPOONACULAR_API_KEY", "")
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
np.random.seed(SEED)
|
| 83 |
torch.manual_seed(SEED)
|
| 84 |
|
|
@@ -128,7 +143,8 @@ print(f"Ready — {len(df)} recipes indexed. "
|
|
| 128 |
# --------------------------------------------------------------------------
|
| 129 |
# Retrieval
|
| 130 |
# --------------------------------------------------------------------------
|
| 131 |
-
def retrieve(user_text, k=3, diet=None, max_prep=None, category=None, pool=500
|
|
|
|
| 132 |
"""Top-k recovery recipes for a free-text description of the user's day."""
|
| 133 |
q = embedder.encode(
|
| 134 |
[QUERY_PREFIX + user_text], convert_to_numpy=True, normalize_embeddings=True
|
|
@@ -142,6 +158,25 @@ def retrieve(user_text, k=3, diet=None, max_prep=None, category=None, pool=500):
|
|
| 142 |
cand = cand[cand["diet_tag"] == diet]
|
| 143 |
if max_prep:
|
| 144 |
cand = cand[cand["Prep_Time"] <= max_prep]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
if len(cand) == 0: # filters too strict -> fall back to unfiltered
|
| 146 |
cand = df.iloc[idx[0]].copy()
|
| 147 |
cand["similarity"] = scores[0]
|
|
@@ -257,7 +292,9 @@ A recommended recipe from our database, to use as inspiration:
|
|
| 257 |
- Ingredients: {ingredients}
|
| 258 |
- Prep time: {prep} minutes
|
| 259 |
|
| 260 |
-
The athlete
|
|
|
|
|
|
|
| 261 |
Selected diet: {diet}
|
| 262 |
Hard maximum preparation time: {max_prep}
|
| 263 |
|
|
@@ -266,9 +303,10 @@ Evidence-based recovery guidance you MUST follow (do not contradict it):
|
|
| 266 |
- Nutrition tomorrow: {nutrition}
|
| 267 |
- Sleep tonight: {sleep}
|
| 268 |
|
| 269 |
-
Adapt the recipe into a NEW dish that respects
|
| 270 |
-
meeting the nutritional need.
|
| 271 |
-
|
|
|
|
| 272 |
that magnesium cures insomnia, anxiety, stress, or cortisol problems.
|
| 273 |
Then write tomorrow's recovery plan.
|
| 274 |
Write in ENGLISH only.
|
|
@@ -314,7 +352,8 @@ def _generate_raw(prompt):
|
|
| 314 |
|
| 315 |
|
| 316 |
def generate_biobite(source_row, state, constraint, category, numbers,
|
| 317 |
-
diet="Any", max_prep=None
|
|
|
|
| 318 |
"""RAG generation: retrieved recipe + coded science -> new recipe + plan."""
|
| 319 |
g = NEXT_DAY_GUIDANCE[category]
|
| 320 |
prompt = PROMPT.format(
|
|
@@ -322,28 +361,42 @@ def generate_biobite(source_row, state, constraint, category, numbers,
|
|
| 322 |
need=source_row["Nutritional_Need"], name=source_row["Recipe_Name"],
|
| 323 |
ingredients=source_row["Ingredients"], prep=source_row["Prep_Time"],
|
| 324 |
constraint=constraint, diet=diet,
|
|
|
|
|
|
|
| 325 |
max_prep=f"{max_prep} minutes" if max_prep else "not specified",
|
| 326 |
training=g["training"],
|
| 327 |
nutrition=g["nutrition"], sleep=g["sleep"],
|
| 328 |
)
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
LAST_ERROR["detail"] = "; ".join(errors) + " | " + raw[:220]
|
| 346 |
-
print("GENERATION VALIDATION FAILED:", LAST_ERROR["detail"])
|
|
|
|
| 347 |
return None
|
| 348 |
# Scientific and training claims stay deterministic. The model is used for
|
| 349 |
# the new recipe, while coded guidance supplies the explanation and plan.
|
|
@@ -382,13 +435,23 @@ TEXT = "#dfeee4"
|
|
| 382 |
MUTED = "#8aa695"
|
| 383 |
|
| 384 |
|
| 385 |
-
def cards_html(rows):
|
| 386 |
cards = []
|
| 387 |
for _, r in rows.iterrows():
|
| 388 |
category = html.escape(str(r["recovery_category"]))
|
| 389 |
recipe_name = html.escape(str(r["Recipe_Name"]))
|
| 390 |
cuisine = html.escape(str(r["cuisine"]))
|
| 391 |
diet_tag = html.escape(str(r["diet_tag"]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
cards.append(f"""
|
| 393 |
<div style="flex:1;min-width:210px;{PANEL}padding:14px;">
|
| 394 |
<div style="font-size:11px;text-transform:uppercase;letter-spacing:.6px;
|
|
@@ -399,7 +462,9 @@ def cards_html(rows):
|
|
| 399 |
⏱ {r['Prep_Time']} min · 🔥 {r['calories']} kcal<br>
|
| 400 |
🥩 {r['protein_g']}g protein · 🌾 {r['carbs_g']}g carbs<br>
|
| 401 |
✨ {r['magnesium_mg']}mg magnesium<br>
|
|
|
|
| 402 |
<span style="color:{MUTED};">{cuisine} · {diet_tag}</span>
|
|
|
|
| 403 |
</div>
|
| 404 |
</div>""")
|
| 405 |
return ('<div style="display:flex;gap:12px;flex-wrap:wrap;">'
|
|
@@ -432,7 +497,17 @@ def recipe_html(obj, image_url=None):
|
|
| 432 |
</div>"""
|
| 433 |
|
| 434 |
|
| 435 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
"""Last-resort output built WITHOUT the language model.
|
| 437 |
|
| 438 |
Because the recovery science is encoded in `recovery_guidance.json`, we can
|
|
@@ -440,24 +515,45 @@ def template_fallback(source_row, category):
|
|
| 440 |
fails — the app degrades gracefully instead of dead-ending.
|
| 441 |
"""
|
| 442 |
g = NEXT_DAY_GUIDANCE[category]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
obj = {
|
| 444 |
-
"Recipe_Name":
|
| 445 |
-
"Ingredients":
|
| 446 |
-
"Instructions":
|
| 447 |
-
"prep_time_min":
|
| 448 |
-
"why_it_works": (
|
| 449 |
-
|
| 450 |
-
f"{source_row['Nutritional_Need']} It provides "
|
| 451 |
-
f"{source_row['protein_g']}g protein, {source_row['carbs_g']}g carbohydrate "
|
| 452 |
-
f"and {source_row['magnesium_mg']}mg magnesium."
|
| 453 |
-
),
|
| 454 |
-
"next_day_plan": "\n".join([
|
| 455 |
-
"07:30 - Hydrate on waking, then eat a balanced breakfast.",
|
| 456 |
-
f"Nutrition - {g['nutrition']}",
|
| 457 |
-
f"Training - {g['training']}",
|
| 458 |
-
"19:00 - Eat your recovery meal at least 2 hours before bed.",
|
| 459 |
-
f"Sleep - {g['sleep']}",
|
| 460 |
-
]),
|
| 461 |
}
|
| 462 |
return obj
|
| 463 |
|
|
@@ -480,7 +576,8 @@ def plan_html(plan_text, category):
|
|
| 480 |
# --------------------------------------------------------------------------
|
| 481 |
# Main callback
|
| 482 |
# --------------------------------------------------------------------------
|
| 483 |
-
def run(state,
|
|
|
|
| 484 |
# ---- Layer 1: validate the input -------------------------------------
|
| 485 |
status, state, message = validate_input(state)
|
| 486 |
if status == "error":
|
|
@@ -488,6 +585,23 @@ def run(state, constraint, diet, max_prep, sleep_hours, strain, hrv):
|
|
| 488 |
warning = notice_html(message) if status == "warn" else ""
|
| 489 |
|
| 490 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
sleep_value = optional_number(sleep_hours, 0, 10)
|
| 492 |
strain_value = optional_number(strain, 0, 21)
|
| 493 |
hrv_value = optional_number(hrv, 10, 150)
|
|
@@ -514,7 +628,10 @@ def run(state, constraint, diet, max_prep, sleep_hours, strain, hrv):
|
|
| 514 |
# ---- Layer 2: retrieve, relaxing filters if they are too strict ---
|
| 515 |
want_prep = int(max_prep) if max_prep else None
|
| 516 |
top3 = retrieve(
|
| 517 |
-
profile_query, k=3, diet=diet, max_prep=want_prep, category=category
|
|
|
|
|
|
|
|
|
|
| 518 |
)
|
| 519 |
relaxed = ""
|
| 520 |
if want_prep and (top3["Prep_Time"] > want_prep).any():
|
|
@@ -523,13 +640,22 @@ def run(state, constraint, diet, max_prep, sleep_hours, strain, hrv):
|
|
| 523 |
f"was relaxed.")
|
| 524 |
elif diet and diet != "Any" and (top3["diet_tag"] != diet).any():
|
| 525 |
relaxed = f"Not enough {diet} matches, so the diet filter was relaxed."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
|
| 527 |
header = (f'<div style="font-size:13px;color:{MUTED};margin:10px 0;">'
|
| 528 |
f'Detected recovery state: '
|
| 529 |
f'<b style="color:{GREEN};">{html.escape(category)}</b> · '
|
| 530 |
f'{html.escape(numbers)} · hybrid routing score '
|
| 531 |
f'{route_scores[category]:.2f}</div>')
|
| 532 |
-
recs = warning + (notice_html(relaxed) if relaxed else "") + header +
|
|
|
|
| 533 |
|
| 534 |
if not constraint or not constraint.strip():
|
| 535 |
constraint = "Keep it simple with easy-to-find ingredients."
|
|
@@ -538,31 +664,38 @@ def run(state, constraint, diet, max_prep, sleep_hours, strain, hrv):
|
|
| 538 |
obj = generate_biobite(
|
| 539 |
top3.iloc[0], state, constraint, category, numbers,
|
| 540 |
diet=diet, max_prep=want_prep,
|
|
|
|
|
|
|
| 541 |
)
|
| 542 |
|
| 543 |
note = ""
|
| 544 |
if obj is None:
|
| 545 |
-
obj = template_fallback(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 546 |
if LAST_ERROR["reason"] == "gpu":
|
| 547 |
detail = LAST_ERROR["detail"].lower()
|
| 548 |
if "quota" in detail or "exceeded" in detail:
|
| 549 |
note = notice_html(
|
| 550 |
"The free daily GPU allowance for this Space has run out, so "
|
| 551 |
-
"this is
|
| 552 |
-
"
|
| 553 |
else:
|
| 554 |
note = notice_html(
|
| 555 |
"The AI generator is temporarily unavailable, so this is the "
|
| 556 |
-
"
|
| 557 |
-
"recovery plan.")
|
| 558 |
elif LAST_ERROR["reason"] == "validation":
|
| 559 |
note = notice_html(
|
| 560 |
"The generated recipe did not pass the format or constraint checks, "
|
| 561 |
-
"so
|
| 562 |
else:
|
| 563 |
note = notice_html(
|
| 564 |
"The generator returned an unexpected response, so this is the best "
|
| 565 |
-
"
|
| 566 |
|
| 567 |
img = fetch_dish_image(obj["Recipe_Name"])
|
| 568 |
return recs, note + recipe_html(obj, img), plan_html(obj["next_day_plan"], category)
|
|
@@ -585,11 +718,11 @@ def run(state, constraint, diet, max_prep, sleep_hours, strain, hrv):
|
|
| 585 |
# --------------------------------------------------------------------------
|
| 586 |
QUICK_STARTERS = [
|
| 587 |
["I did a heavy CrossFit workout today but only slept 4 hours and I'm exhausted",
|
| 588 |
-
"
|
| 589 |
["I ran a half marathon this morning and I'm completely drained",
|
| 590 |
-
"
|
| 591 |
["Really stressful week at work, barely sleeping, my HRV has dropped",
|
| 592 |
-
"
|
| 593 |
]
|
| 594 |
|
| 595 |
THEME = gr.themes.Base(
|
|
@@ -657,11 +790,6 @@ with gr.Blocks(title="Bio-Bite", theme=THEME, css=CSS, js=FORCE_DARK) as demo:
|
|
| 657 |
placeholder="e.g. Heavy leg day at the gym, slept badly, feeling wrecked…",
|
| 658 |
lines=3,
|
| 659 |
)
|
| 660 |
-
constraint = gr.Textbox(
|
| 661 |
-
label="👨🍳 What's in your fridge? Any constraints?",
|
| 662 |
-
placeholder="e.g. Only tofu and rice, 15 minutes, no nuts",
|
| 663 |
-
lines=2,
|
| 664 |
-
)
|
| 665 |
with gr.Column(scale=2):
|
| 666 |
diet = gr.Dropdown(
|
| 667 |
["Any", "omnivore", "vegetarian", "vegan", "pescatarian", "gluten-free"],
|
|
@@ -681,13 +809,44 @@ with gr.Blocks(title="Bio-Bite", theme=THEME, css=CSS, js=FORCE_DARK) as demo:
|
|
| 681 |
label="HRV today (ms) — optional",
|
| 682 |
)
|
| 683 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 684 |
btn = gr.Button("🍽️ Generate My Bio-Bite", variant="primary", size="lg")
|
| 685 |
|
| 686 |
gr.Markdown("### ⚡ Quick starters — one click to try it",
|
| 687 |
elem_classes="bb-sec")
|
| 688 |
gr.Examples(
|
| 689 |
examples=QUICK_STARTERS,
|
| 690 |
-
inputs=[state,
|
|
|
|
| 691 |
label="",
|
| 692 |
)
|
| 693 |
|
|
@@ -720,7 +879,8 @@ with gr.Blocks(title="Bio-Bite", theme=THEME, css=CSS, js=FORCE_DARK) as demo:
|
|
| 720 |
|
| 721 |
btn.click(
|
| 722 |
run,
|
| 723 |
-
inputs=[state,
|
|
|
|
| 724 |
outputs=[out_recs, out_recipe, out_plan],
|
| 725 |
)
|
| 726 |
|
|
|
|
| 32 |
find_metric_conflicts,
|
| 33 |
grounded_explanation,
|
| 34 |
grounded_plan,
|
| 35 |
+
ingredient_present,
|
| 36 |
metric_category_scores,
|
| 37 |
optional_number,
|
| 38 |
parse_json_object,
|
| 39 |
+
validate_food_preferences,
|
| 40 |
validate_generation,
|
| 41 |
)
|
| 42 |
|
|
|
|
| 81 |
GUIDANCE_FILE = "recovery_guidance.json"
|
| 82 |
SPOONACULAR_KEY = os.environ.get("SPOONACULAR_API_KEY", "")
|
| 83 |
|
| 84 |
+
MAIN_INGREDIENT_CHOICES = [
|
| 85 |
+
"No preference", "Steak / beef", "Chicken", "Salmon", "Tuna", "Eggs",
|
| 86 |
+
"Tofu", "Tempeh", "Lentils", "Chickpeas", "Greek yogurt",
|
| 87 |
+
]
|
| 88 |
+
EXTRA_INGREDIENT_CHOICES = [
|
| 89 |
+
"Rice", "Quinoa", "Pasta", "Potatoes", "Sweet potato", "Oats", "Spinach",
|
| 90 |
+
"Broccoli", "Tomato", "Avocado", "Mushrooms", "Bell pepper", "Beans",
|
| 91 |
+
]
|
| 92 |
+
EXCLUDED_INGREDIENT_CHOICES = [
|
| 93 |
+
"Peanuts", "Tree nuts", "Dairy", "Gluten", "Fish / shellfish", "Eggs",
|
| 94 |
+
"Soy", "Sesame", "Caffeine",
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
np.random.seed(SEED)
|
| 98 |
torch.manual_seed(SEED)
|
| 99 |
|
|
|
|
| 143 |
# --------------------------------------------------------------------------
|
| 144 |
# Retrieval
|
| 145 |
# --------------------------------------------------------------------------
|
| 146 |
+
def retrieve(user_text, k=3, diet=None, max_prep=None, category=None, pool=500,
|
| 147 |
+
required_ingredients=None, excluded_ingredients=None):
|
| 148 |
"""Top-k recovery recipes for a free-text description of the user's day."""
|
| 149 |
q = embedder.encode(
|
| 150 |
[QUERY_PREFIX + user_text], convert_to_numpy=True, normalize_embeddings=True
|
|
|
|
| 158 |
cand = cand[cand["diet_tag"] == diet]
|
| 159 |
if max_prep:
|
| 160 |
cand = cand[cand["Prep_Time"] <= max_prep]
|
| 161 |
+
searchable = cand["Recipe_Name"].astype(str) + " " + cand["Ingredients"].astype(str)
|
| 162 |
+
# The main selected ingredient is also used for retrieval when matching
|
| 163 |
+
# dataset recipes exist. Extra required ingredients remain hard rules for
|
| 164 |
+
# generation, but requiring every combination here would often return zero.
|
| 165 |
+
if required_ingredients:
|
| 166 |
+
main_matches = searchable.map(
|
| 167 |
+
lambda value: ingredient_present(value, required_ingredients[0])
|
| 168 |
+
)
|
| 169 |
+
if main_matches.any():
|
| 170 |
+
matched = cand[main_matches]
|
| 171 |
+
remainder = cand[~main_matches]
|
| 172 |
+
cand = pd.concat([matched, remainder])
|
| 173 |
+
searchable = cand["Recipe_Name"].astype(str) + " " + cand["Ingredients"].astype(str)
|
| 174 |
+
if excluded_ingredients and len(cand):
|
| 175 |
+
safe = searchable.map(lambda value: not any(
|
| 176 |
+
ingredient_present(value, blocked) for blocked in excluded_ingredients
|
| 177 |
+
))
|
| 178 |
+
if safe.any():
|
| 179 |
+
cand = cand[safe]
|
| 180 |
if len(cand) == 0: # filters too strict -> fall back to unfiltered
|
| 181 |
cand = df.iloc[idx[0]].copy()
|
| 182 |
cand["similarity"] = scores[0]
|
|
|
|
| 292 |
- Ingredients: {ingredients}
|
| 293 |
- Prep time: {prep} minutes
|
| 294 |
|
| 295 |
+
The athlete's additional request is: "{constraint}"
|
| 296 |
+
Required ingredients — EVERY item must appear in the final Ingredients field: {required_ingredients}
|
| 297 |
+
Excluded ingredients — NONE may appear in the final recipe: {excluded_ingredients}
|
| 298 |
Selected diet: {diet}
|
| 299 |
Hard maximum preparation time: {max_prep}
|
| 300 |
|
|
|
|
| 303 |
- Nutrition tomorrow: {nutrition}
|
| 304 |
- Sleep tonight: {sleep}
|
| 305 |
|
| 306 |
+
Adapt the recipe into a NEW dish that respects every structured choice while still
|
| 307 |
+
meeting the nutritional need. Required ingredients are hard constraints, not ideas.
|
| 308 |
+
Never use an excluded ingredient or violate the selected diet or maximum preparation
|
| 309 |
+
time. Avoid treatment claims and do not claim
|
| 310 |
that magnesium cures insomnia, anxiety, stress, or cortisol problems.
|
| 311 |
Then write tomorrow's recovery plan.
|
| 312 |
Write in ENGLISH only.
|
|
|
|
| 352 |
|
| 353 |
|
| 354 |
def generate_biobite(source_row, state, constraint, category, numbers,
|
| 355 |
+
diet="Any", max_prep=None, required_ingredients=None,
|
| 356 |
+
excluded_ingredients=None):
|
| 357 |
"""RAG generation: retrieved recipe + coded science -> new recipe + plan."""
|
| 358 |
g = NEXT_DAY_GUIDANCE[category]
|
| 359 |
prompt = PROMPT.format(
|
|
|
|
| 361 |
need=source_row["Nutritional_Need"], name=source_row["Recipe_Name"],
|
| 362 |
ingredients=source_row["Ingredients"], prep=source_row["Prep_Time"],
|
| 363 |
constraint=constraint, diet=diet,
|
| 364 |
+
required_ingredients=", ".join(required_ingredients or []) or "none",
|
| 365 |
+
excluded_ingredients=", ".join(excluded_ingredients or []) or "none",
|
| 366 |
max_prep=f"{max_prep} minutes" if max_prep else "not specified",
|
| 367 |
training=g["training"],
|
| 368 |
nutrition=g["nutrition"], sleep=g["sleep"],
|
| 369 |
)
|
| 370 |
+
errors = []
|
| 371 |
+
for attempt in range(2):
|
| 372 |
+
attempt_prompt = prompt
|
| 373 |
+
if attempt and errors:
|
| 374 |
+
attempt_prompt += (
|
| 375 |
+
"\nYour previous answer failed these checks: " + "; ".join(errors) +
|
| 376 |
+
"\nCorrect every issue. Return one complete JSON object only."
|
| 377 |
+
)
|
| 378 |
+
try:
|
| 379 |
+
raw = _generate_raw(attempt_prompt)
|
| 380 |
+
except Exception as exc: # GPU worker error, quota, timeout…
|
| 381 |
+
print(f"GPU GENERATION FAILED [{type(exc).__name__}]: {exc}")
|
| 382 |
+
traceback.print_exc()
|
| 383 |
+
LAST_ERROR["reason"] = "gpu"
|
| 384 |
+
LAST_ERROR["detail"] = f"{type(exc).__name__}: {exc}"
|
| 385 |
+
return None
|
| 386 |
+
|
| 387 |
+
LAST_ERROR["reason"] = "validation"
|
| 388 |
+
LAST_ERROR["detail"] = raw[:300]
|
| 389 |
+
obj, errors = validate_generation(
|
| 390 |
+
parse_json_object(raw), selected_diet=diet,
|
| 391 |
+
constraint=constraint, selected_max=max_prep,
|
| 392 |
+
required_ingredients=required_ingredients,
|
| 393 |
+
excluded_ingredients=excluded_ingredients,
|
| 394 |
+
)
|
| 395 |
+
if obj is not None:
|
| 396 |
+
break
|
| 397 |
LAST_ERROR["detail"] = "; ".join(errors) + " | " + raw[:220]
|
| 398 |
+
print(f"GENERATION VALIDATION FAILED [attempt {attempt + 1}]:", LAST_ERROR["detail"])
|
| 399 |
+
if obj is None:
|
| 400 |
return None
|
| 401 |
# Scientific and training claims stay deterministic. The model is used for
|
| 402 |
# the new recipe, while coded guidance supplies the explanation and plan.
|
|
|
|
| 435 |
MUTED = "#8aa695"
|
| 436 |
|
| 437 |
|
| 438 |
+
def cards_html(rows, required_ingredients=None):
|
| 439 |
cards = []
|
| 440 |
for _, r in rows.iterrows():
|
| 441 |
category = html.escape(str(r["recovery_category"]))
|
| 442 |
recipe_name = html.escape(str(r["Recipe_Name"]))
|
| 443 |
cuisine = html.escape(str(r["cuisine"]))
|
| 444 |
diet_tag = html.escape(str(r["diet_tag"]))
|
| 445 |
+
ingredient_text = str(r["Ingredients"])
|
| 446 |
+
ingredient_preview = html.escape(
|
| 447 |
+
", ".join(part.strip() for part in ingredient_text.split(",")[:3])
|
| 448 |
+
)
|
| 449 |
+
matched = [value for value in (required_ingredients or [])
|
| 450 |
+
if ingredient_present(ingredient_text, value)]
|
| 451 |
+
match_badge = (
|
| 452 |
+
f'<div style="font-size:11px;color:{GREEN};margin-top:7px;">✓ Includes '
|
| 453 |
+
f'{html.escape(", ".join(matched))}</div>' if matched else ""
|
| 454 |
+
)
|
| 455 |
cards.append(f"""
|
| 456 |
<div style="flex:1;min-width:210px;{PANEL}padding:14px;">
|
| 457 |
<div style="font-size:11px;text-transform:uppercase;letter-spacing:.6px;
|
|
|
|
| 462 |
⏱ {r['Prep_Time']} min · 🔥 {r['calories']} kcal<br>
|
| 463 |
🥩 {r['protein_g']}g protein · 🌾 {r['carbs_g']}g carbs<br>
|
| 464 |
✨ {r['magnesium_mg']}mg magnesium<br>
|
| 465 |
+
🥣 {ingredient_preview}<br>
|
| 466 |
<span style="color:{MUTED};">{cuisine} · {diet_tag}</span>
|
| 467 |
+
{match_badge}
|
| 468 |
</div>
|
| 469 |
</div>""")
|
| 470 |
return ('<div style="display:flex;gap:12px;flex-wrap:wrap;">'
|
|
|
|
| 497 |
</div>"""
|
| 498 |
|
| 499 |
|
| 500 |
+
def _fallback_ingredient_name(label):
|
| 501 |
+
"""Turn a friendly UI label into natural recipe wording."""
|
| 502 |
+
return {
|
| 503 |
+
"Steak / beef": "steak",
|
| 504 |
+
"Greek yogurt": "Greek yogurt",
|
| 505 |
+
"Bell pepper": "bell pepper",
|
| 506 |
+
}.get(label, str(label).lower())
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def template_fallback(source_row, category, required_ingredients=None,
|
| 510 |
+
excluded_ingredients=None, max_prep=None, diet="Any"):
|
| 511 |
"""Last-resort output built WITHOUT the language model.
|
| 512 |
|
| 513 |
Because the recovery science is encoded in `recovery_guidance.json`, we can
|
|
|
|
| 515 |
fails — the app degrades gracefully instead of dead-ending.
|
| 516 |
"""
|
| 517 |
g = NEXT_DAY_GUIDANCE[category]
|
| 518 |
+
required_ingredients = required_ingredients or []
|
| 519 |
+
excluded_ingredients = excluded_ingredients or []
|
| 520 |
+
source_text = f"{source_row['Recipe_Name']} {source_row['Ingredients']}"
|
| 521 |
+
source_is_safe = not any(
|
| 522 |
+
ingredient_present(source_text, blocked) for blocked in excluded_ingredients
|
| 523 |
+
)
|
| 524 |
+
source_has_required = all(
|
| 525 |
+
ingredient_present(source_text, wanted) for wanted in required_ingredients
|
| 526 |
+
)
|
| 527 |
+
source_within_time = not max_prep or int(source_row["Prep_Time"]) <= int(max_prep)
|
| 528 |
+
source_matches_diet = diet == "Any" or source_row["diet_tag"] == diet
|
| 529 |
+
|
| 530 |
+
if source_is_safe and source_has_required and source_within_time and source_matches_diet:
|
| 531 |
+
recipe_name = source_row["Recipe_Name"]
|
| 532 |
+
ingredients = source_row["Ingredients"]
|
| 533 |
+
instructions = source_row["Instructions"]
|
| 534 |
+
prep_time = int(source_row["Prep_Time"])
|
| 535 |
+
else:
|
| 536 |
+
chosen = [_fallback_ingredient_name(value) for value in required_ingredients]
|
| 537 |
+
if not chosen:
|
| 538 |
+
chosen = ["quinoa", "chickpeas", "spinach"]
|
| 539 |
+
ingredients = ", ".join(
|
| 540 |
+
chosen + ["mixed vegetables", "olive oil", "lemon juice", "herbs", "salt"]
|
| 541 |
+
)
|
| 542 |
+
recipe_name = f"{chosen[0].title()} Recovery Bowl"
|
| 543 |
+
instructions = (
|
| 544 |
+
"1. Prepare the selected ingredients safely and cook animal proteins thoroughly. "
|
| 545 |
+
"2. Cook or warm the vegetables. 3. Combine everything with olive oil, lemon, "
|
| 546 |
+
"herbs and salt. 4. Serve warm."
|
| 547 |
+
)
|
| 548 |
+
prep_time = min(int(max_prep or 20), 20)
|
| 549 |
+
|
| 550 |
obj = {
|
| 551 |
+
"Recipe_Name": recipe_name,
|
| 552 |
+
"Ingredients": ingredients,
|
| 553 |
+
"Instructions": instructions,
|
| 554 |
+
"prep_time_min": prep_time,
|
| 555 |
+
"why_it_works": grounded_explanation(category),
|
| 556 |
+
"next_day_plan": grounded_plan(category, g),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
}
|
| 558 |
return obj
|
| 559 |
|
|
|
|
| 576 |
# --------------------------------------------------------------------------
|
| 577 |
# Main callback
|
| 578 |
# --------------------------------------------------------------------------
|
| 579 |
+
def run(state, main_ingredient, include_ingredients, excluded_ingredients,
|
| 580 |
+
constraint, diet, max_prep, sleep_hours, strain, hrv):
|
| 581 |
# ---- Layer 1: validate the input -------------------------------------
|
| 582 |
status, state, message = validate_input(state)
|
| 583 |
if status == "error":
|
|
|
|
| 585 |
warning = notice_html(message) if status == "warn" else ""
|
| 586 |
|
| 587 |
try:
|
| 588 |
+
required, excluded, food_errors = validate_food_preferences(
|
| 589 |
+
main_ingredient, include_ingredients, excluded_ingredients, diet
|
| 590 |
+
)
|
| 591 |
+
if food_errors:
|
| 592 |
+
friendly_errors = "<br>".join(
|
| 593 |
+
f"• {html.escape(error)}" for error in food_errors
|
| 594 |
+
)
|
| 595 |
+
return (
|
| 596 |
+
notice_html(
|
| 597 |
+
"Please fix these food preferences before generating:<br>" +
|
| 598 |
+
friendly_errors,
|
| 599 |
+
"error",
|
| 600 |
+
),
|
| 601 |
+
"",
|
| 602 |
+
"",
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
sleep_value = optional_number(sleep_hours, 0, 10)
|
| 606 |
strain_value = optional_number(strain, 0, 21)
|
| 607 |
hrv_value = optional_number(hrv, 10, 150)
|
|
|
|
| 628 |
# ---- Layer 2: retrieve, relaxing filters if they are too strict ---
|
| 629 |
want_prep = int(max_prep) if max_prep else None
|
| 630 |
top3 = retrieve(
|
| 631 |
+
profile_query, k=3, diet=diet, max_prep=want_prep, category=category,
|
| 632 |
+
pool=2000 if required else 500,
|
| 633 |
+
required_ingredients=required,
|
| 634 |
+
excluded_ingredients=excluded,
|
| 635 |
)
|
| 636 |
relaxed = ""
|
| 637 |
if want_prep and (top3["Prep_Time"] > want_prep).any():
|
|
|
|
| 640 |
f"was relaxed.")
|
| 641 |
elif diet and diet != "Any" and (top3["diet_tag"] != diet).any():
|
| 642 |
relaxed = f"Not enough {diet} matches, so the diet filter was relaxed."
|
| 643 |
+
if required and not ingredient_present(
|
| 644 |
+
f"{top3.iloc[0]['Recipe_Name']} {top3.iloc[0]['Ingredients']}", required[0]
|
| 645 |
+
):
|
| 646 |
+
ingredient_note = (
|
| 647 |
+
f"The dataset has no close {html.escape(required[0])} match for this "
|
| 648 |
+
"recovery state. The personalized recipe will still be required to include it."
|
| 649 |
+
)
|
| 650 |
+
relaxed = f"{relaxed} {ingredient_note}".strip()
|
| 651 |
|
| 652 |
header = (f'<div style="font-size:13px;color:{MUTED};margin:10px 0;">'
|
| 653 |
f'Detected recovery state: '
|
| 654 |
f'<b style="color:{GREEN};">{html.escape(category)}</b> · '
|
| 655 |
f'{html.escape(numbers)} · hybrid routing score '
|
| 656 |
f'{route_scores[category]:.2f}</div>')
|
| 657 |
+
recs = (warning + (notice_html(relaxed) if relaxed else "") + header +
|
| 658 |
+
cards_html(top3, required))
|
| 659 |
|
| 660 |
if not constraint or not constraint.strip():
|
| 661 |
constraint = "Keep it simple with easy-to-find ingredients."
|
|
|
|
| 664 |
obj = generate_biobite(
|
| 665 |
top3.iloc[0], state, constraint, category, numbers,
|
| 666 |
diet=diet, max_prep=want_prep,
|
| 667 |
+
required_ingredients=required,
|
| 668 |
+
excluded_ingredients=excluded,
|
| 669 |
)
|
| 670 |
|
| 671 |
note = ""
|
| 672 |
if obj is None:
|
| 673 |
+
obj = template_fallback(
|
| 674 |
+
top3.iloc[0], category,
|
| 675 |
+
required_ingredients=required,
|
| 676 |
+
excluded_ingredients=excluded,
|
| 677 |
+
max_prep=want_prep,
|
| 678 |
+
diet=diet,
|
| 679 |
+
)
|
| 680 |
if LAST_ERROR["reason"] == "gpu":
|
| 681 |
detail = LAST_ERROR["detail"].lower()
|
| 682 |
if "quota" in detail or "exceeded" in detail:
|
| 683 |
note = notice_html(
|
| 684 |
"The free daily GPU allowance for this Space has run out, so "
|
| 685 |
+
"this is a deterministic recipe that still respects your selected "
|
| 686 |
+
"ingredients, exclusions and time limit. The allowance resets every 24 hours.")
|
| 687 |
else:
|
| 688 |
note = notice_html(
|
| 689 |
"The AI generator is temporarily unavailable, so this is the "
|
| 690 |
+
"deterministic recipe that still respects your structured choices.")
|
|
|
|
| 691 |
elif LAST_ERROR["reason"] == "validation":
|
| 692 |
note = notice_html(
|
| 693 |
"The generated recipe did not pass the format or constraint checks, "
|
| 694 |
+
"so a deterministic recipe that respects your structured choices is shown.")
|
| 695 |
else:
|
| 696 |
note = notice_html(
|
| 697 |
"The generator returned an unexpected response, so this is the best "
|
| 698 |
+
"safe deterministic recipe is shown instead.")
|
| 699 |
|
| 700 |
img = fetch_dish_image(obj["Recipe_Name"])
|
| 701 |
return recs, note + recipe_html(obj, img), plan_html(obj["next_day_plan"], category)
|
|
|
|
| 718 |
# --------------------------------------------------------------------------
|
| 719 |
QUICK_STARTERS = [
|
| 720 |
["I did a heavy CrossFit workout today but only slept 4 hours and I'm exhausted",
|
| 721 |
+
"Tofu", ["Rice"], ["Peanuts"], "Keep it simple", "Any", 20, 4, 18, 32],
|
| 722 |
["I ran a half marathon this morning and I'm completely drained",
|
| 723 |
+
"Eggs", ["Rice", "Sweet potato"], [], "Carb-heavy", "vegetarian", 40, 7, 19, 41],
|
| 724 |
["Really stressful week at work, barely sleeping, my HRV has dropped",
|
| 725 |
+
"Tofu", ["Spinach"], ["Caffeine"], "One-pan meal", "Any", 30, 5, 8, 29],
|
| 726 |
]
|
| 727 |
|
| 728 |
THEME = gr.themes.Base(
|
|
|
|
| 790 |
placeholder="e.g. Heavy leg day at the gym, slept badly, feeling wrecked…",
|
| 791 |
lines=3,
|
| 792 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 793 |
with gr.Column(scale=2):
|
| 794 |
diet = gr.Dropdown(
|
| 795 |
["Any", "omnivore", "vegetarian", "vegan", "pescatarian", "gluten-free"],
|
|
|
|
| 809 |
label="HRV today (ms) — optional",
|
| 810 |
)
|
| 811 |
|
| 812 |
+
gr.Markdown("### 🥘 Build the meal around your preferences", elem_classes="bb-sec")
|
| 813 |
+
gr.Markdown(
|
| 814 |
+
"Choose ingredients instead of typing them. Required ingredients are checked "
|
| 815 |
+
"before a result is shown, and conflicting choices are blocked automatically."
|
| 816 |
+
)
|
| 817 |
+
with gr.Row():
|
| 818 |
+
main_ingredient = gr.Dropdown(
|
| 819 |
+
MAIN_INGREDIENT_CHOICES,
|
| 820 |
+
value="No preference",
|
| 821 |
+
label="Main ingredient — guaranteed in the personalized recipe",
|
| 822 |
+
)
|
| 823 |
+
include_ingredients = gr.Dropdown(
|
| 824 |
+
EXTRA_INGREDIENT_CHOICES,
|
| 825 |
+
multiselect=True,
|
| 826 |
+
max_choices=3,
|
| 827 |
+
value=[],
|
| 828 |
+
label="Also include — up to 3",
|
| 829 |
+
)
|
| 830 |
+
excluded_ingredients = gr.Dropdown(
|
| 831 |
+
EXCLUDED_INGREDIENT_CHOICES,
|
| 832 |
+
multiselect=True,
|
| 833 |
+
value=[],
|
| 834 |
+
label="Avoid / allergies",
|
| 835 |
+
)
|
| 836 |
+
constraint = gr.Textbox(
|
| 837 |
+
label="Other requirements — optional",
|
| 838 |
+
placeholder="e.g. spicy, one-pan, mild flavors, high-protein",
|
| 839 |
+
lines=1,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
btn = gr.Button("🍽️ Generate My Bio-Bite", variant="primary", size="lg")
|
| 843 |
|
| 844 |
gr.Markdown("### ⚡ Quick starters — one click to try it",
|
| 845 |
elem_classes="bb-sec")
|
| 846 |
gr.Examples(
|
| 847 |
examples=QUICK_STARTERS,
|
| 848 |
+
inputs=[state, main_ingredient, include_ingredients, excluded_ingredients,
|
| 849 |
+
constraint, diet, max_prep, sleep_hours, strain, hrv],
|
| 850 |
label="",
|
| 851 |
)
|
| 852 |
|
|
|
|
| 879 |
|
| 880 |
btn.click(
|
| 881 |
run,
|
| 882 |
+
inputs=[state, main_ingredient, include_ingredients, excluded_ingredients,
|
| 883 |
+
constraint, diet, max_prep, sleep_hours, strain, hrv],
|
| 884 |
outputs=[out_recs, out_recipe, out_plan],
|
| 885 |
)
|
| 886 |
|
biobite_logic.py
CHANGED
|
@@ -63,6 +63,48 @@ ALLOWED_COMPOUNDS = {
|
|
| 63 |
},
|
| 64 |
}
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
GROUNDING_TEXT = {
|
| 67 |
"strength-recovery": (
|
| 68 |
"Protein-containing ingredients support muscle protein synthesis after resistance exercise; "
|
|
@@ -101,6 +143,54 @@ def optional_number(value: Any, minimum: float, maximum: float) -> float | None:
|
|
| 101 |
return number
|
| 102 |
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
def metric_descriptors(sleep: float | None, strain: float | None, hrv: float | None) -> list[str]:
|
| 105 |
"""Convert wearable numbers to the same language used in the synthetic corpus."""
|
| 106 |
descriptors: list[str] = []
|
|
@@ -222,7 +312,9 @@ def _requested_minutes(constraint: str, selected_max: int | None) -> int | None:
|
|
| 222 |
|
| 223 |
|
| 224 |
def validate_generation(payload: dict[str, Any] | None, selected_diet: str | None,
|
| 225 |
-
constraint: str, selected_max: int | None
|
|
|
|
|
|
|
| 226 |
"""Validate structure and the user constraints before rendering model output."""
|
| 227 |
errors: list[str] = []
|
| 228 |
if not isinstance(payload, dict):
|
|
@@ -269,6 +361,14 @@ def validate_generation(payload: dict[str, Any] | None, selected_diet: str | Non
|
|
| 269 |
if re.search(rf"\b{re.escape(forbidden)}\b", ingredients):
|
| 270 |
errors.append(f"explicitly excluded ingredient was used: {forbidden}")
|
| 271 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
return (normalised if not errors else None), errors
|
| 273 |
|
| 274 |
|
|
|
|
| 63 |
},
|
| 64 |
}
|
| 65 |
|
| 66 |
+
# UI labels map to the words a recipe may realistically use. Keeping aliases in
|
| 67 |
+
# one place makes both positive (must include) and negative (must avoid)
|
| 68 |
+
# constraints deterministic instead of relying on the generator's wording.
|
| 69 |
+
INGREDIENT_ALIASES = {
|
| 70 |
+
"Steak / beef": {"steak", "beef", "sirloin"},
|
| 71 |
+
"Chicken": {"chicken"},
|
| 72 |
+
"Salmon": {"salmon"},
|
| 73 |
+
"Tuna": {"tuna"},
|
| 74 |
+
"Eggs": {"egg", "eggs"},
|
| 75 |
+
"Tofu": {"tofu"},
|
| 76 |
+
"Tempeh": {"tempeh"},
|
| 77 |
+
"Lentils": {"lentil", "lentils"},
|
| 78 |
+
"Chickpeas": {"chickpea", "chickpeas", "garbanzo", "garbanzo beans"},
|
| 79 |
+
"Greek yogurt": {"greek yogurt", "greek yoghurt", "yogurt", "yoghurt"},
|
| 80 |
+
"Rice": {"rice"},
|
| 81 |
+
"Quinoa": {"quinoa"},
|
| 82 |
+
"Pasta": {"pasta"},
|
| 83 |
+
"Potatoes": {"potato", "potatoes"},
|
| 84 |
+
"Sweet potato": {"sweet potato", "sweet potatoes"},
|
| 85 |
+
"Oats": {"oat", "oats", "oatmeal"},
|
| 86 |
+
"Spinach": {"spinach"},
|
| 87 |
+
"Broccoli": {"broccoli"},
|
| 88 |
+
"Tomato": {"tomato", "tomatoes"},
|
| 89 |
+
"Avocado": {"avocado", "avocados"},
|
| 90 |
+
"Mushrooms": {"mushroom", "mushrooms"},
|
| 91 |
+
"Bell pepper": {"bell pepper", "bell peppers", "capsicum"},
|
| 92 |
+
"Beans": {"bean", "beans", "black beans", "kidney beans"},
|
| 93 |
+
"Peanuts": {"peanut", "peanuts", "peanut butter"},
|
| 94 |
+
"Tree nuts": {
|
| 95 |
+
"almond", "almonds", "walnut", "walnuts", "cashew", "cashews",
|
| 96 |
+
"pistachio", "pistachios", "pecan", "pecans", "hazelnut", "hazelnuts",
|
| 97 |
+
},
|
| 98 |
+
"Dairy": {"milk", "cheese", "yogurt", "yoghurt", "butter", "cream", "whey"},
|
| 99 |
+
"Gluten": {"wheat", "barley", "rye", "bread", "pasta", "flour", "couscous"},
|
| 100 |
+
"Fish / shellfish": {
|
| 101 |
+
"fish", "salmon", "tuna", "shrimp", "prawn", "prawns", "shellfish", "anchovy",
|
| 102 |
+
},
|
| 103 |
+
"Soy": {"soy", "soya", "tofu", "tempeh", "edamame"},
|
| 104 |
+
"Sesame": {"sesame", "tahini"},
|
| 105 |
+
"Caffeine": {"coffee", "espresso", "caffeine", "energy drink", "matcha"},
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
GROUNDING_TEXT = {
|
| 109 |
"strength-recovery": (
|
| 110 |
"Protein-containing ingredients support muscle protein synthesis after resistance exercise; "
|
|
|
|
| 143 |
return number
|
| 144 |
|
| 145 |
|
| 146 |
+
def ingredient_aliases(label: str) -> set[str]:
|
| 147 |
+
"""Return display-label aliases, falling back to the label itself."""
|
| 148 |
+
cleaned = str(label or "").strip()
|
| 149 |
+
return INGREDIENT_ALIASES.get(cleaned, {cleaned.lower()} if cleaned else set())
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def ingredient_present(text: str, label: str) -> bool:
|
| 153 |
+
"""Match a selected ingredient against a generated recipe with word boundaries."""
|
| 154 |
+
haystack = str(text or "").lower()
|
| 155 |
+
return any(
|
| 156 |
+
re.search(rf"\b{re.escape(alias.lower())}\b", haystack)
|
| 157 |
+
for alias in ingredient_aliases(label)
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def validate_food_preferences(main_ingredient: str | None,
|
| 162 |
+
include_ingredients: list[str] | None,
|
| 163 |
+
excluded_ingredients: list[str] | None,
|
| 164 |
+
diet: str | None) -> tuple[list[str], list[str], list[str]]:
|
| 165 |
+
"""Normalise structured food choices and reject impossible combinations."""
|
| 166 |
+
required: list[str] = []
|
| 167 |
+
if main_ingredient and main_ingredient != "No preference":
|
| 168 |
+
required.append(str(main_ingredient))
|
| 169 |
+
required.extend(str(value) for value in (include_ingredients or []) if value)
|
| 170 |
+
excluded = [str(value) for value in (excluded_ingredients or []) if value]
|
| 171 |
+
required = list(dict.fromkeys(required))
|
| 172 |
+
excluded = list(dict.fromkeys(excluded))
|
| 173 |
+
errors: list[str] = []
|
| 174 |
+
|
| 175 |
+
if len(required) > 4:
|
| 176 |
+
errors.append("Choose no more than four required ingredients in total")
|
| 177 |
+
|
| 178 |
+
for wanted in required:
|
| 179 |
+
wanted_aliases = ingredient_aliases(wanted)
|
| 180 |
+
for blocked in excluded:
|
| 181 |
+
if wanted_aliases & ingredient_aliases(blocked):
|
| 182 |
+
errors.append(f"{wanted} is selected both as required and excluded")
|
| 183 |
+
|
| 184 |
+
selected_diet = str(diet or "Any")
|
| 185 |
+
if selected_diet != "Any":
|
| 186 |
+
banned = DIET_BANNED.get(selected_diet, set())
|
| 187 |
+
for wanted in required:
|
| 188 |
+
if ingredient_aliases(wanted) & banned:
|
| 189 |
+
errors.append(f"{wanted} is incompatible with the {selected_diet} diet")
|
| 190 |
+
|
| 191 |
+
return required, excluded, list(dict.fromkeys(errors))
|
| 192 |
+
|
| 193 |
+
|
| 194 |
def metric_descriptors(sleep: float | None, strain: float | None, hrv: float | None) -> list[str]:
|
| 195 |
"""Convert wearable numbers to the same language used in the synthetic corpus."""
|
| 196 |
descriptors: list[str] = []
|
|
|
|
| 312 |
|
| 313 |
|
| 314 |
def validate_generation(payload: dict[str, Any] | None, selected_diet: str | None,
|
| 315 |
+
constraint: str, selected_max: int | None,
|
| 316 |
+
required_ingredients: list[str] | None = None,
|
| 317 |
+
excluded_ingredients: list[str] | None = None) -> tuple[dict[str, Any] | None, list[str]]:
|
| 318 |
"""Validate structure and the user constraints before rendering model output."""
|
| 319 |
errors: list[str] = []
|
| 320 |
if not isinstance(payload, dict):
|
|
|
|
| 361 |
if re.search(rf"\b{re.escape(forbidden)}\b", ingredients):
|
| 362 |
errors.append(f"explicitly excluded ingredient was used: {forbidden}")
|
| 363 |
|
| 364 |
+
for forbidden in excluded_ingredients or []:
|
| 365 |
+
if ingredient_present(ingredients, forbidden):
|
| 366 |
+
errors.append(f"selected excluded ingredient was used: {forbidden}")
|
| 367 |
+
|
| 368 |
+
for required in required_ingredients or []:
|
| 369 |
+
if not ingredient_present(ingredients, required):
|
| 370 |
+
errors.append(f"required ingredient is missing: {required}")
|
| 371 |
+
|
| 372 |
return (normalised if not errors else None), errors
|
| 373 |
|
| 374 |
|