Compare commits
12 commits
d24f87a476
...
1882116235
| Author | SHA1 | Date | |
|---|---|---|---|
| 1882116235 | |||
| 144d1dc6c4 | |||
| fe18fb48c0 | |||
| 40a12764c4 | |||
| 9a42cdd4ae | |||
| 77ab6fb94a | |||
| 8c4965123f | |||
| c02e538cb2 | |||
| da940ebaec | |||
| 4f1570ee6f | |||
| 1a5fb23dfd | |||
| 65ef65bb4c |
27 changed files with 2732 additions and 90 deletions
|
|
@ -16,6 +16,12 @@ COPY kiwi/environment.yml .
|
|||
RUN conda env create -f environment.yml
|
||||
|
||||
COPY kiwi/ ./kiwi/
|
||||
|
||||
# Remove gitignored config files that may exist locally — defense-in-depth.
|
||||
# The parent .dockerignore should exclude these, but an explicit rm guarantees
|
||||
# they never end up in the cloud image regardless of .dockerignore placement.
|
||||
RUN rm -f /app/kiwi/.env
|
||||
|
||||
# Install cf-core into the kiwi env BEFORE installing kiwi (kiwi lists it as a dep)
|
||||
RUN conda run -n kiwi pip install --no-cache-dir -e /app/circuitforge-core
|
||||
WORKDIR /app/kiwi
|
||||
|
|
|
|||
|
|
@ -120,6 +120,21 @@ async def local_feed():
|
|||
return [_post_to_dict(p) for p in posts]
|
||||
|
||||
|
||||
@router.get("/hall-of-chaos")
|
||||
async def hall_of_chaos():
|
||||
"""Hidden easter egg endpoint -- returns the 10 most chaotic bloopers."""
|
||||
store = _get_community_store()
|
||||
if store is None:
|
||||
return {"posts": [], "chaos_level": 0}
|
||||
posts = await asyncio.to_thread(
|
||||
store.list_posts, limit=10, post_type="recipe_blooper"
|
||||
)
|
||||
return {
|
||||
"posts": [_post_to_dict(p) for p in posts],
|
||||
"chaos_level": len(posts),
|
||||
}
|
||||
|
||||
|
||||
_VALID_POST_TYPES = {"plan", "recipe_success", "recipe_blooper"}
|
||||
_MAX_TITLE_LEN = 200
|
||||
_MAX_TEXT_LEN = 2000
|
||||
|
|
|
|||
185
app/api/endpoints/imitate.py
Normal file
185
app/api/endpoints/imitate.py
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
"""Kiwi — /api/v1/imitate/samples endpoint for Avocet Imitate tab.
|
||||
|
||||
Returns the actual assembled prompt Kiwi sends to its LLM for recipe generation,
|
||||
including the full pantry context (expiry-first ordering), dietary constraints
|
||||
(from user_settings if present), and the Level 3 format instructions.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.cloud_session import get_session, CloudUser
|
||||
from app.db.store import Store
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_LEVEL3_FORMAT = [
|
||||
"",
|
||||
"Reply using EXACTLY this plain-text format — no markdown, no bold, no extra commentary:",
|
||||
"Title: <name of the dish>",
|
||||
"Ingredients: <comma-separated list>",
|
||||
"Directions:",
|
||||
"1. <first step>",
|
||||
"2. <second step>",
|
||||
"3. <continue for each step>",
|
||||
"Notes: <optional tips>",
|
||||
]
|
||||
|
||||
_LEVEL4_FORMAT = [
|
||||
"",
|
||||
"Reply using EXACTLY this plain-text format — no markdown, no bold:",
|
||||
"Title: <name of the dish>",
|
||||
"Ingredients: <comma-separated list>",
|
||||
"Directions:",
|
||||
"1. <first step>",
|
||||
"2. <second step>",
|
||||
"Notes: <optional tips>",
|
||||
]
|
||||
|
||||
|
||||
def _read_user_settings(store: Store) -> dict:
|
||||
"""Read all key/value pairs from user_settings table."""
|
||||
try:
|
||||
rows = store.conn.execute("SELECT key, value FROM user_settings").fetchall()
|
||||
return {r["key"]: r["value"] for r in rows}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _build_recipe_prompt(
|
||||
pantry_names: list[str],
|
||||
expiring_names: list[str],
|
||||
constraints: list[str],
|
||||
allergies: list[str],
|
||||
level: int = 3,
|
||||
) -> str:
|
||||
"""Assemble the recipe generation prompt matching Kiwi's Level 3/4 format."""
|
||||
# Expiring items first, then remaining pantry items (deduped)
|
||||
expiring_set = set(expiring_names)
|
||||
ordered = list(expiring_names) + [n for n in pantry_names if n not in expiring_set]
|
||||
|
||||
if not ordered:
|
||||
ordered = pantry_names
|
||||
|
||||
if level == 4:
|
||||
lines = [
|
||||
"Surprise me with a creative, unexpected recipe.",
|
||||
"Only use ingredients that make culinary sense together. "
|
||||
"Do not force flavoured/sweetened items (vanilla yoghurt, flavoured syrups, jam) into savoury dishes.",
|
||||
f"Ingredients available: {', '.join(ordered)}",
|
||||
]
|
||||
if constraints:
|
||||
lines.append(f"Constraints: {', '.join(constraints)}")
|
||||
if allergies:
|
||||
lines.append(f"Must NOT contain: {', '.join(allergies)}")
|
||||
lines.append("Treat any mystery ingredient as a wildcard — use your imagination.")
|
||||
lines += _LEVEL4_FORMAT
|
||||
else:
|
||||
lines = [
|
||||
"You are a creative chef. Generate a recipe using the ingredients below.",
|
||||
"IMPORTANT: When you use a pantry item, list it in Ingredients using its exact name "
|
||||
"from the pantry list. Do not add adjectives, quantities, or cooking states "
|
||||
"(e.g. use 'butter', not 'unsalted butter' or '2 tbsp butter').",
|
||||
"IMPORTANT: Only use pantry items that make culinary sense for the dish. "
|
||||
"Do NOT force flavoured/sweetened items (vanilla yoghurt, fruit yoghurt, jam, "
|
||||
"dessert sauces, flavoured syrups) into savoury dishes.",
|
||||
"IMPORTANT: Do not default to the same ingredient repeatedly across dishes. "
|
||||
"If a pantry item does not genuinely improve this specific dish, leave it out.",
|
||||
"",
|
||||
f"Pantry items: {', '.join(ordered)}",
|
||||
]
|
||||
if expiring_names:
|
||||
lines.append(
|
||||
f"Priority — use these soon (expiring): {', '.join(expiring_names)}"
|
||||
)
|
||||
if constraints:
|
||||
lines.append(f"Dietary constraints: {', '.join(constraints)}")
|
||||
if allergies:
|
||||
lines.append(f"IMPORTANT — must NOT contain: {', '.join(allergies)}")
|
||||
lines += _LEVEL3_FORMAT
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@router.get("/samples")
|
||||
async def imitate_samples(
|
||||
limit: int = 5,
|
||||
level: int = 3,
|
||||
session: CloudUser = Depends(get_session),
|
||||
):
|
||||
"""Return assembled recipe generation prompts for Avocet's Imitate tab.
|
||||
|
||||
Each sample includes:
|
||||
system_prompt empty (Kiwi uses no system context)
|
||||
input_text full Level 3/4 prompt with pantry items, expiring items,
|
||||
dietary constraints, and format instructions
|
||||
output_text empty (no prior LLM output stored per-request)
|
||||
|
||||
level: 3 (structured with element biasing context) or 4 (wildcard creative)
|
||||
limit: max number of distinct prompt variants to return (varies by pantry state)
|
||||
"""
|
||||
limit = max(1, min(limit, 10))
|
||||
store = Store(session.db)
|
||||
|
||||
# Full pantry for context
|
||||
all_items = store.list_inventory()
|
||||
pantry_names = [r["product_name"] for r in all_items if r.get("product_name")]
|
||||
|
||||
# Expiring items as priority ingredients
|
||||
expiring = store.expiring_soon(days=14)
|
||||
expiring_names = [r["product_name"] for r in expiring if r.get("product_name")]
|
||||
|
||||
# Dietary constraints from user_settings (keys: constraints, allergies)
|
||||
settings = _read_user_settings(store)
|
||||
import json as _json
|
||||
try:
|
||||
constraints = _json.loads(settings.get("dietary_constraints", "[]")) or []
|
||||
except Exception:
|
||||
constraints = []
|
||||
try:
|
||||
allergies = _json.loads(settings.get("dietary_allergies", "[]")) or []
|
||||
except Exception:
|
||||
allergies = []
|
||||
|
||||
if not pantry_names:
|
||||
return {"samples": [], "total": 0, "type": f"recipe_level{level}"}
|
||||
|
||||
# Build prompt variants: one per expiring item as the "anchor" ingredient,
|
||||
# plus one general pantry prompt. Cap at limit.
|
||||
samples = []
|
||||
seen_anchors: set[str] = set()
|
||||
|
||||
for item in (expiring[:limit - 1] if expiring else []):
|
||||
anchor = item.get("product_name", "")
|
||||
if not anchor or anchor in seen_anchors:
|
||||
continue
|
||||
seen_anchors.add(anchor)
|
||||
|
||||
# Put this item first in the list for the prompt
|
||||
ordered_expiring = [anchor] + [n for n in expiring_names if n != anchor]
|
||||
prompt = _build_recipe_prompt(pantry_names, ordered_expiring, constraints, allergies, level)
|
||||
|
||||
samples.append({
|
||||
"id": item.get("id", 0),
|
||||
"anchor_item": anchor,
|
||||
"expiring_count": len(expiring_names),
|
||||
"pantry_count": len(pantry_names),
|
||||
"system_prompt": "",
|
||||
"input_text": prompt,
|
||||
"output_text": "",
|
||||
})
|
||||
|
||||
# One general prompt using all expiring as priority
|
||||
if len(samples) < limit:
|
||||
prompt = _build_recipe_prompt(pantry_names, expiring_names, constraints, allergies, level)
|
||||
samples.append({
|
||||
"id": 0,
|
||||
"anchor_item": "full pantry",
|
||||
"expiring_count": len(expiring_names),
|
||||
"pantry_count": len(pantry_names),
|
||||
"system_prompt": "",
|
||||
"input_text": prompt,
|
||||
"output_text": "",
|
||||
})
|
||||
|
||||
return {"samples": samples, "total": len(samples), "type": f"recipe_level{level}"}
|
||||
|
|
@ -9,7 +9,19 @@ from fastapi import APIRouter, Depends, HTTPException, Query
|
|||
|
||||
from app.cloud_session import CloudUser, get_session
|
||||
from app.db.store import Store
|
||||
from app.models.schemas.recipe import RecipeRequest, RecipeResult
|
||||
from app.models.schemas.recipe import (
|
||||
AssemblyTemplateOut,
|
||||
BuildRequest,
|
||||
RecipeRequest,
|
||||
RecipeResult,
|
||||
RecipeSuggestion,
|
||||
RoleCandidatesResponse,
|
||||
)
|
||||
from app.services.recipe.assembly_recipes import (
|
||||
build_from_selection,
|
||||
get_role_candidates,
|
||||
get_templates_for_api,
|
||||
)
|
||||
from app.services.recipe.browser_domains import (
|
||||
DOMAINS,
|
||||
get_category_names,
|
||||
|
|
@ -143,6 +155,80 @@ async def browse_recipes(
|
|||
return await asyncio.to_thread(_browse, session.db)
|
||||
|
||||
|
||||
@router.get("/templates", response_model=list[AssemblyTemplateOut])
|
||||
async def list_assembly_templates() -> list[dict]:
|
||||
"""Return all 13 assembly templates with ordered role sequences.
|
||||
|
||||
Cache-friendly: static data, no per-user state.
|
||||
"""
|
||||
return get_templates_for_api()
|
||||
|
||||
|
||||
@router.get("/template-candidates", response_model=RoleCandidatesResponse)
|
||||
async def get_template_role_candidates(
|
||||
template_id: str = Query(..., description="Template slug, e.g. 'burrito_taco'"),
|
||||
role: str = Query(..., description="Role display name, e.g. 'protein'"),
|
||||
prior_picks: str = Query(default="", description="Comma-separated prior selections"),
|
||||
session: CloudUser = Depends(get_session),
|
||||
) -> dict:
|
||||
"""Return pantry-matched candidates for one wizard step."""
|
||||
def _get(db_path: Path) -> dict:
|
||||
store = Store(db_path)
|
||||
try:
|
||||
items = store.list_inventory(status="available")
|
||||
pantry_set = {
|
||||
item["product_name"]
|
||||
for item in items
|
||||
if item.get("product_name")
|
||||
}
|
||||
pantry_list = list(pantry_set)
|
||||
prior = [p.strip() for p in prior_picks.split(",") if p.strip()]
|
||||
profile_index = store.get_element_profiles(pantry_list + prior)
|
||||
return get_role_candidates(
|
||||
template_slug=template_id,
|
||||
role_display=role,
|
||||
pantry_set=pantry_set,
|
||||
prior_picks=prior,
|
||||
profile_index=profile_index,
|
||||
)
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
return await asyncio.to_thread(_get, session.db)
|
||||
|
||||
|
||||
@router.post("/build", response_model=RecipeSuggestion)
|
||||
async def build_recipe(
|
||||
req: BuildRequest,
|
||||
session: CloudUser = Depends(get_session),
|
||||
) -> RecipeSuggestion:
|
||||
"""Build a recipe from explicit role selections."""
|
||||
def _build(db_path: Path) -> RecipeSuggestion | None:
|
||||
store = Store(db_path)
|
||||
try:
|
||||
items = store.list_inventory(status="available")
|
||||
pantry_set = {
|
||||
item["product_name"]
|
||||
for item in items
|
||||
if item.get("product_name")
|
||||
}
|
||||
return build_from_selection(
|
||||
template_slug=req.template_id,
|
||||
role_overrides=req.role_overrides,
|
||||
pantry_set=pantry_set,
|
||||
)
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
result = await asyncio.to_thread(_build, session.db)
|
||||
if result is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Template not found or required ingredient missing.",
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/{recipe_id}")
|
||||
async def get_recipe(recipe_id: int, session: CloudUser = Depends(get_session)) -> dict:
|
||||
def _get(db_path: Path, rid: int) -> dict | None:
|
||||
|
|
|
|||
|
|
@ -170,6 +170,13 @@ def _user_db_path(user_id: str, household_id: str | None = None) -> Path:
|
|||
return path
|
||||
|
||||
|
||||
def _anon_db_path() -> Path:
|
||||
"""Ephemeral DB for unauthenticated guest visitors (Free tier, no persistence)."""
|
||||
path = CLOUD_DATA_ROOT / "anonymous" / "kiwi.db"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
# ── BYOK detection ────────────────────────────────────────────────────────────
|
||||
|
||||
_LLM_CONFIG_PATH = Path.home() / ".config" / "circuitforge" / "llm.yaml"
|
||||
|
|
@ -225,11 +232,21 @@ def get_session(request: Request) -> CloudUser:
|
|||
or request.headers.get("cookie", "")
|
||||
)
|
||||
if not raw_header:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
return CloudUser(
|
||||
user_id="anonymous",
|
||||
tier="free",
|
||||
db=_anon_db_path(),
|
||||
has_byok=has_byok,
|
||||
)
|
||||
|
||||
token = _extract_session_token(raw_header) # gitleaks:allow — function name, not a secret
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
return CloudUser(
|
||||
user_id="anonymous",
|
||||
tier="free",
|
||||
db=_anon_db_path(),
|
||||
has_byok=has_byok,
|
||||
)
|
||||
|
||||
user_id = validate_session_jwt(token)
|
||||
_ensure_provisioned(user_id)
|
||||
|
|
|
|||
5
app/db/migrations/022_recipe_generic_flag.sql
Normal file
5
app/db/migrations/022_recipe_generic_flag.sql
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
-- Migration 022: Add is_generic flag to recipes
|
||||
-- Generic recipes are catch-all/dump recipes with loose ingredient lists
|
||||
-- that should not appear in Level 1 (deterministic "use what I have") results.
|
||||
-- Admins can mark recipes via the recipe editor or a bulk backfill script.
|
||||
ALTER TABLE recipes ADD COLUMN is_generic INTEGER NOT NULL DEFAULT 0;
|
||||
49
app/db/migrations/029_inferred_tags.sql
Normal file
49
app/db/migrations/029_inferred_tags.sql
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
-- Migration 029: Add inferred_tags column and update FTS index to include it.
|
||||
--
|
||||
-- inferred_tags holds a JSON array of normalized tag strings derived by
|
||||
-- scripts/pipeline/infer_recipe_tags.py (e.g. ["cuisine:Italian",
|
||||
-- "dietary:Low-Carb", "flavor:Umami", "can_be:Gluten-Free"]).
|
||||
--
|
||||
-- The FTS5 browser table is rebuilt to index inferred_tags alongside
|
||||
-- category and keywords so browse domain queries match against all signals.
|
||||
|
||||
-- 1. Add inferred_tags column (empty array default; populated by pipeline run)
|
||||
ALTER TABLE recipes ADD COLUMN inferred_tags TEXT NOT NULL DEFAULT '[]';
|
||||
|
||||
-- 2. Drop old FTS table and triggers that only covered category + keywords
|
||||
DROP TRIGGER IF EXISTS recipes_ai;
|
||||
DROP TRIGGER IF EXISTS recipes_ad;
|
||||
DROP TRIGGER IF EXISTS recipes_au;
|
||||
DROP TABLE IF EXISTS recipe_browser_fts;
|
||||
|
||||
-- 3. Recreate FTS5 table: now indexes category, keywords, AND inferred_tags
|
||||
CREATE VIRTUAL TABLE recipe_browser_fts USING fts5(
|
||||
category,
|
||||
keywords,
|
||||
inferred_tags,
|
||||
content=recipes,
|
||||
content_rowid=id
|
||||
);
|
||||
|
||||
-- 4. Triggers to keep FTS in sync with recipes table changes
|
||||
CREATE TRIGGER recipes_ai AFTER INSERT ON recipes BEGIN
|
||||
INSERT INTO recipe_browser_fts(rowid, category, keywords, inferred_tags)
|
||||
VALUES (new.id, new.category, new.keywords, new.inferred_tags);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER recipes_ad AFTER DELETE ON recipes BEGIN
|
||||
INSERT INTO recipe_browser_fts(recipe_browser_fts, rowid, category, keywords, inferred_tags)
|
||||
VALUES ('delete', old.id, old.category, old.keywords, old.inferred_tags);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER recipes_au AFTER UPDATE ON recipes BEGIN
|
||||
INSERT INTO recipe_browser_fts(recipe_browser_fts, rowid, category, keywords, inferred_tags)
|
||||
VALUES ('delete', old.id, old.category, old.keywords, old.inferred_tags);
|
||||
INSERT INTO recipe_browser_fts(rowid, category, keywords, inferred_tags)
|
||||
VALUES (new.id, new.category, new.keywords, new.inferred_tags);
|
||||
END;
|
||||
|
||||
-- 5. Populate FTS from current table state
|
||||
-- (inferred_tags is '[]' for all rows at this point; run infer_recipe_tags.py
|
||||
-- to populate, then the FTS will be rebuilt as part of that script.)
|
||||
INSERT INTO recipe_browser_fts(recipe_browser_fts) VALUES('rebuild');
|
||||
|
|
@ -571,6 +571,7 @@ class Store:
|
|||
max_carbs_g: float | None = None,
|
||||
max_sodium_mg: float | None = None,
|
||||
excluded_ids: list[int] | None = None,
|
||||
exclude_generic: bool = False,
|
||||
) -> list[dict]:
|
||||
"""Find recipes containing any of the given ingredient names.
|
||||
Scores by match count and returns highest-scoring first.
|
||||
|
|
@ -580,6 +581,9 @@ class Store:
|
|||
|
||||
Nutrition filters use NULL-passthrough: rows without nutrition data
|
||||
always pass (they may be estimated or absent entirely).
|
||||
|
||||
exclude_generic: when True, skips recipes marked is_generic=1.
|
||||
Pass True for Level 1 ("Use What I Have") to suppress catch-all recipes.
|
||||
"""
|
||||
if not ingredient_names:
|
||||
return []
|
||||
|
|
@ -605,6 +609,8 @@ class Store:
|
|||
placeholders = ",".join("?" * len(excluded_ids))
|
||||
extra_clauses.append(f"r.id NOT IN ({placeholders})")
|
||||
extra_params.extend(excluded_ids)
|
||||
if exclude_generic:
|
||||
extra_clauses.append("r.is_generic = 0")
|
||||
where_extra = (" AND " + " AND ".join(extra_clauses)) if extra_clauses else ""
|
||||
|
||||
if self._fts_ready():
|
||||
|
|
@ -680,6 +686,29 @@ class Store:
|
|||
def get_recipe(self, recipe_id: int) -> dict | None:
|
||||
return self._fetch_one("SELECT * FROM recipes WHERE id = ?", (recipe_id,))
|
||||
|
||||
def get_element_profiles(self, names: list[str]) -> dict[str, list[str]]:
|
||||
"""Return {ingredient_name: [element_tag, ...]} for the given names.
|
||||
|
||||
Only names present in ingredient_profiles are returned -- missing names
|
||||
are silently omitted so callers can distinguish "no profile" from "empty
|
||||
elements list".
|
||||
"""
|
||||
if not names:
|
||||
return {}
|
||||
placeholders = ",".join("?" * len(names))
|
||||
rows = self._fetch_all(
|
||||
f"SELECT name, elements FROM ingredient_profiles WHERE name IN ({placeholders})",
|
||||
tuple(names),
|
||||
)
|
||||
result: dict[str, list[str]] = {}
|
||||
for row in rows:
|
||||
try:
|
||||
elements = json.loads(row["elements"]) if row["elements"] else []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
elements = []
|
||||
result[row["name"]] = elements
|
||||
return result
|
||||
|
||||
# ── rate limits ───────────────────────────────────────────────────────
|
||||
|
||||
def check_and_increment_rate_limit(
|
||||
|
|
|
|||
|
|
@ -82,3 +82,48 @@ class RecipeRequest(BaseModel):
|
|||
nutrition_filters: NutritionFilters = Field(default_factory=NutritionFilters)
|
||||
excluded_ids: list[int] = Field(default_factory=list)
|
||||
shopping_mode: bool = False
|
||||
|
||||
|
||||
# ── Build Your Own schemas ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
class AssemblyRoleOut(BaseModel):
|
||||
"""One role slot in a template, as returned by GET /api/recipes/templates."""
|
||||
|
||||
display: str
|
||||
required: bool
|
||||
keywords: list[str]
|
||||
hint: str = ""
|
||||
|
||||
|
||||
class AssemblyTemplateOut(BaseModel):
|
||||
"""One assembly template, as returned by GET /api/recipes/templates."""
|
||||
|
||||
id: str # slug, e.g. "burrito_taco"
|
||||
title: str
|
||||
icon: str
|
||||
descriptor: str
|
||||
role_sequence: list[AssemblyRoleOut]
|
||||
|
||||
|
||||
class RoleCandidateItem(BaseModel):
|
||||
"""One candidate ingredient for a wizard picker step."""
|
||||
|
||||
name: str
|
||||
in_pantry: bool
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class RoleCandidatesResponse(BaseModel):
|
||||
"""Response from GET /api/recipes/template-candidates."""
|
||||
|
||||
compatible: list[RoleCandidateItem] = Field(default_factory=list)
|
||||
other: list[RoleCandidateItem] = Field(default_factory=list)
|
||||
available_tags: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class BuildRequest(BaseModel):
|
||||
"""Request body for POST /api/recipes/build."""
|
||||
|
||||
template_id: str
|
||||
role_overrides: dict[str, str] = Field(default_factory=dict)
|
||||
|
|
|
|||
|
|
@ -42,11 +42,21 @@ class AssemblyRole:
|
|||
class AssemblyTemplate:
|
||||
"""A template assembly dish."""
|
||||
id: int
|
||||
slug: str # URL-safe identifier, e.g. "burrito_taco"
|
||||
icon: str # emoji
|
||||
descriptor: str # one-line description shown in template grid
|
||||
title: str
|
||||
required: list[AssemblyRole]
|
||||
optional: list[AssemblyRole]
|
||||
directions: list[str]
|
||||
notes: str = ""
|
||||
# Per-role hints shown in the wizard picker header
|
||||
# keys match role.display values; missing keys fall back to ""
|
||||
role_hints: dict[str, str] = None # type: ignore[assignment]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.role_hints is None:
|
||||
self.role_hints = {}
|
||||
|
||||
|
||||
def _matches_role(role: AssemblyRole, pantry_set: set[str]) -> list[str]:
|
||||
|
|
@ -138,6 +148,9 @@ def _personalized_title(tmpl: AssemblyTemplate, pantry_set: set[str], seed: int)
|
|||
ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
||||
AssemblyTemplate(
|
||||
id=-1,
|
||||
slug="burrito_taco",
|
||||
icon="🌯",
|
||||
descriptor="Protein, veg, and sauce in a tortilla or over rice",
|
||||
title="Burrito / Taco",
|
||||
required=[
|
||||
AssemblyRole("tortilla or wrap", [
|
||||
|
|
@ -170,9 +183,21 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Fold in the sides and roll tightly. Optionally toast seam-side down 1-2 minutes.",
|
||||
],
|
||||
notes="Works as a burrito (rolled), taco (folded), or quesadilla (cheese only, pressed flat).",
|
||||
role_hints={
|
||||
"tortilla or wrap": "The foundation -- what holds everything",
|
||||
"protein": "The main filling",
|
||||
"rice or starch": "Optional base layer",
|
||||
"cheese": "Optional -- melts into the filling",
|
||||
"salsa or sauce": "Optional -- adds moisture and heat",
|
||||
"sour cream or yogurt": "Optional -- cool contrast to heat",
|
||||
"vegetables": "Optional -- adds texture and colour",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-2,
|
||||
slug="fried_rice",
|
||||
icon="🍳",
|
||||
descriptor="Rice + egg + whatever's in the fridge",
|
||||
title="Fried Rice",
|
||||
required=[
|
||||
AssemblyRole("cooked rice", [
|
||||
|
|
@ -205,9 +230,21 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Season with soy sauce and any other sauces. Toss to combine.",
|
||||
],
|
||||
notes="Add a fried egg on top. A drizzle of sesame oil at the end adds a lot.",
|
||||
role_hints={
|
||||
"cooked rice": "Day-old cold rice works best",
|
||||
"protein": "Pre-cooked or raw -- cook before adding rice",
|
||||
"soy sauce or seasoning": "The primary flavour driver",
|
||||
"oil": "High smoke-point oil for high heat",
|
||||
"egg": "Scrambled in the same pan",
|
||||
"vegetables": "Add crunch and colour",
|
||||
"garlic or ginger": "Aromatic base -- add first",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-3,
|
||||
slug="omelette_scramble",
|
||||
icon="🥚",
|
||||
descriptor="Eggs with fillings, pan-cooked",
|
||||
title="Omelette / Scramble",
|
||||
required=[
|
||||
AssemblyRole("eggs", ["egg"]),
|
||||
|
|
@ -238,9 +275,19 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Season and serve immediately.",
|
||||
],
|
||||
notes="Works for breakfast, lunch, or a quick dinner. Any leftover vegetables work well.",
|
||||
role_hints={
|
||||
"eggs": "The base -- beat with a splash of water",
|
||||
"cheese": "Fold in just before serving",
|
||||
"vegetables": "Saute first, then add eggs",
|
||||
"protein": "Cook through before adding eggs",
|
||||
"herbs or seasoning": "Season at the end",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-4,
|
||||
slug="stir_fry",
|
||||
icon="🥢",
|
||||
descriptor="High-heat protein + veg in sauce",
|
||||
title="Stir Fry",
|
||||
required=[
|
||||
AssemblyRole("vegetables", [
|
||||
|
|
@ -271,9 +318,20 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Serve over rice or noodles.",
|
||||
],
|
||||
notes="High heat is the key. Do not crowd the pan -- cook in batches if needed.",
|
||||
role_hints={
|
||||
"vegetables": "Cut to similar size for even cooking",
|
||||
"starch base": "Serve under or toss with the stir fry",
|
||||
"protein": "Cook first, remove, add back at end",
|
||||
"sauce": "Add last -- toss for 1-2 minutes only",
|
||||
"garlic or ginger": "Add early for aromatic base",
|
||||
"oil": "High smoke-point oil only",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-5,
|
||||
slug="pasta",
|
||||
icon="🍝",
|
||||
descriptor="Pantry pasta with flexible sauce",
|
||||
title="Pasta with Whatever You Have",
|
||||
required=[
|
||||
AssemblyRole("pasta", [
|
||||
|
|
@ -307,9 +365,20 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Toss cooked pasta with sauce. Finish with cheese if using.",
|
||||
],
|
||||
notes="Pasta water is the secret -- the starch thickens and binds any sauce.",
|
||||
role_hints={
|
||||
"pasta": "The base -- cook al dente, reserve pasta water",
|
||||
"sauce base": "Simmer 5 min; pasta water loosens it",
|
||||
"protein": "Cook through before adding sauce",
|
||||
"cheese": "Finish off heat to avoid graininess",
|
||||
"vegetables": "Saute until tender before adding sauce",
|
||||
"garlic": "Saute in oil first -- the flavour foundation",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-6,
|
||||
slug="sandwich_wrap",
|
||||
icon="🥪",
|
||||
descriptor="Protein + veg between bread or in a wrap",
|
||||
title="Sandwich / Wrap",
|
||||
required=[
|
||||
AssemblyRole("bread or wrap", [
|
||||
|
|
@ -341,9 +410,19 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Press together and cut diagonally.",
|
||||
],
|
||||
notes="Leftovers, deli meat, canned fish -- nearly anything works between bread.",
|
||||
role_hints={
|
||||
"bread or wrap": "Toast for better texture",
|
||||
"protein": "Layer on first after condiments",
|
||||
"cheese": "Goes on top of protein",
|
||||
"condiment": "Spread on both inner surfaces",
|
||||
"vegetables": "Top layer -- keeps bread from getting soggy",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-7,
|
||||
slug="grain_bowl",
|
||||
icon="🥗",
|
||||
descriptor="Grain base + protein + toppings + dressing",
|
||||
title="Grain Bowl",
|
||||
required=[
|
||||
AssemblyRole("grain base", [
|
||||
|
|
@ -377,9 +456,19 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Drizzle with dressing and add toppings.",
|
||||
],
|
||||
notes="Great for meal prep -- cook grains and proteins in bulk, assemble bowls all week.",
|
||||
role_hints={
|
||||
"grain base": "Season while cooking -- bland grains sink the bowl",
|
||||
"protein": "Slice or shred; arrange on top",
|
||||
"vegetables": "Roast or saute for best flavour",
|
||||
"dressing or sauce": "Drizzle last -- ties everything together",
|
||||
"toppings": "Add crunch and contrast",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-8,
|
||||
slug="soup_stew",
|
||||
icon="🥣",
|
||||
descriptor="Liquid-based, flexible ingredients",
|
||||
title="Soup / Stew",
|
||||
required=[
|
||||
# Narrow to dedicated soup bases — tomato sauce and coconut milk are
|
||||
|
|
@ -415,9 +504,19 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Season to taste and simmer at least 20 minutes for flavors to develop.",
|
||||
],
|
||||
notes="Soups and stews improve overnight in the fridge. Almost any combination works.",
|
||||
role_hints={
|
||||
"broth or stock": "The liquid base -- determines overall flavour",
|
||||
"protein": "Brown first for deeper flavour",
|
||||
"vegetables": "Dense veg first; quick-cooking veg last",
|
||||
"starch thickener": "Adds body and turns soup into stew",
|
||||
"seasoning": "Taste and adjust after 20 min simmer",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-9,
|
||||
slug="casserole_bake",
|
||||
icon="🫙",
|
||||
descriptor="Oven bake with protein, veg, starch",
|
||||
title="Casserole / Bake",
|
||||
required=[
|
||||
AssemblyRole("starch or base", [
|
||||
|
|
@ -457,9 +556,20 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Bake covered 25 minutes, then uncovered 15 minutes until golden and bubbly.",
|
||||
],
|
||||
notes="Classic pantry dump dinner. Cream of anything soup is the universal binder.",
|
||||
role_hints={
|
||||
"starch or base": "Cook slightly underdone -- finishes in oven",
|
||||
"binder or sauce": "Coats everything and holds the bake together",
|
||||
"protein": "Pre-cook before mixing in",
|
||||
"vegetables": "Chop small for even distribution",
|
||||
"cheese topping": "Goes on last -- browns in the final 15 min",
|
||||
"seasoning": "Casseroles need more salt than you think",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-10,
|
||||
slug="pancakes_quickbread",
|
||||
icon="🥞",
|
||||
descriptor="Batter-based; sweet or savory",
|
||||
title="Pancakes / Waffles / Quick Bread",
|
||||
required=[
|
||||
AssemblyRole("flour or baking mix", [
|
||||
|
|
@ -495,9 +605,20 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"For muffins or quick bread: pour into greased pan, bake at 375 F until a toothpick comes out clean.",
|
||||
],
|
||||
notes="Overmixing develops gluten and makes pancakes tough. Stop when just combined.",
|
||||
role_hints={
|
||||
"flour or baking mix": "Whisk dry ingredients together first",
|
||||
"leavening or egg": "Activates rise -- don't skip",
|
||||
"liquid": "Add to dry ingredients; lumps are fine",
|
||||
"fat": "Adds richness and prevents sticking",
|
||||
"sweetener": "Mix into wet ingredients",
|
||||
"mix-ins": "Fold in last -- gently",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-11,
|
||||
slug="porridge_oatmeal",
|
||||
icon="🌾",
|
||||
descriptor="Oat or grain base with toppings",
|
||||
title="Porridge / Oatmeal",
|
||||
required=[
|
||||
AssemblyRole("oats or grain porridge", [
|
||||
|
|
@ -520,9 +641,20 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Top with fruit, nuts, or seeds and serve immediately.",
|
||||
],
|
||||
notes="Overnight oats: skip cooking — soak oats in cold milk overnight in the fridge.",
|
||||
role_hints={
|
||||
"oats or grain porridge": "1 part oats to 2 parts liquid",
|
||||
"liquid": "Use milk for creamier result",
|
||||
"sweetener": "Stir in after cooking",
|
||||
"fruit": "Add fresh on top or simmer dried fruit in",
|
||||
"toppings": "Add last for crunch",
|
||||
"spice": "Stir in with sweetener",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-12,
|
||||
slug="pie_pot_pie",
|
||||
icon="🥧",
|
||||
descriptor="Pastry or biscuit crust with filling",
|
||||
title="Pie / Pot Pie",
|
||||
required=[
|
||||
AssemblyRole("pastry or crust", [
|
||||
|
|
@ -561,9 +693,20 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"For sweet pie: fill unbaked crust with fruit filling, top with second crust or crumble, bake similarly.",
|
||||
],
|
||||
notes="Puff pastry from the freezer is the shortcut to impressive pot pies. Thaw in the fridge overnight.",
|
||||
role_hints={
|
||||
"pastry or crust": "Thaw puff pastry overnight in fridge",
|
||||
"protein filling": "Cook through before adding to filling",
|
||||
"vegetables": "Chop small; cook until just tender",
|
||||
"sauce or binder": "Holds the filling together in the crust",
|
||||
"seasoning": "Fillings need generous seasoning",
|
||||
"sweet filling": "For dessert pies -- fruit + sugar",
|
||||
},
|
||||
),
|
||||
AssemblyTemplate(
|
||||
id=-13,
|
||||
slug="pudding_custard",
|
||||
icon="🍮",
|
||||
descriptor="Dairy-based set dessert",
|
||||
title="Pudding / Custard",
|
||||
required=[
|
||||
AssemblyRole("dairy or dairy-free milk", [
|
||||
|
|
@ -601,10 +744,58 @@ ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [
|
|||
"Pour into dishes and refrigerate at least 2 hours to set.",
|
||||
],
|
||||
notes="UK-style pudding is broad — bread pudding, rice pudding, spotted dick, treacle sponge all count.",
|
||||
role_hints={
|
||||
"dairy or dairy-free milk": "Heat until steaming before adding to eggs",
|
||||
"thickener or set": "Cornstarch for stovetop; eggs for baked custard",
|
||||
"sweetener or flavouring": "Signals dessert intent -- required",
|
||||
"sweetener": "Adjust to taste",
|
||||
"flavouring": "Add off-heat to preserve aroma",
|
||||
"starchy base": "For bread pudding or rice pudding",
|
||||
"fruit": "Layer in or fold through before setting",
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# Slug to template lookup (built once at import time)
|
||||
_TEMPLATE_BY_SLUG: dict[str, AssemblyTemplate] = {
|
||||
t.slug: t for t in ASSEMBLY_TEMPLATES
|
||||
}
|
||||
|
||||
|
||||
def get_templates_for_api() -> list[dict]:
|
||||
"""Serialise all 13 templates for GET /api/recipes/templates.
|
||||
|
||||
Combines required and optional roles into a single ordered role_sequence
|
||||
with required roles first.
|
||||
"""
|
||||
out = []
|
||||
for tmpl in ASSEMBLY_TEMPLATES:
|
||||
roles = []
|
||||
for role in tmpl.required:
|
||||
roles.append({
|
||||
"display": role.display,
|
||||
"required": True,
|
||||
"keywords": role.keywords,
|
||||
"hint": tmpl.role_hints.get(role.display, ""),
|
||||
})
|
||||
for role in tmpl.optional:
|
||||
roles.append({
|
||||
"display": role.display,
|
||||
"required": False,
|
||||
"keywords": role.keywords,
|
||||
"hint": tmpl.role_hints.get(role.display, ""),
|
||||
})
|
||||
out.append({
|
||||
"id": tmpl.slug,
|
||||
"title": tmpl.title,
|
||||
"icon": tmpl.icon,
|
||||
"descriptor": tmpl.descriptor,
|
||||
"role_sequence": roles,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
|
@ -679,3 +870,142 @@ def match_assembly_templates(
|
|||
# Sort by optional coverage descending — best-matched templates first
|
||||
results.sort(key=lambda s: s.match_count, reverse=True)
|
||||
return results
|
||||
|
||||
|
||||
def get_role_candidates(
|
||||
template_slug: str,
|
||||
role_display: str,
|
||||
pantry_set: set[str],
|
||||
prior_picks: list[str],
|
||||
profile_index: dict[str, list[str]],
|
||||
) -> dict:
|
||||
"""Return ingredient candidates for one wizard step.
|
||||
|
||||
Splits candidates into 'compatible' (element overlap with prior picks)
|
||||
and 'other' (valid for role but no overlap).
|
||||
|
||||
profile_index: {ingredient_name: [element_tag, ...]} -- pre-loaded from
|
||||
Store.get_element_profiles() by the caller so this function stays DB-free.
|
||||
|
||||
Returns {"compatible": [...], "other": [...], "available_tags": [...]}
|
||||
where each item is {"name": str, "in_pantry": bool, "tags": [str]}.
|
||||
"""
|
||||
tmpl = _TEMPLATE_BY_SLUG.get(template_slug)
|
||||
if tmpl is None:
|
||||
return {"compatible": [], "other": [], "available_tags": []}
|
||||
|
||||
# Find the AssemblyRole for this display name
|
||||
target_role: AssemblyRole | None = None
|
||||
for role in tmpl.required + tmpl.optional:
|
||||
if role.display == role_display:
|
||||
target_role = role
|
||||
break
|
||||
if target_role is None:
|
||||
return {"compatible": [], "other": [], "available_tags": []}
|
||||
|
||||
# Build prior-pick element set for compatibility scoring
|
||||
prior_elements: set[str] = set()
|
||||
for pick in prior_picks:
|
||||
prior_elements.update(profile_index.get(pick, []))
|
||||
|
||||
# Find pantry items that match this role
|
||||
pantry_matches = _matches_role(target_role, pantry_set)
|
||||
|
||||
# Build keyword-based "other" candidates from role keywords not in pantry
|
||||
pantry_lower = {p.lower() for p in pantry_set}
|
||||
other_names: list[str] = []
|
||||
for kw in target_role.keywords:
|
||||
if not any(kw in item.lower() for item in pantry_lower):
|
||||
if len(kw) >= 4:
|
||||
other_names.append(kw.title())
|
||||
|
||||
def _make_item(name: str, in_pantry: bool) -> dict:
|
||||
tags = profile_index.get(name, profile_index.get(name.lower(), []))
|
||||
return {"name": name, "in_pantry": in_pantry, "tags": tags}
|
||||
|
||||
# Score: compatible if shares any element with prior picks (or no prior picks yet)
|
||||
compatible: list[dict] = []
|
||||
other: list[dict] = []
|
||||
for name in pantry_matches:
|
||||
item_elements = set(profile_index.get(name, []))
|
||||
item = _make_item(name, in_pantry=True)
|
||||
if not prior_elements or item_elements & prior_elements:
|
||||
compatible.append(item)
|
||||
else:
|
||||
other.append(item)
|
||||
|
||||
for name in other_names:
|
||||
other.append(_make_item(name, in_pantry=False))
|
||||
|
||||
# available_tags: union of all tags in the full candidate set
|
||||
all_tags: set[str] = set()
|
||||
for item in compatible + other:
|
||||
all_tags.update(item["tags"])
|
||||
|
||||
return {
|
||||
"compatible": compatible,
|
||||
"other": other,
|
||||
"available_tags": sorted(all_tags),
|
||||
}
|
||||
|
||||
|
||||
def build_from_selection(
|
||||
template_slug: str,
|
||||
role_overrides: dict[str, str],
|
||||
pantry_set: set[str],
|
||||
) -> "RecipeSuggestion | None":
|
||||
"""Build a RecipeSuggestion from explicit role selections.
|
||||
|
||||
role_overrides: {role.display -> chosen pantry item name}
|
||||
|
||||
Returns None if template not found or any required role is uncovered.
|
||||
"""
|
||||
tmpl = _TEMPLATE_BY_SLUG.get(template_slug)
|
||||
if tmpl is None:
|
||||
return None
|
||||
|
||||
seed = _pantry_hash(pantry_set)
|
||||
|
||||
# Validate required roles: covered by override OR pantry match
|
||||
matched_required: list[str] = []
|
||||
for role in tmpl.required:
|
||||
chosen = role_overrides.get(role.display)
|
||||
if chosen:
|
||||
matched_required.append(chosen)
|
||||
else:
|
||||
hits = _matches_role(role, pantry_set)
|
||||
if not hits:
|
||||
return None
|
||||
matched_required.append(_pick_one(hits, seed + tmpl.id))
|
||||
|
||||
# Collect optional matches (override preferred, then pantry match)
|
||||
matched_optional: list[str] = []
|
||||
for role in tmpl.optional:
|
||||
chosen = role_overrides.get(role.display)
|
||||
if chosen:
|
||||
matched_optional.append(chosen)
|
||||
else:
|
||||
hits = _matches_role(role, pantry_set)
|
||||
if hits:
|
||||
matched_optional.append(_pick_one(hits, seed + tmpl.id))
|
||||
|
||||
all_matched = matched_required + matched_optional
|
||||
|
||||
# Build title: prefer override items for personalisation
|
||||
effective_pantry = pantry_set | set(role_overrides.values())
|
||||
title = _personalized_title(tmpl, effective_pantry, seed + tmpl.id)
|
||||
|
||||
return RecipeSuggestion(
|
||||
id=tmpl.id,
|
||||
title=title,
|
||||
match_count=len(all_matched),
|
||||
element_coverage={},
|
||||
swap_candidates=[],
|
||||
matched_ingredients=all_matched,
|
||||
missing_ingredients=[],
|
||||
directions=tmpl.directions,
|
||||
notes=tmpl.notes,
|
||||
level=1,
|
||||
is_wildcard=False,
|
||||
nutrition=None,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@ if TYPE_CHECKING:
|
|||
from app.db.store import Store
|
||||
|
||||
from app.models.schemas.recipe import GroceryLink, NutritionPanel, RecipeRequest, RecipeResult, RecipeSuggestion, SwapCandidate
|
||||
from app.services.recipe.assembly_recipes import match_assembly_templates
|
||||
from app.services.recipe.element_classifier import ElementClassifier
|
||||
from app.services.recipe.grocery_links import GroceryLinkBuilder
|
||||
from app.services.recipe.substitution_engine import SubstitutionEngine
|
||||
|
|
@ -517,13 +516,6 @@ def _build_source_url(row: dict) -> str | None:
|
|||
return None
|
||||
|
||||
|
||||
_ASSEMBLY_TIER_LIMITS: dict[str, int] = {
|
||||
"free": 2,
|
||||
"paid": 4,
|
||||
"premium": 6,
|
||||
}
|
||||
|
||||
|
||||
# Method complexity classification patterns
|
||||
_EASY_METHODS = re.compile(
|
||||
r"\b(microwave|mix|stir|blend|toast|assemble|heat)\b", re.IGNORECASE
|
||||
|
|
@ -637,6 +629,11 @@ class RecipeEngine:
|
|||
return gen.generate(req, profiles, gaps)
|
||||
|
||||
# Level 1 & 2: deterministic path
|
||||
# L1 ("Use What I Have") applies strict quality gates:
|
||||
# - exclude_generic: filter catch-all recipes at the DB level
|
||||
# - effective_max_missing: default to 2 when user hasn't set a cap
|
||||
# - match ratio: require ≥60% ingredient coverage to avoid low-signal results
|
||||
_l1 = req.level == 1 and not req.shopping_mode
|
||||
nf = req.nutrition_filters
|
||||
rows = self._store.search_recipes_by_ingredients(
|
||||
req.pantry_items,
|
||||
|
|
@ -647,7 +644,16 @@ class RecipeEngine:
|
|||
max_carbs_g=nf.max_carbs_g,
|
||||
max_sodium_mg=nf.max_sodium_mg,
|
||||
excluded_ids=req.excluded_ids or [],
|
||||
exclude_generic=_l1,
|
||||
)
|
||||
|
||||
# L1 strict defaults: cap missing ingredients and require a minimum ratio.
|
||||
_L1_MAX_MISSING_DEFAULT = 2
|
||||
_L1_MIN_MATCH_RATIO = 0.6
|
||||
effective_max_missing = req.max_missing
|
||||
if _l1 and effective_max_missing is None:
|
||||
effective_max_missing = _L1_MAX_MISSING_DEFAULT
|
||||
|
||||
suggestions = []
|
||||
hard_day_tier_map: dict[int, int] = {} # recipe_id → tier when hard_day_mode
|
||||
|
||||
|
|
@ -690,9 +696,17 @@ class RecipeEngine:
|
|||
missing.append(n)
|
||||
|
||||
# Filter by max_missing — skipped in shopping mode (user is willing to buy)
|
||||
if not req.shopping_mode and req.max_missing is not None and len(missing) > req.max_missing:
|
||||
if not req.shopping_mode and effective_max_missing is not None and len(missing) > effective_max_missing:
|
||||
continue
|
||||
|
||||
# L1 match ratio gate: drop results where less than 60% of the recipe's
|
||||
# ingredients are in the pantry. Prevents low-signal results like a
|
||||
# 10-ingredient recipe matching on only one common item.
|
||||
if _l1 and ingredient_names:
|
||||
match_ratio = len(matched) / len(ingredient_names)
|
||||
if match_ratio < _L1_MIN_MATCH_RATIO:
|
||||
continue
|
||||
|
||||
# Filter and tier-rank by hard_day_mode
|
||||
if req.hard_day_mode:
|
||||
directions: list[str] = row.get("directions") or []
|
||||
|
|
@ -761,39 +775,17 @@ class RecipeEngine:
|
|||
source_url=_build_source_url(row),
|
||||
))
|
||||
|
||||
# Assembly-dish templates (burrito, fried rice, pasta, etc.)
|
||||
# Expiry boost: when expiry_first, the pantry_items list is already sorted
|
||||
# by expiry urgency — treat the first slice as the "expiring" set so templates
|
||||
# that use those items bubble up in the merged ranking.
|
||||
expiring_set: set[str] = set()
|
||||
if req.expiry_first:
|
||||
expiring_set = _expand_pantry_set(req.pantry_items[:10])
|
||||
|
||||
assembly = match_assembly_templates(
|
||||
pantry_items=req.pantry_items,
|
||||
pantry_set=pantry_set,
|
||||
excluded_ids=req.excluded_ids or [],
|
||||
expiring_set=expiring_set,
|
||||
)
|
||||
|
||||
# Cap by tier — lifted in shopping mode since missing-ingredient templates
|
||||
# are desirable there (each fires an affiliate link opportunity).
|
||||
if not req.shopping_mode:
|
||||
assembly_limit = _ASSEMBLY_TIER_LIMITS.get(req.tier, 3)
|
||||
assembly = assembly[:assembly_limit]
|
||||
|
||||
# Interleave: sort templates and corpus recipes together.
|
||||
# Sort corpus results — assembly templates are now served from a dedicated tab.
|
||||
# Hard day mode: primary sort by tier (0=premade, 1=simple, 2=moderate),
|
||||
# then by match_count within each tier. Assembly templates are inherently
|
||||
# simple so they default to tier 1 when not in the tier map.
|
||||
# Normal mode: sort by match_count only.
|
||||
# then by match_count within each tier.
|
||||
# Normal mode: sort by match_count descending.
|
||||
if req.hard_day_mode and hard_day_tier_map:
|
||||
suggestions = sorted(
|
||||
assembly + suggestions,
|
||||
suggestions,
|
||||
key=lambda s: (hard_day_tier_map.get(s.id, 1), -s.match_count),
|
||||
)
|
||||
else:
|
||||
suggestions = sorted(assembly + suggestions, key=lambda s: s.match_count, reverse=True)
|
||||
suggestions = sorted(suggestions, key=lambda s: -s.match_count)
|
||||
|
||||
# Build grocery list — deduplicated union of all missing ingredients
|
||||
seen: set[str] = set()
|
||||
|
|
|
|||
300
app/services/recipe/tag_inferrer.py
Normal file
300
app/services/recipe/tag_inferrer.py
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
"""
|
||||
Recipe tag inference engine.
|
||||
|
||||
Derives normalized tags from a recipe's title, ingredient names, existing corpus
|
||||
tags (category + keywords), enriched ingredient profile data, and optional
|
||||
nutrition data.
|
||||
|
||||
Tags are organized into five namespaces:
|
||||
cuisine:* -- cuisine/region classification
|
||||
dietary:* -- dietary restriction / nutrition profile
|
||||
flavor:* -- flavor profile (spicy, smoky, sweet, etc.)
|
||||
time:* -- effort / time signals
|
||||
meal:* -- meal type
|
||||
can_be:* -- achievable with substitutions (e.g. can_be:Gluten-Free)
|
||||
|
||||
Output is a flat sorted list of strings, e.g.:
|
||||
["can_be:Gluten-Free", "cuisine:Italian", "dietary:Low-Carb",
|
||||
"flavor:Savory", "flavor:Umami", "time:Quick"]
|
||||
|
||||
These populate recipes.inferred_tags and are FTS5-indexed so browse domain
|
||||
queries find recipes the food.com corpus tags alone would miss.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Text-signal tables
|
||||
# (tag, [case-insensitive substrings to search in combined title+ingredient text])
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_CUISINE_SIGNALS: list[tuple[str, list[str]]] = [
|
||||
("cuisine:Japanese", ["miso", "dashi", "ramen", "sushi", "teriyaki", "sake", "mirin",
|
||||
"wasabi", "panko", "edamame", "tonkatsu", "yakitori", "ponzu"]),
|
||||
("cuisine:Korean", ["gochujang", "kimchi", "doenjang", "gochugaru",
|
||||
"bulgogi", "bibimbap", "japchae"]),
|
||||
("cuisine:Thai", ["fish sauce", "lemongrass", "galangal", "pad thai", "thai basil",
|
||||
"kaffir lime", "tom yum", "green curry", "red curry", "nam pla"]),
|
||||
("cuisine:Chinese", ["hoisin", "oyster sauce", "five spice", "bok choy", "chow mein",
|
||||
"dumpling", "wonton", "mapo", "char siu", "sichuan"]),
|
||||
("cuisine:Vietnamese", ["pho", "banh mi", "nuoc cham", "rice paper", "vietnamese"]),
|
||||
("cuisine:Indian", ["garam masala", "turmeric", "cardamom", "fenugreek", "paneer",
|
||||
"tikka", "masala", "biryani", "dal", "naan", "tandoori",
|
||||
"curry leaf", "tamarind", "chutney"]),
|
||||
("cuisine:Middle Eastern", ["tahini", "harissa", "za'atar", "sumac", "baharat", "rose water",
|
||||
"pomegranate molasses", "freekeh", "fattoush", "shakshuka"]),
|
||||
("cuisine:Greek", ["feta", "tzatziki", "moussaka", "spanakopita", "orzo",
|
||||
"kalamata", "gyro", "souvlaki", "dolma"]),
|
||||
("cuisine:Mediterranean", ["hummus", "pita", "couscous", "preserved lemon"]),
|
||||
("cuisine:Italian", ["pasta", "pizza", "risotto", "lasagna", "carbonara", "gnocchi",
|
||||
"parmesan", "mozzarella", "ricotta", "prosciutto", "pancetta",
|
||||
"arancini", "osso buco", "tiramisu", "pesto", "bolognese",
|
||||
"cannoli", "polenta", "bruschetta", "focaccia"]),
|
||||
("cuisine:French", ["croissant", "quiche", "crepe", "coq au vin",
|
||||
"ratatouille", "bearnaise", "hollandaise", "bouillabaisse",
|
||||
"herbes de provence", "dijon", "gruyere", "brie", "cassoulet"]),
|
||||
("cuisine:Spanish", ["paella", "chorizo", "gazpacho", "tapas", "patatas bravas",
|
||||
"sofrito", "manchego", "albondigas"]),
|
||||
("cuisine:German", ["sauerkraut", "bratwurst", "schnitzel", "pretzel", "strudel",
|
||||
"spaetzle", "sauerbraten"]),
|
||||
("cuisine:Mexican", ["taco", "burrito", "enchilada", "salsa", "guacamole", "chipotle",
|
||||
"queso", "tamale", "mole", "jalapeno", "tortilla", "carnitas",
|
||||
"chile verde", "posole", "tostada", "quesadilla"]),
|
||||
("cuisine:Latin American", ["plantain", "yuca", "chimichurri", "ceviche", "adobo", "empanada"]),
|
||||
("cuisine:American", ["bbq sauce", "buffalo sauce", "ranch dressing", "coleslaw",
|
||||
"cornbread", "mac and cheese", "brisket", "cheeseburger"]),
|
||||
("cuisine:Southern", ["collard greens", "black-eyed peas", "okra", "grits", "catfish",
|
||||
"hush puppies", "pecan pie"]),
|
||||
("cuisine:Cajun", ["cajun", "creole", "gumbo", "jambalaya", "andouille", "etouffee"]),
|
||||
("cuisine:African", ["injera", "berbere", "jollof", "suya", "egusi", "fufu", "tagine"]),
|
||||
("cuisine:Caribbean", ["jerk", "scotch bonnet", "callaloo", "ackee"]),
|
||||
]
|
||||
|
||||
_DIETARY_SIGNALS: list[tuple[str, list[str]]] = [
|
||||
("dietary:Vegan", ["vegan", "plant-based", "plant based"]),
|
||||
("dietary:Vegetarian", ["vegetarian", "meatless"]),
|
||||
("dietary:Gluten-Free", ["gluten-free", "gluten free", "celiac"]),
|
||||
("dietary:Dairy-Free", ["dairy-free", "dairy free", "lactose free", "non-dairy"]),
|
||||
("dietary:Low-Carb", ["low-carb", "low carb", "keto", "ketogenic", "very low carbs"]),
|
||||
("dietary:High-Protein", ["high protein", "high-protein"]),
|
||||
("dietary:Low-Fat", ["low-fat", "low fat", "fat-free", "reduced fat"]),
|
||||
("dietary:Paleo", ["paleo", "whole30"]),
|
||||
("dietary:Nut-Free", ["nut-free", "nut free", "peanut free"]),
|
||||
("dietary:Egg-Free", ["egg-free", "egg free"]),
|
||||
("dietary:Low-Sodium", ["low sodium", "no salt"]),
|
||||
("dietary:Healthy", ["healthy", "low cholesterol", "heart healthy", "wholesome"]),
|
||||
]
|
||||
|
||||
_FLAVOR_SIGNALS: list[tuple[str, list[str]]] = [
|
||||
("flavor:Spicy", ["jalapeno", "habanero", "ghost pepper", "sriracha",
|
||||
"chili flake", "red pepper flake", "cayenne", "hot sauce",
|
||||
"gochujang", "harissa", "scotch bonnet", "szechuan pepper", "spicy"]),
|
||||
("flavor:Smoky", ["smoked", "liquid smoke", "smoked paprika",
|
||||
"bbq sauce", "barbecue", "hickory", "mesquite"]),
|
||||
("flavor:Sweet", ["honey", "maple syrup", "brown sugar", "caramel", "chocolate",
|
||||
"vanilla", "condensed milk", "molasses", "agave"]),
|
||||
("flavor:Savory", ["soy sauce", "fish sauce", "miso", "worcestershire", "anchovy",
|
||||
"parmesan", "blue cheese", "bone broth"]),
|
||||
("flavor:Tangy", ["lemon juice", "lime juice", "vinegar", "balsamic", "buttermilk",
|
||||
"sour cream", "fermented", "pickled", "tamarind", "sumac"]),
|
||||
("flavor:Herby", ["fresh basil", "fresh cilantro", "fresh dill", "fresh mint",
|
||||
"fresh tarragon", "fresh thyme", "herbes de provence"]),
|
||||
("flavor:Rich", ["heavy cream", "creme fraiche", "mascarpone", "double cream",
|
||||
"ghee", "coconut cream", "cream cheese"]),
|
||||
("flavor:Umami", ["mushroom", "nutritional yeast", "tomato paste",
|
||||
"parmesan rind", "bonito", "kombu"]),
|
||||
]
|
||||
|
||||
_TIME_SIGNALS: list[tuple[str, list[str]]] = [
|
||||
("time:Quick", ["< 15 mins", "< 30 mins", "weeknight", "easy"]),
|
||||
("time:Under 1 Hour", ["< 60 mins"]),
|
||||
("time:Make-Ahead", ["freezer", "overnight", "refrigerator", "make-ahead", "make ahead"]),
|
||||
("time:Slow Cook", ["slow cooker", "crockpot", "< 4 hours", "braise"]),
|
||||
]
|
||||
|
||||
# food.com corpus tag -> normalized tags
|
||||
_CORPUS_TAG_MAP: dict[str, list[str]] = {
|
||||
"european": ["cuisine:Italian", "cuisine:French", "cuisine:German",
|
||||
"cuisine:Spanish"],
|
||||
"asian": ["cuisine:Chinese", "cuisine:Japanese", "cuisine:Thai",
|
||||
"cuisine:Korean", "cuisine:Vietnamese"],
|
||||
"chinese": ["cuisine:Chinese"],
|
||||
"japanese": ["cuisine:Japanese"],
|
||||
"thai": ["cuisine:Thai"],
|
||||
"vietnamese": ["cuisine:Vietnamese"],
|
||||
"indian": ["cuisine:Indian"],
|
||||
"greek": ["cuisine:Greek"],
|
||||
"mexican": ["cuisine:Mexican"],
|
||||
"african": ["cuisine:African"],
|
||||
"caribbean": ["cuisine:Caribbean"],
|
||||
"vegan": ["dietary:Vegan", "dietary:Vegetarian"],
|
||||
"vegetarian": ["dietary:Vegetarian"],
|
||||
"healthy": ["dietary:Healthy"],
|
||||
"low cholesterol": ["dietary:Healthy"],
|
||||
"very low carbs": ["dietary:Low-Carb"],
|
||||
"high in...": ["dietary:High-Protein"],
|
||||
"lactose free": ["dietary:Dairy-Free"],
|
||||
"egg free": ["dietary:Egg-Free"],
|
||||
"< 15 mins": ["time:Quick"],
|
||||
"< 30 mins": ["time:Quick"],
|
||||
"< 60 mins": ["time:Under 1 Hour"],
|
||||
"< 4 hours": ["time:Slow Cook"],
|
||||
"weeknight": ["time:Quick"],
|
||||
"freezer": ["time:Make-Ahead"],
|
||||
"dessert": ["meal:Dessert"],
|
||||
"breakfast": ["meal:Breakfast"],
|
||||
"lunch/snacks": ["meal:Lunch", "meal:Snack"],
|
||||
"beverages": ["meal:Beverage"],
|
||||
"cookie & brownie": ["meal:Dessert"],
|
||||
"breads": ["meal:Bread"],
|
||||
}
|
||||
|
||||
# ingredient_profiles.elements value -> flavor tag
|
||||
_ELEMENT_TO_FLAVOR: dict[str, str] = {
|
||||
"Aroma": "flavor:Herby",
|
||||
"Richness": "flavor:Rich",
|
||||
"Structure": "", # no flavor tag
|
||||
"Binding": "",
|
||||
"Crust": "flavor:Smoky",
|
||||
"Lift": "",
|
||||
"Emulsion": "flavor:Rich",
|
||||
"Acid": "flavor:Tangy",
|
||||
}
|
||||
|
||||
|
||||
def _build_text(title: str, ingredient_names: list[str]) -> str:
|
||||
parts = [title.lower()]
|
||||
parts.extend(i.lower() for i in ingredient_names)
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def _match_signals(text: str, table: list[tuple[str, list[str]]]) -> list[str]:
|
||||
return [tag for tag, pats in table if any(p in text for p in pats)]
|
||||
|
||||
|
||||
def infer_tags(
|
||||
title: str,
|
||||
ingredient_names: list[str],
|
||||
corpus_keywords: list[str],
|
||||
corpus_category: str = "",
|
||||
# Enriched ingredient profile signals (from ingredient_profiles cross-ref)
|
||||
element_coverage: dict[str, float] | None = None,
|
||||
fermented_count: int = 0,
|
||||
glutamate_total: float = 0.0,
|
||||
ph_min: float | None = None,
|
||||
available_sub_constraints: list[str] | None = None,
|
||||
# Nutrition data for macro-based tags
|
||||
calories: float | None = None,
|
||||
protein_g: float | None = None,
|
||||
fat_g: float | None = None,
|
||||
carbs_g: float | None = None,
|
||||
servings: float | None = None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
Derive normalized tags for a recipe.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
title, ingredient_names, corpus_keywords, corpus_category
|
||||
: Primary recipe data.
|
||||
element_coverage
|
||||
: Dict from recipes.element_coverage -- element name to coverage ratio
|
||||
(e.g. {"Aroma": 0.6, "Richness": 0.4}). Derived from ingredient_profiles.
|
||||
fermented_count
|
||||
: Number of fermented ingredients (from ingredient_profiles.is_fermented).
|
||||
glutamate_total
|
||||
: Sum of glutamate_mg across all profiled ingredients. High values signal umami.
|
||||
ph_min
|
||||
: Minimum ph_estimate across profiled ingredients. Low values signal acidity.
|
||||
available_sub_constraints
|
||||
: Substitution constraint labels achievable for this recipe
|
||||
(e.g. ["gluten_free", "low_carb"]). From substitution_pairs cross-ref.
|
||||
These become can_be:* tags.
|
||||
calories, protein_g, fat_g, carbs_g, servings
|
||||
: Nutrition data for macro-based dietary tags.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Sorted list of unique normalized tag strings.
|
||||
"""
|
||||
tags: set[str] = set()
|
||||
|
||||
# 1. Map corpus tags to normalized vocabulary
|
||||
for kw in corpus_keywords:
|
||||
for t in _CORPUS_TAG_MAP.get(kw.lower(), []):
|
||||
tags.add(t)
|
||||
if corpus_category:
|
||||
for t in _CORPUS_TAG_MAP.get(corpus_category.lower(), []):
|
||||
tags.add(t)
|
||||
|
||||
# 2. Text-signal matching
|
||||
text = _build_text(title, ingredient_names)
|
||||
tags.update(_match_signals(text, _CUISINE_SIGNALS))
|
||||
tags.update(_match_signals(text, _DIETARY_SIGNALS))
|
||||
tags.update(_match_signals(text, _FLAVOR_SIGNALS))
|
||||
|
||||
# 3. Time signals from corpus keywords + text
|
||||
corpus_text = " ".join(kw.lower() for kw in corpus_keywords)
|
||||
tags.update(_match_signals(corpus_text, _TIME_SIGNALS))
|
||||
tags.update(_match_signals(text, _TIME_SIGNALS))
|
||||
|
||||
# 4. Enriched profile signals
|
||||
if element_coverage:
|
||||
for element, coverage in element_coverage.items():
|
||||
if coverage > 0.2: # >20% of ingredients carry this element
|
||||
flavor_tag = _ELEMENT_TO_FLAVOR.get(element, "")
|
||||
if flavor_tag:
|
||||
tags.add(flavor_tag)
|
||||
|
||||
if glutamate_total > 50:
|
||||
tags.add("flavor:Umami")
|
||||
|
||||
if fermented_count > 0:
|
||||
tags.add("flavor:Tangy")
|
||||
|
||||
if ph_min is not None and ph_min < 4.5:
|
||||
tags.add("flavor:Tangy")
|
||||
|
||||
# 5. Achievable-via-substitution tags
|
||||
if available_sub_constraints:
|
||||
label_to_tag = {
|
||||
"gluten_free": "can_be:Gluten-Free",
|
||||
"low_calorie": "can_be:Low-Calorie",
|
||||
"low_carb": "can_be:Low-Carb",
|
||||
"vegan": "can_be:Vegan",
|
||||
"dairy_free": "can_be:Dairy-Free",
|
||||
"low_sodium": "can_be:Low-Sodium",
|
||||
}
|
||||
for label in available_sub_constraints:
|
||||
tag = label_to_tag.get(label)
|
||||
if tag:
|
||||
tags.add(tag)
|
||||
|
||||
# 6. Macro-based dietary tags
|
||||
if servings and servings > 0 and any(
|
||||
v is not None for v in (protein_g, fat_g, carbs_g, calories)
|
||||
):
|
||||
def _per(v: float | None) -> float | None:
|
||||
return v / servings if v is not None else None
|
||||
|
||||
prot_s = _per(protein_g)
|
||||
fat_s = _per(fat_g)
|
||||
carb_s = _per(carbs_g)
|
||||
cal_s = _per(calories)
|
||||
|
||||
if prot_s is not None and prot_s >= 20:
|
||||
tags.add("dietary:High-Protein")
|
||||
if fat_s is not None and fat_s <= 5:
|
||||
tags.add("dietary:Low-Fat")
|
||||
if carb_s is not None and carb_s <= 10:
|
||||
tags.add("dietary:Low-Carb")
|
||||
if cal_s is not None and cal_s <= 250:
|
||||
tags.add("dietary:Light")
|
||||
elif protein_g is not None and protein_g >= 20:
|
||||
tags.add("dietary:High-Protein")
|
||||
|
||||
# 7. Vegan implies vegetarian
|
||||
if "dietary:Vegan" in tags:
|
||||
tags.add("dietary:Vegetarian")
|
||||
|
||||
return sorted(tags)
|
||||
|
|
@ -170,7 +170,7 @@ import { householdAPI } from './services/api'
|
|||
|
||||
type Tab = 'inventory' | 'receipts' | 'recipes' | 'settings'
|
||||
|
||||
const currentTab = ref<Tab>('inventory')
|
||||
const currentTab = ref<Tab>('recipes')
|
||||
const sidebarCollapsed = ref(false)
|
||||
const inventoryStore = useInventoryStore()
|
||||
const { kiwiVisible, kiwiDirection } = useEasterEggs()
|
||||
|
|
@ -198,6 +198,11 @@ async function switchTab(tab: Tab) {
|
|||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// Pre-fetch inventory so Recipes tab has data on first load
|
||||
if (inventoryStore.items.length === 0) {
|
||||
await inventoryStore.fetchItems()
|
||||
}
|
||||
|
||||
// Handle household invite links: /#/join?household_id=xxx&token=yyy
|
||||
const hash = window.location.hash
|
||||
if (hash.includes('/join')) {
|
||||
|
|
|
|||
539
frontend/src/components/BuildYourOwnTab.vue
Normal file
539
frontend/src/components/BuildYourOwnTab.vue
Normal file
|
|
@ -0,0 +1,539 @@
|
|||
<template>
|
||||
<div class="byo-tab">
|
||||
|
||||
<!-- ── Step 0: Template grid ─────────────────────────────────── -->
|
||||
<div v-if="phase === 'select'" class="byo-section">
|
||||
<h2 class="section-title text-xl mb-sm">Build Your Own Recipe</h2>
|
||||
<p class="text-sm text-secondary mb-md">
|
||||
Choose a style, then pick your ingredients one step at a time.
|
||||
</p>
|
||||
|
||||
<div v-if="templatesLoading" class="text-secondary text-sm">Loading templates…</div>
|
||||
<div v-else-if="templatesError" role="alert" class="status-badge status-error mb-md">
|
||||
{{ templatesError }}
|
||||
</div>
|
||||
<div v-else class="template-grid" role="list">
|
||||
<button
|
||||
v-for="tmpl in templates"
|
||||
:key="tmpl.id"
|
||||
class="template-card card"
|
||||
role="listitem"
|
||||
:aria-label="tmpl.title + ': ' + tmpl.descriptor"
|
||||
@click="selectTemplate(tmpl)"
|
||||
>
|
||||
<span class="tmpl-icon" aria-hidden="true">{{ tmpl.icon }}</span>
|
||||
<span class="tmpl-title">{{ tmpl.title }}</span>
|
||||
<span class="tmpl-descriptor text-sm text-secondary">{{ tmpl.descriptor }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Step 1+: Ingredient wizard ───────────────────────────── -->
|
||||
<div v-else-if="phase === 'wizard'" class="byo-section">
|
||||
<!-- Back + step counter -->
|
||||
<div class="byo-nav mb-sm">
|
||||
<button class="btn btn-sm btn-secondary" @click="goBack">← Back</button>
|
||||
<span class="text-sm text-secondary step-counter">Step {{ wizardStep + 1 }} of {{ totalSteps }}</span>
|
||||
</div>
|
||||
|
||||
<h2 class="section-title text-xl mb-xs">What's your {{ currentRole?.display }}?</h2>
|
||||
<p v-if="currentRole?.hint" class="text-sm text-secondary mb-md">{{ currentRole.hint }}</p>
|
||||
|
||||
<!-- Missing ingredient mode toggle -->
|
||||
<div class="mode-toggle mb-sm" role="radiogroup" aria-label="Missing ingredients">
|
||||
<button
|
||||
v-for="mode in missingModes"
|
||||
:key="mode.value"
|
||||
:class="['btn', 'btn-sm', recipesStore.missingIngredientMode === mode.value ? 'btn-primary' : 'btn-secondary']"
|
||||
:aria-checked="recipesStore.missingIngredientMode === mode.value"
|
||||
role="radio"
|
||||
@click="recipesStore.missingIngredientMode = mode.value as any"
|
||||
>{{ mode.label }}</button>
|
||||
</div>
|
||||
|
||||
<!-- Filter row: text search or tag cloud -->
|
||||
<div class="filter-row mb-sm">
|
||||
<input
|
||||
v-if="recipesStore.builderFilterMode === 'text'"
|
||||
v-model="filterText"
|
||||
class="form-input filter-input"
|
||||
:placeholder="'Search ' + (currentRole?.display ?? 'ingredients') + '…'"
|
||||
aria-label="Search ingredients"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="tag-cloud"
|
||||
role="group"
|
||||
aria-label="Filter by tag"
|
||||
>
|
||||
<button
|
||||
v-for="tag in candidates?.available_tags ?? []"
|
||||
:key="tag"
|
||||
:class="['btn', 'btn-sm', 'tag-chip', selectedTags.has(tag) ? 'tag-active' : '']"
|
||||
:aria-pressed="selectedTags.has(tag)"
|
||||
@click="toggleTag(tag)"
|
||||
>{{ tag }}</button>
|
||||
<span v-if="(candidates?.available_tags ?? []).length === 0" class="text-secondary text-sm">
|
||||
No tags available for this ingredient set.
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
class="btn btn-sm btn-secondary filter-mode-btn"
|
||||
:aria-pressed="recipesStore.builderFilterMode === 'tags'"
|
||||
:aria-label="recipesStore.builderFilterMode === 'text' ? 'Switch to tag filter' : 'Switch to text search'"
|
||||
@click="recipesStore.builderFilterMode = recipesStore.builderFilterMode === 'text' ? 'tags' : 'text'"
|
||||
>{{ recipesStore.builderFilterMode === 'text' ? '🏷️' : '🔍' }}</button>
|
||||
</div>
|
||||
|
||||
<!-- Candidates loading / error -->
|
||||
<div v-if="candidatesLoading" class="text-secondary text-sm mb-sm">Loading options…</div>
|
||||
<div v-else-if="candidatesError" role="alert" class="status-badge status-error mb-sm">
|
||||
{{ candidatesError }}
|
||||
</div>
|
||||
|
||||
<!-- Compatible candidates -->
|
||||
<div v-if="filteredCompatible.length > 0" class="candidates-section mb-sm">
|
||||
<p class="text-xs font-semibold text-secondary mb-xs" aria-hidden="true">Available</p>
|
||||
<div class="ingredient-grid">
|
||||
<button
|
||||
v-for="item in filteredCompatible"
|
||||
:key="item.name"
|
||||
:class="['ingredient-card', 'btn', selectedInRole.has(item.name) ? 'ingredient-active' : '']"
|
||||
:aria-pressed="selectedInRole.has(item.name)"
|
||||
:aria-label="item.name + (item.in_pantry ? '' : ' — not in pantry')"
|
||||
@click="toggleIngredient(item.name)"
|
||||
>
|
||||
<span class="ingredient-name">{{ item.name }}</span>
|
||||
<span v-if="!item.in_pantry && recipesStore.missingIngredientMode === 'add-to-cart'"
|
||||
class="cart-icon" aria-hidden="true">🛒</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Other candidates (greyed or add-to-cart mode only) -->
|
||||
<template v-if="recipesStore.missingIngredientMode !== 'hidden' && filteredOther.length > 0">
|
||||
<div class="candidates-separator text-xs text-secondary mb-xs">also works</div>
|
||||
<div class="ingredient-grid ingredient-grid-other mb-sm">
|
||||
<button
|
||||
v-for="item in filteredOther"
|
||||
:key="item.name"
|
||||
:class="['ingredient-card', 'btn',
|
||||
item.in_pantry ? '' : 'ingredient-missing',
|
||||
selectedInRole.has(item.name) ? 'ingredient-active' : '']"
|
||||
:aria-pressed="selectedInRole.has(item.name)"
|
||||
:aria-label="item.name + (item.in_pantry ? '' : ' — not in pantry')"
|
||||
:disabled="!item.in_pantry && recipesStore.missingIngredientMode === 'greyed'"
|
||||
@click="item.in_pantry || recipesStore.missingIngredientMode !== 'greyed' ? toggleIngredient(item.name) : undefined"
|
||||
>
|
||||
<span class="ingredient-name">{{ item.name }}</span>
|
||||
<span v-if="!item.in_pantry && recipesStore.missingIngredientMode === 'add-to-cart'"
|
||||
class="cart-icon" aria-hidden="true">🛒</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- No-match state: nothing compatible AND nothing visible in other section.
|
||||
filteredOther items are hidden when mode is 'hidden', so check visibility too. -->
|
||||
<template v-if="!candidatesLoading && !candidatesError && filteredCompatible.length === 0 && (filteredOther.length === 0 || recipesStore.missingIngredientMode === 'hidden')">
|
||||
<!-- Custom freeform input: text filter with no matches → offer "use anyway" -->
|
||||
<div v-if="recipesStore.builderFilterMode === 'text' && filterText.trim().length > 0" class="custom-ingredient-prompt mb-sm">
|
||||
<p class="text-sm text-secondary mb-xs">
|
||||
No match for "{{ filterText.trim() }}" in your pantry.
|
||||
</p>
|
||||
<button class="btn btn-secondary" @click="useCustomIngredient">
|
||||
Use "{{ filterText.trim() }}" anyway
|
||||
</button>
|
||||
</div>
|
||||
<!-- No pantry items at all for this role -->
|
||||
<p v-else class="text-sm text-secondary mb-sm">
|
||||
Nothing in your pantry fits this role yet. You can skip it or
|
||||
<button class="btn-link" @click="recipesStore.missingIngredientMode = 'greyed'">show options to add.</button>
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<!-- Skip / Next -->
|
||||
<div class="byo-actions">
|
||||
<button
|
||||
v-if="!currentRole?.required"
|
||||
class="btn btn-secondary"
|
||||
@click="advanceStep"
|
||||
>Skip (optional)</button>
|
||||
<button
|
||||
v-else-if="currentRole?.required && selectedInRole.size === 0"
|
||||
class="btn btn-secondary"
|
||||
@click="advanceStep"
|
||||
>I'll add this later</button>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
:disabled="buildLoading"
|
||||
@click="wizardStep < totalSteps - 1 ? advanceStep() : buildRecipe()"
|
||||
>
|
||||
{{ wizardStep < totalSteps - 1 ? 'Next →' : 'Build this recipe' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Result ─────────────────────────────────────────────────── -->
|
||||
<div v-else-if="phase === 'result'" class="byo-section">
|
||||
<div v-if="buildLoading" class="text-secondary text-sm mb-md">Building your recipe…</div>
|
||||
<div v-else-if="buildError" role="alert" class="status-badge status-error mb-md">
|
||||
{{ buildError }}
|
||||
</div>
|
||||
<template v-else-if="builtRecipe">
|
||||
<RecipeDetailPanel
|
||||
:recipe="builtRecipe"
|
||||
:grocery-links="[]"
|
||||
@close="phase = 'select'"
|
||||
@cooked="phase = 'select'"
|
||||
/>
|
||||
<div class="byo-actions mt-sm">
|
||||
<button class="btn btn-secondary" @click="resetToTemplate">Try a different build</button>
|
||||
<button class="btn btn-secondary" @click="phase = 'wizard'">Adjust ingredients</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRecipesStore } from '../stores/recipes'
|
||||
import RecipeDetailPanel from './RecipeDetailPanel.vue'
|
||||
import { recipesAPI, type AssemblyTemplateOut, type RoleCandidatesResponse, type RecipeSuggestion } from '../services/api'
|
||||
|
||||
const recipesStore = useRecipesStore()
|
||||
|
||||
type Phase = 'select' | 'wizard' | 'result'
|
||||
const phase = ref<Phase>('select')
|
||||
|
||||
// Template grid state
|
||||
const templates = ref<AssemblyTemplateOut[]>([])
|
||||
const templatesLoading = ref(false)
|
||||
const templatesError = ref<string | null>(null)
|
||||
|
||||
// Wizard state
|
||||
const selectedTemplate = ref<AssemblyTemplateOut | null>(null)
|
||||
const wizardStep = ref(0)
|
||||
const roleOverrides = ref<Record<string, string[]>>({})
|
||||
|
||||
// Candidates for current step
|
||||
const candidates = ref<RoleCandidatesResponse | null>(null)
|
||||
const candidatesLoading = ref(false)
|
||||
const candidatesError = ref<string | null>(null)
|
||||
|
||||
// Filter state (reset on step advance)
|
||||
const filterText = ref('')
|
||||
const selectedTags = ref<Set<string>>(new Set())
|
||||
|
||||
// Result state
|
||||
const builtRecipe = ref<RecipeSuggestion | null>(null)
|
||||
const buildLoading = ref(false)
|
||||
const buildError = ref<string | null>(null)
|
||||
|
||||
const missingModes = [
|
||||
{ label: 'Available only', value: 'hidden' },
|
||||
{ label: 'Show missing', value: 'greyed' },
|
||||
{ label: 'Add to cart', value: 'add-to-cart' },
|
||||
]
|
||||
|
||||
const totalSteps = computed(() => selectedTemplate.value?.role_sequence.length ?? 0)
|
||||
const currentRole = computed(() => selectedTemplate.value?.role_sequence[wizardStep.value] ?? null)
|
||||
|
||||
const selectedInRole = computed<Set<string>>(() => {
|
||||
const role = currentRole.value?.display
|
||||
if (!role) return new Set()
|
||||
return new Set(roleOverrides.value[role] ?? [])
|
||||
})
|
||||
|
||||
const priorPicks = computed<string[]>(() => {
|
||||
if (!selectedTemplate.value) return []
|
||||
return selectedTemplate.value.role_sequence
|
||||
.slice(0, wizardStep.value)
|
||||
.flatMap((r) => roleOverrides.value[r.display] ?? [])
|
||||
})
|
||||
|
||||
const filteredCompatible = computed(() => applyFilter(candidates.value?.compatible ?? []))
|
||||
const filteredOther = computed(() => applyFilter(candidates.value?.other ?? []))
|
||||
|
||||
function applyFilter(items: RoleCandidatesResponse['compatible']) {
|
||||
if (recipesStore.builderFilterMode === 'text') {
|
||||
const q = filterText.value.trim().toLowerCase()
|
||||
if (!q) return items
|
||||
return items.filter((i) => i.name.toLowerCase().includes(q))
|
||||
} else {
|
||||
if (selectedTags.value.size === 0) return items
|
||||
return items.filter((i) =>
|
||||
[...selectedTags.value].every((tag) => i.tags.includes(tag))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTag(tag: string) {
|
||||
const next = new Set(selectedTags.value)
|
||||
next.has(tag) ? next.delete(tag) : next.add(tag)
|
||||
selectedTags.value = next
|
||||
}
|
||||
|
||||
function toggleIngredient(name: string) {
|
||||
const role = currentRole.value?.display
|
||||
if (!role) return
|
||||
const current = new Set(roleOverrides.value[role] ?? [])
|
||||
current.has(name) ? current.delete(name) : current.add(name)
|
||||
roleOverrides.value = { ...roleOverrides.value, [role]: [...current] }
|
||||
}
|
||||
|
||||
function useCustomIngredient() {
|
||||
const name = filterText.value.trim()
|
||||
if (!name) return
|
||||
const role = currentRole.value?.display
|
||||
if (!role) return
|
||||
const current = new Set(roleOverrides.value[role] ?? [])
|
||||
current.add(name)
|
||||
roleOverrides.value = { ...roleOverrides.value, [role]: [...current] }
|
||||
filterText.value = ''
|
||||
}
|
||||
|
||||
async function selectTemplate(tmpl: AssemblyTemplateOut) {
|
||||
selectedTemplate.value = tmpl
|
||||
wizardStep.value = 0
|
||||
roleOverrides.value = {}
|
||||
phase.value = 'wizard'
|
||||
await loadCandidates()
|
||||
}
|
||||
|
||||
async function loadCandidates() {
|
||||
if (!selectedTemplate.value || !currentRole.value) return
|
||||
candidatesLoading.value = true
|
||||
candidatesError.value = null
|
||||
filterText.value = ''
|
||||
selectedTags.value = new Set()
|
||||
try {
|
||||
candidates.value = await recipesAPI.getRoleCandidates(
|
||||
selectedTemplate.value.id,
|
||||
currentRole.value.display,
|
||||
priorPicks.value,
|
||||
)
|
||||
} catch {
|
||||
candidatesError.value = 'Could not load ingredient options. Please try again.'
|
||||
} finally {
|
||||
candidatesLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function advanceStep() {
|
||||
if (!selectedTemplate.value) return
|
||||
if (wizardStep.value < totalSteps.value - 1) {
|
||||
wizardStep.value++
|
||||
await loadCandidates()
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (phase.value === 'result') {
|
||||
phase.value = 'wizard'
|
||||
return
|
||||
}
|
||||
if (wizardStep.value > 0) {
|
||||
wizardStep.value--
|
||||
loadCandidates()
|
||||
} else {
|
||||
phase.value = 'select'
|
||||
selectedTemplate.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function buildRecipe() {
|
||||
if (!selectedTemplate.value) return
|
||||
buildLoading.value = true
|
||||
buildError.value = null
|
||||
phase.value = 'result'
|
||||
|
||||
const overrides: Record<string, string> = {}
|
||||
for (const [role, picks] of Object.entries(roleOverrides.value)) {
|
||||
if (picks.length > 0) overrides[role] = picks[0]!
|
||||
}
|
||||
|
||||
try {
|
||||
builtRecipe.value = await recipesAPI.buildRecipe({
|
||||
template_id: selectedTemplate.value.id,
|
||||
role_overrides: overrides,
|
||||
})
|
||||
} catch {
|
||||
buildError.value = 'Could not build recipe. Try adjusting your ingredients.'
|
||||
} finally {
|
||||
buildLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function resetToTemplate() {
|
||||
phase.value = 'select'
|
||||
selectedTemplate.value = null
|
||||
wizardStep.value = 0
|
||||
roleOverrides.value = {}
|
||||
builtRecipe.value = null
|
||||
buildError.value = null
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
templatesLoading.value = true
|
||||
try {
|
||||
templates.value = await recipesAPI.getTemplates()
|
||||
} catch {
|
||||
templatesError.value = 'Could not load templates. Please refresh.'
|
||||
} finally {
|
||||
templatesLoading.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.byo-tab {
|
||||
padding: var(--spacing-sm) 0;
|
||||
}
|
||||
|
||||
.byo-section {
|
||||
max-width: 640px;
|
||||
}
|
||||
|
||||
.template-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: var(--spacing-sm);
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.template-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.template-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-xs);
|
||||
padding: var(--spacing-md);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tmpl-icon {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.tmpl-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.tmpl-descriptor {
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.byo-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-md);
|
||||
}
|
||||
|
||||
.step-counter {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.mode-toggle {
|
||||
display: flex;
|
||||
gap: var(--spacing-xs);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.filter-row {
|
||||
display: flex;
|
||||
gap: var(--spacing-xs);
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.filter-input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.filter-mode-btn {
|
||||
flex-shrink: 0;
|
||||
min-width: 36px;
|
||||
}
|
||||
|
||||
.tag-cloud {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--spacing-xs);
|
||||
}
|
||||
|
||||
.tag-active {
|
||||
background: var(--color-primary);
|
||||
color: var(--color-bg-primary);
|
||||
}
|
||||
|
||||
.ingredient-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: var(--spacing-xs);
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.ingredient-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.ingredient-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--spacing-sm) var(--spacing-md);
|
||||
text-align: left;
|
||||
min-height: 44px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ingredient-active {
|
||||
border: 2px solid var(--color-primary);
|
||||
background: var(--color-primary-light);
|
||||
color: var(--color-bg-primary);
|
||||
}
|
||||
|
||||
.ingredient-missing {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.ingredient-name {
|
||||
flex: 1;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.cart-icon {
|
||||
font-size: 0.85rem;
|
||||
margin-left: var(--spacing-xs);
|
||||
}
|
||||
|
||||
.candidates-separator {
|
||||
margin-top: var(--spacing-sm);
|
||||
padding-top: var(--spacing-xs);
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.byo-actions {
|
||||
display: flex;
|
||||
gap: var(--spacing-sm);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--color-primary);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -140,11 +140,13 @@ import { ref, computed, onMounted } from 'vue'
|
|||
|
||||
const props = defineProps<{ currentTab?: string }>()
|
||||
|
||||
const apiBase = (import.meta.env.VITE_API_BASE as string) ?? ''
|
||||
|
||||
// Probe once on mount — hidden until confirmed enabled so button never flashes
|
||||
const enabled = ref(false)
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/v1/feedback/status')
|
||||
const res = await fetch(`${apiBase}/api/v1/feedback/status`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
enabled.value = data.enabled === true
|
||||
|
|
@ -205,7 +207,7 @@ async function submit() {
|
|||
loading.value = true
|
||||
submitError.value = ''
|
||||
try {
|
||||
const res = await fetch('/api/v1/feedback', {
|
||||
const res = await fetch(`${apiBase}/api/v1/feedback`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
|
|
@ -407,6 +409,114 @@ async function submit() {
|
|||
.mt-md { margin-top: var(--spacing-md); }
|
||||
.mt-xs { margin-top: var(--spacing-xs); }
|
||||
|
||||
/* ── Form elements ────────────────────────────────────────────────────── */
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-xs);
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: 600;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.form-input {
|
||||
width: 100%;
|
||||
padding: var(--spacing-xs) var(--spacing-sm);
|
||||
background: var(--color-bg-secondary);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--color-text-primary);
|
||||
font-family: var(--font-body);
|
||||
font-size: var(--font-size-sm);
|
||||
line-height: 1.5;
|
||||
transition: border-color 0.15s;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.form-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--color-border-focus);
|
||||
}
|
||||
.form-input::placeholder { color: var(--color-text-muted); opacity: 0.7; }
|
||||
|
||||
/* ── Buttons ──────────────────────────────────────────────────────────── */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--spacing-xs);
|
||||
padding: var(--spacing-xs) var(--spacing-md);
|
||||
border-radius: var(--radius-md);
|
||||
font-family: var(--font-body);
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s, border-color 0.15s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.btn-primary {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
border: 1px solid var(--color-primary);
|
||||
}
|
||||
.btn-primary:hover:not(:disabled) { filter: brightness(1.1); }
|
||||
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
color: var(--color-text-secondary);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
.btn-ghost:hover:not(:disabled) {
|
||||
background: var(--color-bg-secondary);
|
||||
color: var(--color-text-primary);
|
||||
border-color: var(--color-border-focus);
|
||||
}
|
||||
|
||||
/* ── Filter chips ─────────────────────────────────────────────────────── */
|
||||
.filter-chip-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--spacing-xs);
|
||||
}
|
||||
|
||||
.btn-chip {
|
||||
padding: 5px var(--spacing-sm);
|
||||
background: var(--color-bg-secondary);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 999px;
|
||||
font-family: var(--font-body);
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: 500;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s, border-color 0.15s;
|
||||
}
|
||||
.btn-chip.active,
|
||||
.btn-chip:hover {
|
||||
background: color-mix(in srgb, var(--color-primary) 15%, transparent);
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
/* ── Card ─────────────────────────────────────────────────────────────── */
|
||||
.card {
|
||||
background: var(--color-bg-card);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
/* ── Text utilities ───────────────────────────────────────────────────── */
|
||||
.text-muted { color: var(--color-text-muted); }
|
||||
.text-sm { font-size: var(--font-size-sm); line-height: 1.5; }
|
||||
.text-xs { font-size: 0.75rem; line-height: 1.5; }
|
||||
.font-semibold { font-weight: 600; }
|
||||
|
||||
/* Transition */
|
||||
.modal-fade-enter-active, .modal-fade-leave-active { transition: opacity 0.2s ease; }
|
||||
.modal-fade-enter-from, .modal-fade-leave-to { opacity: 0; }
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@
|
|||
v-if="activeTab === 'browse'"
|
||||
role="tabpanel"
|
||||
aria-labelledby="tab-browse"
|
||||
tabindex="0"
|
||||
@open-recipe="openRecipeById"
|
||||
/>
|
||||
|
||||
|
|
@ -29,6 +30,7 @@
|
|||
v-else-if="activeTab === 'saved'"
|
||||
role="tabpanel"
|
||||
aria-labelledby="tab-saved"
|
||||
tabindex="0"
|
||||
@open-recipe="openRecipeById"
|
||||
/>
|
||||
|
||||
|
|
@ -37,11 +39,20 @@
|
|||
v-else-if="activeTab === 'community'"
|
||||
role="tabpanel"
|
||||
aria-labelledby="tab-community"
|
||||
tabindex="0"
|
||||
@plan-forked="onPlanForked"
|
||||
/>
|
||||
|
||||
<!-- Build Your Own tab -->
|
||||
<BuildYourOwnTab
|
||||
v-else-if="activeTab === 'build'"
|
||||
role="tabpanel"
|
||||
aria-labelledby="tab-build"
|
||||
tabindex="0"
|
||||
/>
|
||||
|
||||
<!-- Find tab (existing search UI) -->
|
||||
<div v-else role="tabpanel" aria-labelledby="tab-find">
|
||||
<div v-else ref="findPanelRef" role="tabpanel" aria-labelledby="tab-find" tabindex="0">
|
||||
<!-- Controls Panel -->
|
||||
<div class="card mb-controls">
|
||||
<h2 class="section-title text-xl mb-md">Find Recipes</h2>
|
||||
|
|
@ -55,6 +66,7 @@
|
|||
:key="lvl.value"
|
||||
:class="['btn', 'btn-secondary', { active: recipesStore.level === lvl.value }]"
|
||||
@click="recipesStore.level = lvl.value"
|
||||
:aria-pressed="recipesStore.level === lvl.value"
|
||||
:title="lvl.description"
|
||||
>
|
||||
{{ lvl.label }}
|
||||
|
|
@ -85,8 +97,8 @@
|
|||
</button>
|
||||
|
||||
<!-- Dietary Preferences (collapsible) -->
|
||||
<details class="collapsible form-group">
|
||||
<summary class="collapsible-summary filter-summary">
|
||||
<details class="collapsible form-group" @toggle="(e: Event) => dietaryOpen = (e.target as HTMLDetailsElement).open">
|
||||
<summary class="collapsible-summary filter-summary" :aria-expanded="dietaryOpen">
|
||||
Dietary preferences
|
||||
<span v-if="dietaryActive" class="filter-active-dot" aria-label="filters active"></span>
|
||||
</summary>
|
||||
|
|
@ -162,8 +174,9 @@
|
|||
|
||||
<!-- Max Missing — hidden in shopping mode -->
|
||||
<div v-if="!recipesStore.shoppingMode" class="form-group">
|
||||
<label class="form-label">Max Missing Ingredients <span class="text-muted text-xs">(optional)</span></label>
|
||||
<label class="form-label" for="max-missing">Max Missing Ingredients <span class="text-muted text-xs">(optional)</span></label>
|
||||
<input
|
||||
id="max-missing"
|
||||
type="number"
|
||||
class="form-input"
|
||||
min="0"
|
||||
|
|
@ -177,8 +190,8 @@
|
|||
</details>
|
||||
|
||||
<!-- Advanced Filters (collapsible) -->
|
||||
<details class="collapsible form-group">
|
||||
<summary class="collapsible-summary filter-summary">
|
||||
<details class="collapsible form-group" @toggle="(e: Event) => advancedOpen = (e.target as HTMLDetailsElement).open">
|
||||
<summary class="collapsible-summary filter-summary" :aria-expanded="advancedOpen">
|
||||
Advanced filters
|
||||
<span v-if="advancedActive" class="filter-active-dot" aria-label="filters active"></span>
|
||||
</summary>
|
||||
|
|
@ -189,26 +202,26 @@
|
|||
<label class="form-label">Nutrition limits <span class="text-muted text-xs">(per recipe, optional)</span></label>
|
||||
<div class="nutrition-filters-grid mt-xs">
|
||||
<div class="form-group">
|
||||
<label class="form-label">Max Calories</label>
|
||||
<input type="number" class="form-input" min="0" placeholder="e.g. 600"
|
||||
<label class="form-label" for="filter-max-cal">Max Calories</label>
|
||||
<input id="filter-max-cal" type="number" class="form-input" min="0" placeholder="e.g. 600"
|
||||
:value="recipesStore.nutritionFilters.max_calories ?? ''"
|
||||
@input="onNutritionInput('max_calories', $event)" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Max Sugar (g)</label>
|
||||
<input type="number" class="form-input" min="0" placeholder="e.g. 10"
|
||||
<label class="form-label" for="filter-max-sugar">Max Sugar (g)</label>
|
||||
<input id="filter-max-sugar" type="number" class="form-input" min="0" placeholder="e.g. 10"
|
||||
:value="recipesStore.nutritionFilters.max_sugar_g ?? ''"
|
||||
@input="onNutritionInput('max_sugar_g', $event)" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Max Carbs (g)</label>
|
||||
<input type="number" class="form-input" min="0" placeholder="e.g. 50"
|
||||
<label class="form-label" for="filter-max-carbs">Max Carbs (g)</label>
|
||||
<input id="filter-max-carbs" type="number" class="form-input" min="0" placeholder="e.g. 50"
|
||||
:value="recipesStore.nutritionFilters.max_carbs_g ?? ''"
|
||||
@input="onNutritionInput('max_carbs_g', $event)" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">Max Sodium (mg)</label>
|
||||
<input type="number" class="form-input" min="0" placeholder="e.g. 800"
|
||||
<label class="form-label" for="filter-max-sodium">Max Sodium (mg)</label>
|
||||
<input id="filter-max-sodium" type="number" class="form-input" min="0" placeholder="e.g. 800"
|
||||
:value="recipesStore.nutritionFilters.max_sodium_mg ?? ''"
|
||||
@input="onNutritionInput('max_sodium_mg', $event)" />
|
||||
</div>
|
||||
|
|
@ -227,14 +240,16 @@
|
|||
:key="style.id"
|
||||
:class="['btn', 'btn-secondary', 'btn-sm', { active: recipesStore.styleId === style.id }]"
|
||||
@click="recipesStore.styleId = recipesStore.styleId === style.id ? null : style.id"
|
||||
:aria-pressed="recipesStore.styleId === style.id"
|
||||
>{{ style.label }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Category Filter (Level 1–2 only) -->
|
||||
<div v-if="recipesStore.level <= 2" class="form-group">
|
||||
<label class="form-label">Category <span class="text-muted text-xs">(optional)</span></label>
|
||||
<label class="form-label" for="adv-category">Category <span class="text-muted text-xs">(optional)</span></label>
|
||||
<input
|
||||
id="adv-category"
|
||||
class="form-input"
|
||||
v-model="categoryInput"
|
||||
placeholder="e.g. Breakfast, Asian, Chicken, < 30 Mins"
|
||||
|
|
@ -272,26 +287,27 @@
|
|||
</div>
|
||||
|
||||
<!-- Error -->
|
||||
<div v-if="recipesStore.error" class="status-badge status-error mb-md">
|
||||
<div v-if="recipesStore.error" role="alert" class="status-badge status-error mb-md">
|
||||
{{ recipesStore.error }}
|
||||
</div>
|
||||
|
||||
<!-- Screen reader announcement when results load -->
|
||||
<!-- Screen reader announcement for loading + results -->
|
||||
<div aria-live="polite" aria-atomic="true" class="sr-only">
|
||||
<span v-if="recipesStore.result && !recipesStore.loading">
|
||||
<span v-if="recipesStore.loading">Finding recipes…</span>
|
||||
<span v-else-if="recipesStore.result">
|
||||
{{ filteredSuggestions.length }} recipe{{ filteredSuggestions.length !== 1 ? 's' : '' }} found
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Results -->
|
||||
<div v-if="recipesStore.result" class="results-section fade-in">
|
||||
<div v-if="recipesStore.result" class="results-section fade-in" :aria-busy="recipesStore.loading">
|
||||
<!-- Rate limit warning -->
|
||||
<div
|
||||
v-if="recipesStore.result.rate_limited"
|
||||
class="status-badge status-warning rate-limit-banner mb-md"
|
||||
>
|
||||
You've used your {{ recipesStore.result.rate_limit_count }} free suggestions today. Upgrade for
|
||||
unlimited.
|
||||
Today's free suggestions are used up. Your limit resets tomorrow, or
|
||||
<a href="#" class="link-inline" @click.prevent="$emit('upgrade')">upgrade for unlimited access</a>.
|
||||
</div>
|
||||
|
||||
<!-- Element gaps -->
|
||||
|
|
@ -320,22 +336,26 @@
|
|||
v-for="lvl in availableLevels"
|
||||
:key="lvl"
|
||||
:class="['filter-chip', { active: filterLevel === lvl }]"
|
||||
:aria-pressed="filterLevel === lvl"
|
||||
@click="filterLevel = filterLevel === lvl ? null : lvl"
|
||||
>Lv{{ lvl }}</button>
|
||||
>{{ levelLabels[lvl] ?? `Level ${lvl}` }}</button>
|
||||
</template>
|
||||
<button
|
||||
:class="['filter-chip', { active: filterMissing === 0 }]"
|
||||
:aria-pressed="filterMissing === 0"
|
||||
@click="filterMissing = filterMissing === 0 ? null : 0"
|
||||
>Can make now</button>
|
||||
<button
|
||||
:class="['filter-chip', { active: filterMissing === 2 }]"
|
||||
:aria-pressed="filterMissing === 2"
|
||||
@click="filterMissing = filterMissing === 2 ? null : 2"
|
||||
>≤2 missing</button>
|
||||
<button
|
||||
v-if="hasActiveFilters"
|
||||
class="filter-chip filter-chip-clear"
|
||||
aria-label="Clear all recipe filters"
|
||||
@click="clearFilters"
|
||||
>✕ Clear</button>
|
||||
><span aria-hidden="true">✕</span> Clear</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -348,7 +368,7 @@
|
|||
<p>No recipes match your filters.</p>
|
||||
<button class="btn btn-ghost btn-sm mt-xs" @click="clearFilters">Clear filters</button>
|
||||
</template>
|
||||
<p v-else>No recipes found for your current pantry and settings. Try lowering the creativity level or adding more items.</p>
|
||||
<p v-else>We didn't find matches at this level. Try <button class="btn btn-ghost btn-sm" @click="recipesStore.level = 1; handleSuggest()">Level 1 — Use What I Have</button> or adjust your filters.</p>
|
||||
</div>
|
||||
|
||||
<!-- Recipe Cards -->
|
||||
|
|
@ -398,28 +418,28 @@
|
|||
<!-- Nutrition chips -->
|
||||
<div v-if="recipe.nutrition" class="nutrition-chips mb-sm">
|
||||
<span v-if="recipe.nutrition.calories != null" class="nutrition-chip">
|
||||
🔥 {{ Math.round(recipe.nutrition.calories) }} kcal
|
||||
<span aria-hidden="true">🔥</span><span class="sr-only">Calories:</span> {{ Math.round(recipe.nutrition.calories) }} kcal
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.fat_g != null" class="nutrition-chip">
|
||||
🧈 {{ recipe.nutrition.fat_g.toFixed(1) }}g fat
|
||||
<span aria-hidden="true">🧈</span><span class="sr-only">Fat:</span> {{ recipe.nutrition.fat_g.toFixed(1) }}g fat
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.protein_g != null" class="nutrition-chip">
|
||||
💪 {{ recipe.nutrition.protein_g.toFixed(1) }}g protein
|
||||
<span aria-hidden="true">💪</span><span class="sr-only">Protein:</span> {{ recipe.nutrition.protein_g.toFixed(1) }}g protein
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.carbs_g != null" class="nutrition-chip">
|
||||
🌾 {{ recipe.nutrition.carbs_g.toFixed(1) }}g carbs
|
||||
<span aria-hidden="true">🌾</span><span class="sr-only">Carbs:</span> {{ recipe.nutrition.carbs_g.toFixed(1) }}g carbs
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.fiber_g != null" class="nutrition-chip">
|
||||
🌿 {{ recipe.nutrition.fiber_g.toFixed(1) }}g fiber
|
||||
<span aria-hidden="true">🌿</span><span class="sr-only">Fiber:</span> {{ recipe.nutrition.fiber_g.toFixed(1) }}g fiber
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.sugar_g != null" class="nutrition-chip nutrition-chip-sugar">
|
||||
🍬 {{ recipe.nutrition.sugar_g.toFixed(1) }}g sugar
|
||||
<span aria-hidden="true">🍬</span><span class="sr-only">Sugar:</span> {{ recipe.nutrition.sugar_g.toFixed(1) }}g sugar
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.sodium_mg != null" class="nutrition-chip">
|
||||
🧂 {{ Math.round(recipe.nutrition.sodium_mg) }}mg sodium
|
||||
<span aria-hidden="true">🧂</span><span class="sr-only">Sodium:</span> {{ Math.round(recipe.nutrition.sodium_mg) }}mg sodium
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.servings != null" class="nutrition-chip nutrition-chip-servings">
|
||||
🍽️ {{ recipe.nutrition.servings }} serving{{ recipe.nutrition.servings !== 1 ? 's' : '' }}
|
||||
<span aria-hidden="true">🍽️</span><span class="sr-only">Servings:</span> {{ recipe.nutrition.servings }} serving{{ recipe.nutrition.servings !== 1 ? 's' : '' }}
|
||||
</span>
|
||||
<span v-if="recipe.nutrition.estimated" class="nutrition-chip nutrition-chip-estimated" title="Estimated from ingredient profiles">
|
||||
~ estimated
|
||||
|
|
@ -428,7 +448,7 @@
|
|||
|
||||
<!-- Missing ingredients -->
|
||||
<div v-if="recipe.missing_ingredients.length > 0" class="mb-sm">
|
||||
<p class="text-sm font-semibold text-warning">You'd need:</p>
|
||||
<p class="text-sm font-semibold text-secondary">You'd need:</p>
|
||||
<div class="flex flex-wrap gap-xs mt-xs">
|
||||
<span
|
||||
v-for="ing in recipe.missing_ingredients"
|
||||
|
|
@ -456,8 +476,12 @@
|
|||
</div>
|
||||
|
||||
<!-- Swap candidates collapsible -->
|
||||
<details v-if="recipe.swap_candidates.length > 0" class="collapsible mb-sm">
|
||||
<summary class="text-sm font-semibold collapsible-summary">
|
||||
<details
|
||||
v-if="recipe.swap_candidates.length > 0"
|
||||
class="collapsible mb-sm"
|
||||
@toggle="(e: Event) => toggleSwapOpen(recipe.id, (e.target as HTMLDetailsElement).open)"
|
||||
>
|
||||
<summary class="text-sm font-semibold collapsible-summary" :aria-expanded="openSwapIds.has(recipe.id)">
|
||||
Possible swaps ({{ recipe.swap_candidates.length }})
|
||||
</summary>
|
||||
<div class="card-secondary mt-xs">
|
||||
|
|
@ -518,6 +542,16 @@
|
|||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Soft Build Your Own nudge when corpus results are sparse -->
|
||||
<div
|
||||
v-if="!recipesStore.loading && filteredSuggestions.length <= 2 && recipesStore.result"
|
||||
class="byo-nudge text-sm text-secondary mt-md"
|
||||
>
|
||||
Not finding what you want?
|
||||
<button class="btn-link" @click="activeTab = 'build'">Try Build Your Own</button>
|
||||
to make something from scratch.
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Recipe detail panel — mounts as a full-screen overlay -->
|
||||
|
|
@ -544,6 +578,11 @@
|
|||
|
||||
</div><!-- end Find tab -->
|
||||
|
||||
<!-- Recipe load error — announced to screen readers via aria-live -->
|
||||
<div v-if="browserRecipeError" role="alert" class="status-badge status-error mb-sm">
|
||||
{{ browserRecipeError }}
|
||||
</div>
|
||||
|
||||
<!-- Detail panel for browser/saved recipe lookups -->
|
||||
<RecipeDetailPanel
|
||||
v-if="browserSelectedRecipe"
|
||||
|
|
@ -556,13 +595,15 @@
|
|||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted, nextTick, watch } from 'vue'
|
||||
import { useRecipesStore } from '../stores/recipes'
|
||||
import { useInventoryStore } from '../stores/inventory'
|
||||
import { useSavedRecipesStore } from '../stores/savedRecipes'
|
||||
import RecipeDetailPanel from './RecipeDetailPanel.vue'
|
||||
import RecipeBrowserPanel from './RecipeBrowserPanel.vue'
|
||||
import SavedRecipesPanel from './SavedRecipesPanel.vue'
|
||||
import CommunityFeedPanel from './CommunityFeedPanel.vue'
|
||||
import BuildYourOwnTab from './BuildYourOwnTab.vue'
|
||||
import type { ForkResult } from '../stores/community'
|
||||
import type { RecipeSuggestion, GroceryLink } from '../services/api'
|
||||
import { recipesAPI } from '../services/api'
|
||||
|
|
@ -571,24 +612,38 @@ const recipesStore = useRecipesStore()
|
|||
const inventoryStore = useInventoryStore()
|
||||
|
||||
// Tab state
|
||||
type TabId = 'find' | 'browse' | 'saved' | 'community'
|
||||
type TabId = 'find' | 'browse' | 'saved' | 'community' | 'build'
|
||||
const tabs: Array<{ id: TabId; label: string }> = [
|
||||
{ id: 'saved', label: 'Saved' },
|
||||
{ id: 'build', label: 'Build Your Own' },
|
||||
{ id: 'community', label: 'Community' },
|
||||
{ id: 'find', label: 'Find' },
|
||||
{ id: 'browse', label: 'Browse' },
|
||||
{ id: 'saved', label: 'Saved' },
|
||||
{ id: 'community', label: 'Community' },
|
||||
]
|
||||
const activeTab = ref<TabId>('find')
|
||||
const activeTab = ref<TabId>('saved')
|
||||
const savedStore = useSavedRecipesStore()
|
||||
// Template ref for the Find-tab panel div (used for focus management on tab switch)
|
||||
const findPanelRef = ref<HTMLElement | null>(null)
|
||||
|
||||
function onTabKeydown(e: KeyboardEvent) {
|
||||
const tabIds: TabId[] = ['find', 'browse', 'saved', 'community']
|
||||
const tabIds: TabId[] = ['saved', 'build', 'community', 'find', 'browse']
|
||||
const current = tabIds.indexOf(activeTab.value)
|
||||
if (e.key === 'ArrowRight') {
|
||||
e.preventDefault()
|
||||
activeTab.value = tabIds[(current + 1) % tabIds.length]!
|
||||
nextTick(() => {
|
||||
// Move focus to the newly active panel so keyboard users don't have to Tab
|
||||
// through the entire tab bar again to reach the panel content
|
||||
const panel = document.querySelector('[role="tabpanel"]') as HTMLElement | null
|
||||
panel?.focus()
|
||||
})
|
||||
} else if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault()
|
||||
activeTab.value = tabIds[(current - 1 + tabIds.length) % tabIds.length]!
|
||||
nextTick(() => {
|
||||
const panel = document.querySelector('[role="tabpanel"]') as HTMLElement | null
|
||||
panel?.focus()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -600,14 +655,39 @@ function onPlanForked(_payload: ForkResult) {
|
|||
// Browser/saved tab recipe detail panel (fetches full recipe from API)
|
||||
const browserSelectedRecipe = ref<RecipeSuggestion | null>(null)
|
||||
|
||||
const browserRecipeError = ref<string | null>(null)
|
||||
|
||||
async function openRecipeById(recipeId: number) {
|
||||
browserRecipeError.value = null
|
||||
try {
|
||||
browserSelectedRecipe.value = await recipesAPI.getRecipe(recipeId)
|
||||
} catch {
|
||||
// silently ignore — recipe may not exist
|
||||
browserRecipeError.value = 'Could not load this recipe. Please try again.'
|
||||
}
|
||||
}
|
||||
|
||||
// Collapsible panel open state — kept in sync with DOM toggle event so
|
||||
// :aria-expanded on <summary> reflects the actual open/closed state
|
||||
const dietaryOpen = ref(false)
|
||||
const advancedOpen = ref(false)
|
||||
|
||||
// Per-recipe swap section open tracking (Set of recipe IDs whose swap <details> are open)
|
||||
// Uses reassignment instead of .add()/.delete() so Vue's ref() detects the change
|
||||
const openSwapIds = ref<Set<number>>(new Set())
|
||||
function toggleSwapOpen(recipeId: number, isOpen: boolean) {
|
||||
const next = new Set(openSwapIds.value)
|
||||
isOpen ? next.add(recipeId) : next.delete(recipeId)
|
||||
openSwapIds.value = next
|
||||
}
|
||||
|
||||
// Human-readable level labels for filter chips (avoids "Lv1" etc. for screen readers)
|
||||
const levelLabels: Record<number, string> = {
|
||||
1: 'Use What I Have',
|
||||
2: 'Allow Swaps',
|
||||
3: 'Get Creative',
|
||||
4: 'Surprise Me',
|
||||
}
|
||||
|
||||
// Local input state for tags
|
||||
const constraintInput = ref('')
|
||||
const allergyInput = ref('')
|
||||
|
|
@ -841,10 +921,37 @@ onMounted(async () => {
|
|||
if (inventoryStore.items.length === 0) {
|
||||
await inventoryStore.fetchItems()
|
||||
}
|
||||
// Pre-load saved recipes so we know immediately whether to redirect
|
||||
await savedStore.load()
|
||||
})
|
||||
|
||||
// If Saved tab is empty after loading, bounce to Build Your Own
|
||||
watch(
|
||||
() => ({ loading: savedStore.loading, count: savedStore.saved.length }),
|
||||
({ loading, count }) => {
|
||||
if (!loading && count === 0 && activeTab.value === 'saved') {
|
||||
activeTab.value = 'build'
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.byo-nudge {
|
||||
padding: var(--spacing-sm) 0;
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--color-primary);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
text-decoration: underline;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
.tab-bar {
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
padding-bottom: var(--spacing-sm);
|
||||
|
|
@ -939,7 +1046,10 @@ onMounted(async () => {
|
|||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 2px 6px;
|
||||
/* WCAG 2.2 2.5.8: minimum 24×24px touch target */
|
||||
min-width: 24px;
|
||||
min-height: 24px;
|
||||
padding: 4px 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
color: var(--color-text-muted);
|
||||
|
|
@ -958,7 +1068,10 @@ onMounted(async () => {
|
|||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 2px 6px;
|
||||
/* WCAG 2.2 2.5.8: minimum 24×24px touch target */
|
||||
min-width: 24px;
|
||||
min-height: 24px;
|
||||
padding: 4px 6px;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
color: var(--color-text-muted);
|
||||
|
|
|
|||
|
|
@ -503,6 +503,40 @@ export interface Staple {
|
|||
dietary_tags: string[]
|
||||
}
|
||||
|
||||
// ── Build Your Own types ──────────────────────────────────────────────────
|
||||
|
||||
export interface AssemblyRoleOut {
|
||||
display: string
|
||||
required: boolean
|
||||
keywords: string[]
|
||||
hint: string
|
||||
}
|
||||
|
||||
export interface AssemblyTemplateOut {
|
||||
id: string
|
||||
title: string
|
||||
icon: string
|
||||
descriptor: string
|
||||
role_sequence: AssemblyRoleOut[]
|
||||
}
|
||||
|
||||
export interface RoleCandidateItem {
|
||||
name: string
|
||||
in_pantry: boolean
|
||||
tags: string[]
|
||||
}
|
||||
|
||||
export interface RoleCandidatesResponse {
|
||||
compatible: RoleCandidateItem[]
|
||||
other: RoleCandidateItem[]
|
||||
available_tags: string[]
|
||||
}
|
||||
|
||||
export interface BuildRequest {
|
||||
template_id: string
|
||||
role_overrides: Record<string, string>
|
||||
}
|
||||
|
||||
// ========== Recipes API ==========
|
||||
|
||||
export const recipesAPI = {
|
||||
|
|
@ -518,6 +552,28 @@ export const recipesAPI = {
|
|||
const response = await api.get('/staples/', { params: dietary ? { dietary } : undefined })
|
||||
return response.data
|
||||
},
|
||||
async getTemplates(): Promise<AssemblyTemplateOut[]> {
|
||||
const response = await api.get('/recipes/templates')
|
||||
return response.data
|
||||
},
|
||||
async getRoleCandidates(
|
||||
templateId: string,
|
||||
role: string,
|
||||
priorPicks: string[] = [],
|
||||
): Promise<RoleCandidatesResponse> {
|
||||
const response = await api.get('/recipes/template-candidates', {
|
||||
params: {
|
||||
template_id: templateId,
|
||||
role,
|
||||
prior_picks: priorPicks.join(','),
|
||||
},
|
||||
})
|
||||
return response.data
|
||||
},
|
||||
async buildRecipe(req: BuildRequest): Promise<RecipeSuggestion> {
|
||||
const response = await api.post('/recipes/build', req)
|
||||
return response.data
|
||||
},
|
||||
}
|
||||
|
||||
// ========== Settings API ==========
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
*/
|
||||
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { recipesAPI, type RecipeResult, type RecipeSuggestion, type RecipeRequest, type NutritionFilters } from '../services/api'
|
||||
|
||||
const DISMISSED_KEY = 'kiwi:dismissed_recipes'
|
||||
|
|
@ -18,6 +18,12 @@ const COOK_LOG_MAX = 200
|
|||
const BOOKMARKS_KEY = 'kiwi:bookmarks'
|
||||
const BOOKMARKS_MAX = 50
|
||||
|
||||
const MISSING_MODE_KEY = 'kiwi:builder_missing_mode'
|
||||
const FILTER_MODE_KEY = 'kiwi:builder_filter_mode'
|
||||
|
||||
type MissingIngredientMode = 'hidden' | 'greyed' | 'add-to-cart'
|
||||
type BuilderFilterMode = 'text' | 'tags'
|
||||
|
||||
// [id, dismissedAtMs]
|
||||
type DismissEntry = [number, number]
|
||||
|
||||
|
|
@ -71,6 +77,16 @@ function saveBookmarks(bookmarks: RecipeSuggestion[]) {
|
|||
localStorage.setItem(BOOKMARKS_KEY, JSON.stringify(bookmarks.slice(0, BOOKMARKS_MAX)))
|
||||
}
|
||||
|
||||
function loadMissingMode(): MissingIngredientMode {
|
||||
const raw = localStorage.getItem(MISSING_MODE_KEY)
|
||||
if (raw === 'hidden' || raw === 'greyed' || raw === 'add-to-cart') return raw
|
||||
return 'greyed'
|
||||
}
|
||||
|
||||
function loadFilterMode(): BuilderFilterMode {
|
||||
return localStorage.getItem(FILTER_MODE_KEY) === 'tags' ? 'tags' : 'text'
|
||||
}
|
||||
|
||||
export const useRecipesStore = defineStore('recipes', () => {
|
||||
// Suggestion result state
|
||||
const result = ref<RecipeResult | null>(null)
|
||||
|
|
@ -103,6 +119,14 @@ export const useRecipesStore = defineStore('recipes', () => {
|
|||
// Bookmarks: full RecipeSuggestion snapshots, max BOOKMARKS_MAX
|
||||
const bookmarks = ref<RecipeSuggestion[]>(loadBookmarks())
|
||||
|
||||
// Build Your Own wizard preferences -- persisted across sessions
|
||||
const missingIngredientMode = ref<MissingIngredientMode>(loadMissingMode())
|
||||
const builderFilterMode = ref<BuilderFilterMode>(loadFilterMode())
|
||||
|
||||
// Persist wizard prefs on change
|
||||
watch(missingIngredientMode, (val) => localStorage.setItem(MISSING_MODE_KEY, val))
|
||||
watch(builderFilterMode, (val) => localStorage.setItem(FILTER_MODE_KEY, val))
|
||||
|
||||
const dismissedCount = computed(() => dismissedIds.value.size)
|
||||
|
||||
function _buildRequest(pantryItems: string[], extraExcluded: number[] = []): RecipeRequest {
|
||||
|
|
@ -246,6 +270,8 @@ export const useRecipesStore = defineStore('recipes', () => {
|
|||
isBookmarked,
|
||||
toggleBookmark,
|
||||
clearBookmarks,
|
||||
missingIngredientMode,
|
||||
builderFilterMode,
|
||||
suggest,
|
||||
loadMore,
|
||||
dismiss,
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@
|
|||
/* Theme Colors - Dark Mode (Default) */
|
||||
--color-text-primary: rgba(255, 248, 235, 0.92);
|
||||
--color-text-secondary: rgba(255, 248, 235, 0.60);
|
||||
--color-text-muted: rgba(255, 248, 235, 0.38);
|
||||
/* Raised from 0.38 → 0.52 for WCAG 1.4.3 AA compliance (~5.5:1 against card bg) */
|
||||
--color-text-muted: rgba(255, 248, 235, 0.52);
|
||||
|
||||
--color-bg-primary: #1e1c1a;
|
||||
--color-bg-secondary: #161412;
|
||||
|
|
@ -40,7 +41,8 @@
|
|||
/* Status Colors */
|
||||
--color-success: #4a8c40;
|
||||
--color-success-dark: #3a7030;
|
||||
--color-success-light: #6aac60;
|
||||
/* Lightened from #6aac60 → #7fc073 for WCAG 1.4.3 AA compliance on dark backgrounds */
|
||||
--color-success-light: #7fc073;
|
||||
--color-success-bg: rgba(74, 140, 64, 0.12);
|
||||
--color-success-border: rgba(74, 140, 64, 0.30);
|
||||
|
||||
|
|
|
|||
118
scripts/backfill_keywords.py
Normal file
118
scripts/backfill_keywords.py
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Backfill keywords column: repair character-split R-vector data.
|
||||
|
||||
The food.com corpus was imported with Keywords stored as a JSON array of
|
||||
individual characters (e.g. ["c","(","\"","I","t","a","l","i","a","n",...])
|
||||
instead of the intended keyword list (e.g. ["Italian","Low-Fat","Easy"]).
|
||||
|
||||
This script detects the broken pattern (all array elements have length 1),
|
||||
rejoins them into the original R-vector string, parses quoted tokens, and
|
||||
writes the corrected JSON back.
|
||||
|
||||
Rows that are already correct (empty array, or multi-char strings) are skipped.
|
||||
FTS5 index is rebuilt after the update so searches reflect the fix.
|
||||
|
||||
Usage:
|
||||
conda run -n cf python scripts/backfill_keywords.py [path/to/kiwi.db]
|
||||
# default: data/kiwi.db
|
||||
|
||||
Estimated time on 3.1M rows: 3-8 minutes (mostly the FTS rebuild at the end).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_QUOTED = re.compile(r'"([^"]*)"')
|
||||
|
||||
|
||||
def _parse_r_vector(s: str) -> list[str]:
|
||||
return _QUOTED.findall(s)
|
||||
|
||||
|
||||
def _repair(raw_json: str) -> str | None:
|
||||
"""Return corrected JSON string, or None if the row is already clean."""
|
||||
try:
|
||||
val = json.loads(raw_json)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
|
||||
if not isinstance(val, list) or not val:
|
||||
return None # empty or non-list — leave as-is
|
||||
|
||||
# Already correct: contains multi-character strings
|
||||
if any(isinstance(e, str) and len(e) > 1 for e in val):
|
||||
return None
|
||||
|
||||
# Broken: all single characters — rejoin and re-parse
|
||||
if all(isinstance(e, str) and len(e) == 1 for e in val):
|
||||
rejoined = "".join(val)
|
||||
keywords = _parse_r_vector(rejoined)
|
||||
return json.dumps(keywords)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def backfill(db_path: Path, batch_size: int = 5000) -> None:
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
|
||||
total = conn.execute("SELECT count(*) FROM recipes").fetchone()[0]
|
||||
print(f"Total recipes: {total:,}")
|
||||
|
||||
fixed = 0
|
||||
skipped = 0
|
||||
offset = 0
|
||||
|
||||
while True:
|
||||
rows = conn.execute(
|
||||
"SELECT id, keywords FROM recipes LIMIT ? OFFSET ?",
|
||||
(batch_size, offset),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
break
|
||||
|
||||
updates: list[tuple[str, int]] = []
|
||||
for row_id, raw_json in rows:
|
||||
corrected = _repair(raw_json)
|
||||
if corrected is not None:
|
||||
updates.append((corrected, row_id))
|
||||
else:
|
||||
skipped += 1
|
||||
|
||||
if updates:
|
||||
conn.executemany(
|
||||
"UPDATE recipes SET keywords = ? WHERE id = ?", updates
|
||||
)
|
||||
conn.commit()
|
||||
fixed += len(updates)
|
||||
|
||||
offset += batch_size
|
||||
done = offset + len(rows) - (batch_size - len(rows))
|
||||
pct = min(100, int((offset / total) * 100))
|
||||
print(f" {pct:>3}% processed {offset:,} fixed {fixed:,} skipped {skipped:,}", end="\r")
|
||||
|
||||
print(f"\nDone. Fixed {fixed:,} rows, skipped {skipped:,} (already correct or empty).")
|
||||
|
||||
if fixed > 0:
|
||||
print("Rebuilding FTS5 browser index (recipe_browser_fts)…")
|
||||
try:
|
||||
conn.execute("INSERT INTO recipe_browser_fts(recipe_browser_fts) VALUES('rebuild')")
|
||||
conn.commit()
|
||||
print("FTS rebuild complete.")
|
||||
except Exception as e:
|
||||
print(f"FTS rebuild skipped (table may not exist yet): {e}")
|
||||
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
db_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("data/kiwi.db")
|
||||
if not db_path.exists():
|
||||
print(f"DB not found: {db_path}")
|
||||
sys.exit(1)
|
||||
backfill(db_path)
|
||||
|
|
@ -57,6 +57,34 @@ def _parse_r_vector(s: str) -> list[str]:
|
|||
return _QUOTED.findall(s)
|
||||
|
||||
|
||||
def _parse_keywords(val: object) -> list[str]:
|
||||
"""Parse the food.com Keywords column into a proper list of keyword strings.
|
||||
|
||||
The raw parquet value can arrive in three forms:
|
||||
- None / NaN → []
|
||||
- str: c("Italian", ...) → parse quoted tokens via _parse_r_vector
|
||||
- list of single chars → the R-vector was character-split during dataset
|
||||
export; rejoin then re-parse
|
||||
- list of strings → already correct, use as-is
|
||||
"""
|
||||
import math
|
||||
if val is None:
|
||||
return []
|
||||
if isinstance(val, float) and math.isnan(val):
|
||||
return []
|
||||
if isinstance(val, str):
|
||||
return _parse_r_vector(val)
|
||||
if isinstance(val, list):
|
||||
if not val:
|
||||
return []
|
||||
# Detect character-split R-vector: every element is a single character
|
||||
if all(isinstance(e, str) and len(e) == 1 for e in val):
|
||||
return _parse_r_vector("".join(val))
|
||||
# Already a proper list of keyword strings
|
||||
return [str(e) for e in val if e]
|
||||
return []
|
||||
|
||||
|
||||
def extract_ingredient_names(raw_list: list[str]) -> list[str]:
|
||||
"""Strip quantities and units from ingredient strings -> normalized names."""
|
||||
names = []
|
||||
|
|
@ -168,7 +196,7 @@ def build(db_path: Path, recipes_path: Path, batch_size: int = 10000) -> None:
|
|||
json.dumps(ingredient_names),
|
||||
json.dumps(directions),
|
||||
str(row.get("RecipeCategory", "") or ""),
|
||||
json.dumps(_safe_list(row.get("Keywords"))),
|
||||
json.dumps(_parse_keywords(row.get("Keywords"))),
|
||||
_float_or_none(row.get("Calories")),
|
||||
_float_or_none(row.get("FatContent")),
|
||||
_float_or_none(row.get("ProteinContent")),
|
||||
|
|
|
|||
255
scripts/pipeline/infer_recipe_tags.py
Normal file
255
scripts/pipeline/infer_recipe_tags.py
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
"""
|
||||
Infer and backfill normalized tags for all recipes.
|
||||
|
||||
Reads recipes in batches, cross-references ingredient_profiles and
|
||||
substitution_pairs, runs tag_inferrer on each recipe, and writes the result
|
||||
to recipes.inferred_tags. Also rebuilds recipe_browser_fts after the run.
|
||||
|
||||
This script is idempotent: pass --force to re-derive tags even if
|
||||
inferred_tags is already non-empty.
|
||||
|
||||
Usage:
|
||||
conda run -n cf python scripts/pipeline/infer_recipe_tags.py \\
|
||||
[path/to/kiwi.db] [--batch-size 2000] [--force]
|
||||
|
||||
Estimated time on 3.1M rows: 10-20 minutes (CPU-bound text matching).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Allow importing from the app package when run from the repo root
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from app.services.recipe.tag_inferrer import infer_tags
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Substitution constraint label mapping
|
||||
# Keys are what we store in substitution_pairs.constraint_label.
|
||||
# ---------------------------------------------------------------------------
|
||||
_INTERESTING_CONSTRAINTS = {"gluten_free", "low_calorie", "low_carb", "vegan", "dairy_free", "low_sodium"}
|
||||
|
||||
|
||||
def _load_profiles(conn: sqlite3.Connection) -> dict[str, dict]:
|
||||
"""
|
||||
Load ingredient_profiles into a dict keyed by name.
|
||||
Values hold only the fields we need for tag inference.
|
||||
"""
|
||||
profiles: dict[str, dict] = {}
|
||||
rows = conn.execute("""
|
||||
SELECT name, elements, glutamate_mg, is_fermented, ph_estimate
|
||||
FROM ingredient_profiles
|
||||
""").fetchall()
|
||||
for name, elements_json, glutamate_mg, is_fermented, ph_estimate in rows:
|
||||
try:
|
||||
elements: list[str] = json.loads(elements_json) if elements_json else []
|
||||
except Exception:
|
||||
elements = []
|
||||
profiles[name] = {
|
||||
"elements": elements,
|
||||
"glutamate": float(glutamate_mg or 0),
|
||||
"fermented": bool(is_fermented),
|
||||
"ph": float(ph_estimate) if ph_estimate is not None else None,
|
||||
}
|
||||
return profiles
|
||||
|
||||
|
||||
def _load_sub_index(conn: sqlite3.Connection) -> dict[str, set[str]]:
|
||||
"""
|
||||
Build a dict of ingredient_name -> set of available constraint labels.
|
||||
Only loads constraints we care about.
|
||||
"""
|
||||
index: dict[str, set[str]] = {}
|
||||
placeholders = ",".join("?" * len(_INTERESTING_CONSTRAINTS))
|
||||
rows = conn.execute(
|
||||
f"SELECT original_name, constraint_label FROM substitution_pairs "
|
||||
f"WHERE constraint_label IN ({placeholders})",
|
||||
list(_INTERESTING_CONSTRAINTS),
|
||||
).fetchall()
|
||||
for name, label in rows:
|
||||
index.setdefault(name, set()).add(label)
|
||||
return index
|
||||
|
||||
|
||||
def _enrich(
|
||||
ingredient_names: list[str],
|
||||
profile_index: dict[str, dict],
|
||||
sub_index: dict[str, set[str]],
|
||||
) -> dict:
|
||||
"""
|
||||
Cross-reference ingredient_names against our enrichment indices.
|
||||
Returns a dict of enriched signals ready for infer_tags().
|
||||
"""
|
||||
fermented_count = 0
|
||||
glutamate_total = 0.0
|
||||
ph_values: list[float] = []
|
||||
element_totals: dict[str, float] = {}
|
||||
profiled = 0
|
||||
constraint_sets: list[set[str]] = []
|
||||
|
||||
for name in ingredient_names:
|
||||
profile = profile_index.get(name)
|
||||
if profile:
|
||||
profiled += 1
|
||||
glutamate_total += profile["glutamate"]
|
||||
if profile["fermented"]:
|
||||
fermented_count += 1
|
||||
if profile["ph"] is not None:
|
||||
ph_values.append(profile["ph"])
|
||||
for elem in profile["elements"]:
|
||||
element_totals[elem] = element_totals.get(elem, 0.0) + 1.0
|
||||
|
||||
subs = sub_index.get(name)
|
||||
if subs:
|
||||
constraint_sets.append(subs)
|
||||
|
||||
# Element coverage: fraction of profiled ingredients that carry each element
|
||||
element_coverage: dict[str, float] = {}
|
||||
if profiled > 0:
|
||||
element_coverage = {e: round(c / profiled, 3) for e, c in element_totals.items()}
|
||||
|
||||
# Only emit a can_be:* tag if ALL relevant ingredients have the substitution available.
|
||||
# (A recipe is gluten_free-achievable only if every gluten source can be swapped.)
|
||||
# We use a simpler heuristic: if at least one ingredient has the constraint, flag it.
|
||||
# Future improvement: require coverage of all gluten-bearing ingredients.
|
||||
available_constraints: list[str] = []
|
||||
if constraint_sets:
|
||||
union_constraints: set[str] = set()
|
||||
for cs in constraint_sets:
|
||||
union_constraints.update(cs)
|
||||
available_constraints = sorted(union_constraints & _INTERESTING_CONSTRAINTS)
|
||||
|
||||
return {
|
||||
"element_coverage": element_coverage,
|
||||
"fermented_count": fermented_count,
|
||||
"glutamate_total": glutamate_total,
|
||||
"ph_min": min(ph_values) if ph_values else None,
|
||||
"available_sub_constraints": available_constraints,
|
||||
}
|
||||
|
||||
|
||||
def run(db_path: Path, batch_size: int = 2000, force: bool = False) -> None:
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
|
||||
total = conn.execute("SELECT count(*) FROM recipes").fetchone()[0]
|
||||
print(f"Total recipes: {total:,}")
|
||||
print("Loading ingredient profiles...")
|
||||
profile_index = _load_profiles(conn)
|
||||
print(f" {len(profile_index):,} profiles loaded")
|
||||
print("Loading substitution index...")
|
||||
sub_index = _load_sub_index(conn)
|
||||
print(f" {len(sub_index):,} substitutable ingredients indexed")
|
||||
|
||||
updated = 0
|
||||
skipped = 0
|
||||
offset = 0
|
||||
|
||||
where_clause = "" if force else "WHERE inferred_tags = '[]' OR inferred_tags IS NULL"
|
||||
|
||||
eligible = conn.execute(
|
||||
f"SELECT count(*) FROM recipes {where_clause}"
|
||||
).fetchone()[0]
|
||||
print(f"Recipes to process: {eligible:,} ({'all' if force else 'untagged only'})")
|
||||
|
||||
while True:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT id, title, ingredient_names, category, keywords,
|
||||
element_coverage,
|
||||
calories, fat_g, protein_g, carbs_g, servings
|
||||
FROM recipes {where_clause}
|
||||
ORDER BY id
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(batch_size, offset),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
break
|
||||
|
||||
updates: list[tuple[str, int]] = []
|
||||
for (row_id, title, ingr_json, category, kw_json,
|
||||
elem_cov_json, calories, fat_g, protein_g, carbs_g, servings) in rows:
|
||||
try:
|
||||
ingredient_names: list[str] = json.loads(ingr_json) if ingr_json else []
|
||||
corpus_keywords: list[str] = json.loads(kw_json) if kw_json else []
|
||||
element_coverage: dict[str, float] = (
|
||||
json.loads(elem_cov_json) if elem_cov_json else {}
|
||||
)
|
||||
except Exception:
|
||||
ingredient_names = []
|
||||
corpus_keywords = []
|
||||
element_coverage = {}
|
||||
|
||||
enriched = _enrich(ingredient_names, profile_index, sub_index)
|
||||
# Prefer the pre-computed element_coverage from the recipes table
|
||||
# (it was computed over all ingredients at import time, not just the
|
||||
# profiled subset). Fall back to what _enrich computed.
|
||||
effective_coverage = element_coverage or enriched["element_coverage"]
|
||||
|
||||
tags = infer_tags(
|
||||
title=title or "",
|
||||
ingredient_names=ingredient_names,
|
||||
corpus_keywords=corpus_keywords,
|
||||
corpus_category=category or "",
|
||||
element_coverage=effective_coverage,
|
||||
fermented_count=enriched["fermented_count"],
|
||||
glutamate_total=enriched["glutamate_total"],
|
||||
ph_min=enriched["ph_min"],
|
||||
available_sub_constraints=enriched["available_sub_constraints"],
|
||||
calories=calories,
|
||||
protein_g=protein_g,
|
||||
fat_g=fat_g,
|
||||
carbs_g=carbs_g,
|
||||
servings=servings,
|
||||
)
|
||||
updates.append((json.dumps(tags), row_id))
|
||||
|
||||
if updates:
|
||||
conn.executemany(
|
||||
"UPDATE recipes SET inferred_tags = ? WHERE id = ?", updates
|
||||
)
|
||||
conn.commit()
|
||||
updated += len(updates)
|
||||
else:
|
||||
skipped += len(rows)
|
||||
|
||||
offset += len(rows)
|
||||
pct = min(100, int((offset / eligible) * 100)) if eligible else 100
|
||||
print(
|
||||
f" {pct:>3}% offset {offset:,} tagged {updated:,}",
|
||||
end="\r",
|
||||
)
|
||||
|
||||
print(f"\nDone. Tagged {updated:,} recipes, skipped {skipped:,}.")
|
||||
|
||||
if updated > 0:
|
||||
print("Rebuilding FTS5 browser index (recipe_browser_fts)...")
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO recipe_browser_fts(recipe_browser_fts) VALUES('rebuild')"
|
||||
)
|
||||
conn.commit()
|
||||
print("FTS rebuild complete.")
|
||||
except Exception as e:
|
||||
print(f"FTS rebuild skipped: {e}")
|
||||
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("db", nargs="?", default="data/kiwi.db", type=Path)
|
||||
parser.add_argument("--batch-size", type=int, default=2000)
|
||||
parser.add_argument("--force", action="store_true",
|
||||
help="Re-derive tags even if inferred_tags is already set.")
|
||||
args = parser.parse_args()
|
||||
if not args.db.exists():
|
||||
print(f"DB not found: {args.db}")
|
||||
sys.exit(1)
|
||||
run(args.db, args.batch_size, args.force)
|
||||
|
|
@ -70,3 +70,14 @@ def test_local_feed_returns_json():
|
|||
response = client.get("/api/v1/community/local-feed")
|
||||
assert response.status_code == 200
|
||||
assert isinstance(response.json(), list)
|
||||
|
||||
|
||||
def test_hall_of_chaos_route_exists():
|
||||
"""GET /community/hall-of-chaos returns 200 and includes chaos_level key."""
|
||||
mock_store = MagicMock()
|
||||
mock_store.list_posts.return_value = []
|
||||
with patch("app.api.endpoints.community._community_store", mock_store):
|
||||
response = client.get("/api/v1/community/hall-of-chaos")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "chaos_level" in data
|
||||
|
|
|
|||
77
tests/api/test_recipe_build_endpoints.py
Normal file
77
tests/api/test_recipe_build_endpoints.py
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
"""Tests for GET /templates, GET /template-candidates, POST /build endpoints."""
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(tmp_path):
|
||||
"""FastAPI test client with a seeded in-memory DB."""
|
||||
import os
|
||||
os.environ["KIWI_DB_PATH"] = str(tmp_path / "test.db")
|
||||
os.environ["CLOUD_MODE"] = "false"
|
||||
from app.main import app
|
||||
from app.db.store import Store
|
||||
store = Store(tmp_path / "test.db")
|
||||
store.conn.execute(
|
||||
"INSERT INTO products (name, barcode) VALUES (?,?)", ("chicken breast", None)
|
||||
)
|
||||
store.conn.execute(
|
||||
"INSERT INTO inventory_items (product_id, location, status) VALUES (1,'pantry','available')"
|
||||
)
|
||||
store.conn.execute(
|
||||
"INSERT INTO products (name, barcode) VALUES (?,?)", ("flour tortilla", None)
|
||||
)
|
||||
store.conn.execute(
|
||||
"INSERT INTO inventory_items (product_id, location, status) VALUES (2,'pantry','available')"
|
||||
)
|
||||
store.conn.commit()
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_get_templates_returns_13(client):
|
||||
resp = client.get("/api/v1/recipes/templates")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data) == 13
|
||||
|
||||
|
||||
def test_get_templates_shape(client):
|
||||
resp = client.get("/api/v1/recipes/templates")
|
||||
t = next(t for t in resp.json() if t["id"] == "burrito_taco")
|
||||
assert t["icon"] == "🌯"
|
||||
assert len(t["role_sequence"]) >= 2
|
||||
assert t["role_sequence"][0]["required"] is True
|
||||
|
||||
|
||||
def test_get_template_candidates_returns_shape(client):
|
||||
resp = client.get(
|
||||
"/api/v1/recipes/template-candidates",
|
||||
params={"template_id": "burrito_taco", "role": "tortilla or wrap"}
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "compatible" in data
|
||||
assert "other" in data
|
||||
assert "available_tags" in data
|
||||
|
||||
|
||||
def test_post_build_returns_recipe(client):
|
||||
resp = client.post("/api/v1/recipes/build", json={
|
||||
"template_id": "burrito_taco",
|
||||
"role_overrides": {
|
||||
"tortilla or wrap": "flour tortilla",
|
||||
"protein": "chicken breast",
|
||||
}
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["id"] == -1
|
||||
assert len(data["directions"]) > 0
|
||||
|
||||
|
||||
def test_post_build_unknown_template_returns_404(client):
|
||||
resp = client.post("/api/v1/recipes/build", json={
|
||||
"template_id": "does_not_exist",
|
||||
"role_overrides": {}
|
||||
})
|
||||
assert resp.status_code == 404
|
||||
|
|
@ -42,3 +42,15 @@ def test_check_rate_limit_exceeded(store_with_recipes):
|
|||
allowed, count = store_with_recipes.check_and_increment_rate_limit("leftover_mode", daily_max=5)
|
||||
assert allowed is False
|
||||
assert count == 5
|
||||
|
||||
|
||||
def test_get_element_profiles_returns_known_items(store_with_profiles):
|
||||
profiles = store_with_profiles.get_element_profiles(["butter", "parmesan", "unknown_item"])
|
||||
assert profiles["butter"] == ["Richness"]
|
||||
assert "Depth" in profiles["parmesan"]
|
||||
assert "unknown_item" not in profiles
|
||||
|
||||
|
||||
def test_get_element_profiles_empty_list(store_with_profiles):
|
||||
profiles = store_with_profiles.get_element_profiles([])
|
||||
assert profiles == {}
|
||||
|
|
|
|||
216
tests/services/recipe/test_assembly_build.py
Normal file
216
tests/services/recipe/test_assembly_build.py
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
"""Tests for Build Your Own recipe assembly schemas."""
|
||||
import pytest
|
||||
from app.models.schemas.recipe import (
|
||||
AssemblyRoleOut,
|
||||
AssemblyTemplateOut,
|
||||
RoleCandidateItem,
|
||||
RoleCandidatesResponse,
|
||||
BuildRequest,
|
||||
)
|
||||
|
||||
|
||||
def test_assembly_role_out_schema():
|
||||
"""Test AssemblyRoleOut schema creation and field access."""
|
||||
role = AssemblyRoleOut(
|
||||
display="protein",
|
||||
required=True,
|
||||
keywords=["chicken"],
|
||||
hint="Main ingredient"
|
||||
)
|
||||
assert role.display == "protein"
|
||||
assert role.required is True
|
||||
assert role.keywords == ["chicken"]
|
||||
assert role.hint == "Main ingredient"
|
||||
|
||||
|
||||
def test_assembly_template_out_schema():
|
||||
"""Test AssemblyTemplateOut schema with nested roles."""
|
||||
tmpl = AssemblyTemplateOut(
|
||||
id="burrito_taco",
|
||||
title="Burrito / Taco",
|
||||
icon="🌯",
|
||||
descriptor="Protein, veg, and sauce in a tortilla or over rice",
|
||||
role_sequence=[
|
||||
AssemblyRoleOut(
|
||||
display="base",
|
||||
required=True,
|
||||
keywords=["tortilla"],
|
||||
hint="The wrap"
|
||||
),
|
||||
],
|
||||
)
|
||||
assert tmpl.id == "burrito_taco"
|
||||
assert tmpl.title == "Burrito / Taco"
|
||||
assert tmpl.icon == "🌯"
|
||||
assert len(tmpl.role_sequence) == 1
|
||||
assert tmpl.role_sequence[0].display == "base"
|
||||
|
||||
|
||||
def test_role_candidate_item_schema():
|
||||
"""Test RoleCandidateItem schema with tags."""
|
||||
item = RoleCandidateItem(
|
||||
name="bell pepper",
|
||||
in_pantry=True,
|
||||
tags=["sweet", "vegetable"]
|
||||
)
|
||||
assert item.name == "bell pepper"
|
||||
assert item.in_pantry is True
|
||||
assert "sweet" in item.tags
|
||||
|
||||
|
||||
def test_role_candidates_response_schema():
|
||||
"""Test RoleCandidatesResponse with compatible and other candidates."""
|
||||
resp = RoleCandidatesResponse(
|
||||
compatible=[
|
||||
RoleCandidateItem(name="bell pepper", in_pantry=True, tags=["sweet"])
|
||||
],
|
||||
other=[
|
||||
RoleCandidateItem(
|
||||
name="corn",
|
||||
in_pantry=False,
|
||||
tags=["sweet", "starchy"]
|
||||
)
|
||||
],
|
||||
available_tags=["sweet", "starchy"],
|
||||
)
|
||||
assert len(resp.compatible) == 1
|
||||
assert resp.compatible[0].name == "bell pepper"
|
||||
assert len(resp.other) == 1
|
||||
assert "sweet" in resp.available_tags
|
||||
assert "starchy" in resp.available_tags
|
||||
|
||||
|
||||
def test_build_request_schema():
|
||||
"""Test BuildRequest schema with template and role overrides."""
|
||||
req = BuildRequest(
|
||||
template_id="burrito_taco",
|
||||
role_overrides={"protein": "chicken", "sauce": "verde"}
|
||||
)
|
||||
assert req.template_id == "burrito_taco"
|
||||
assert req.role_overrides["protein"] == "chicken"
|
||||
assert req.role_overrides["sauce"] == "verde"
|
||||
|
||||
|
||||
def test_role_candidates_response_defaults():
|
||||
"""Test RoleCandidatesResponse with default factory fields."""
|
||||
resp = RoleCandidatesResponse()
|
||||
assert resp.compatible == []
|
||||
assert resp.other == []
|
||||
assert resp.available_tags == []
|
||||
|
||||
|
||||
def test_build_request_defaults():
|
||||
"""Test BuildRequest with default role_overrides."""
|
||||
req = BuildRequest(template_id="test_template")
|
||||
assert req.template_id == "test_template"
|
||||
assert req.role_overrides == {}
|
||||
|
||||
|
||||
def test_get_templates_for_api_returns_13():
|
||||
from app.services.recipe.assembly_recipes import get_templates_for_api
|
||||
templates = get_templates_for_api()
|
||||
assert len(templates) == 13
|
||||
|
||||
|
||||
def test_get_templates_for_api_shape():
|
||||
from app.services.recipe.assembly_recipes import get_templates_for_api
|
||||
templates = get_templates_for_api()
|
||||
t = next(t for t in templates if t["id"] == "burrito_taco")
|
||||
assert t["title"] == "Burrito / Taco"
|
||||
assert t["icon"] == "🌯"
|
||||
assert isinstance(t["role_sequence"], list)
|
||||
assert len(t["role_sequence"]) >= 1
|
||||
role = t["role_sequence"][0]
|
||||
assert "display" in role
|
||||
assert "required" in role
|
||||
assert "keywords" in role
|
||||
assert "hint" in role
|
||||
|
||||
|
||||
def test_get_templates_for_api_all_have_slugs():
|
||||
from app.services.recipe.assembly_recipes import get_templates_for_api
|
||||
templates = get_templates_for_api()
|
||||
slugs = {t["id"] for t in templates}
|
||||
assert len(slugs) == 13
|
||||
assert all(isinstance(s, str) and len(s) > 3 for s in slugs)
|
||||
|
||||
|
||||
def test_get_role_candidates_splits_compatible_other():
|
||||
from app.services.recipe.assembly_recipes import get_role_candidates
|
||||
profile_index = {
|
||||
"rice": ["Starch", "Structure"],
|
||||
"chicken": ["Protein"],
|
||||
"broccoli": ["Vegetable"],
|
||||
}
|
||||
result = get_role_candidates(
|
||||
template_slug="stir_fry",
|
||||
role_display="protein",
|
||||
pantry_set={"rice", "chicken", "broccoli"},
|
||||
prior_picks=["rice"],
|
||||
profile_index=profile_index,
|
||||
)
|
||||
assert isinstance(result["compatible"], list)
|
||||
assert isinstance(result["other"], list)
|
||||
assert isinstance(result["available_tags"], list)
|
||||
all_names = [c["name"] for c in result["compatible"] + result["other"]]
|
||||
assert "chicken" in all_names
|
||||
|
||||
|
||||
def test_get_role_candidates_available_tags():
|
||||
from app.services.recipe.assembly_recipes import get_role_candidates
|
||||
profile_index = {
|
||||
"chicken": ["Protein", "Umami"],
|
||||
"tofu": ["Protein"],
|
||||
}
|
||||
result = get_role_candidates(
|
||||
template_slug="stir_fry",
|
||||
role_display="protein",
|
||||
pantry_set={"chicken", "tofu"},
|
||||
prior_picks=[],
|
||||
profile_index=profile_index,
|
||||
)
|
||||
assert "Protein" in result["available_tags"]
|
||||
|
||||
|
||||
def test_get_role_candidates_unknown_template_returns_empty():
|
||||
from app.services.recipe.assembly_recipes import get_role_candidates
|
||||
result = get_role_candidates(
|
||||
template_slug="nonexistent_template",
|
||||
role_display="protein",
|
||||
pantry_set={"chicken"},
|
||||
prior_picks=[],
|
||||
profile_index={},
|
||||
)
|
||||
assert result == {"compatible": [], "other": [], "available_tags": []}
|
||||
|
||||
|
||||
def test_build_from_selection_returns_recipe():
|
||||
from app.services.recipe.assembly_recipes import build_from_selection
|
||||
result = build_from_selection(
|
||||
template_slug="burrito_taco",
|
||||
role_overrides={"tortilla or wrap": "flour tortilla", "protein": "chicken"},
|
||||
pantry_set={"flour tortilla", "chicken", "salsa"},
|
||||
)
|
||||
assert result is not None
|
||||
assert len(result.directions) > 0
|
||||
assert result.id == -1
|
||||
|
||||
|
||||
def test_build_from_selection_missing_required_role_returns_none():
|
||||
from app.services.recipe.assembly_recipes import build_from_selection
|
||||
result = build_from_selection(
|
||||
template_slug="burrito_taco",
|
||||
role_overrides={"protein": "chicken"},
|
||||
pantry_set={"chicken"},
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_build_from_selection_unknown_template_returns_none():
|
||||
from app.services.recipe.assembly_recipes import build_from_selection
|
||||
result = build_from_selection(
|
||||
template_slug="does_not_exist",
|
||||
role_overrides={},
|
||||
pantry_set={"chicken"},
|
||||
)
|
||||
assert result is None
|
||||
|
|
@ -119,3 +119,18 @@ def test_grocery_links_free_tier(store_with_recipes):
|
|||
assert hasattr(link, "ingredient")
|
||||
assert hasattr(link, "retailer")
|
||||
assert hasattr(link, "url")
|
||||
|
||||
|
||||
def test_suggest_returns_no_assembly_results(store_with_recipes):
|
||||
"""Assembly templates (negative IDs) must no longer appear in suggest() output."""
|
||||
from app.services.recipe.recipe_engine import RecipeEngine
|
||||
from app.models.schemas.recipe import RecipeRequest
|
||||
engine = RecipeEngine(store_with_recipes)
|
||||
req = RecipeRequest(
|
||||
pantry_items=["flour tortilla", "chicken", "salsa", "rice"],
|
||||
level=1,
|
||||
constraints=[],
|
||||
)
|
||||
result = engine.suggest(req)
|
||||
assembly_ids = [s.id for s in result.suggestions if s.id < 0]
|
||||
assert assembly_ids == [], f"Found assembly results in suggest(): {assembly_ids}"
|
||||
|
|
|
|||
Loading…
Reference in a new issue