diff --git a/.env.example b/.env.example index 1723c12..f0f6415 100644 --- a/.env.example +++ b/.env.example @@ -11,33 +11,6 @@ DATA_DIR=./data # Database (defaults to DATA_DIR/kiwi.db) # DB_PATH=./data/kiwi.db -# Pipeline data directory for downloaded parquets (used by download_datasets.py) -# Override to store large datasets on a separate drive or NAS -# KIWI_PIPELINE_DATA_DIR=./data/pipeline - -# CF-core resource coordinator (VRAM lease management) -# Set to the coordinator URL when running alongside cf-core orchestration -# COORDINATOR_URL=http://localhost:7700 -# IP this machine advertises to the coordinator (must be reachable from coordinator host) -# CF_ORCH_ADVERTISE_HOST=10.1.10.71 - -# CF-core hosted coordinator (managed cloud GPU inference — Paid+ tier) -# Set CF_ORCH_URL to use a hosted cf-orch coordinator instead of self-hosting. -# CF_LICENSE_KEY is read automatically by CFOrchClient for bearer auth. -# CF_ORCH_URL=https://orch.circuitforge.tech -# CF_LICENSE_KEY=CFG-KIWI-xxxx-xxxx-xxxx - -# LLM backend — env-var auto-config (no llm.yaml needed for bare-metal users) -# LLMRouter checks these in priority order: -# 1. Anthropic cloud — set ANTHROPIC_API_KEY -# 2. OpenAI cloud — set OPENAI_API_KEY -# 3. Local Ollama — set OLLAMA_HOST (+ optionally OLLAMA_MODEL) -# All three are optional; leave unset to rely on a local llm.yaml instead. -# ANTHROPIC_API_KEY=sk-ant-... -# OPENAI_API_KEY=sk-... -# OLLAMA_HOST=http://localhost:11434 -# OLLAMA_MODEL=llama3.2 - # Processing USE_GPU=true GPU_MEMORY_LIMIT=6144 @@ -55,14 +28,6 @@ DEMO_MODE=false # Cloud mode (set in compose.cloud.yml; also set here for reference) # CLOUD_DATA_ROOT=/devl/kiwi-cloud-data # KIWI_DB=data/kiwi.db # local-mode DB path override -# DEV ONLY: bypass JWT auth for these IPs/CIDRs (LAN testing without Caddy in the path). -# NEVER set in production. -# IMPORTANT: Docker port mapping NATs source IPs to the bridge gateway. When hitting -# localhost:8515 (host → Docker → nginx → API), nginx sees 192.168.80.1, not 127.0.0.1. -# Include the Docker bridge CIDR to allow localhost and LAN access through nginx. -# Run: docker network inspect kiwi-cloud_kiwi-cloud-net | grep Subnet -# Example: CLOUD_AUTH_BYPASS_IPS=10.1.10.0/24,127.0.0.1,::1,192.168.80.0/20 -# CLOUD_AUTH_BYPASS_IPS= # Heimdall license server (required for cloud tier resolution) # HEIMDALL_URL=https://license.circuitforge.tech @@ -70,8 +35,3 @@ DEMO_MODE=false # Directus JWT (must match cf-directus SECRET env var) # DIRECTUS_JWT_SECRET= - -# In-app feedback → Forgejo issue creation -# FORGEJO_API_TOKEN= -# FORGEJO_REPO=Circuit-Forge/kiwi -# FORGEJO_API_URL=https://git.opensourcesolarpunk.com/api/v1 diff --git a/.gitignore b/.gitignore index 5ffd0c8..2b8682f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,4 @@ -# CLAUDE.md — gitignored per BSL 1.1 commercial policy -CLAUDE.md - # Superpowers brainstorming artifacts .superpowers/ @@ -22,6 +19,3 @@ dist/ # Data directories data/ - -# Test artifacts (MagicMock sqlite files from pytest) - dict: - token = os.environ.get("FORGEJO_API_TOKEN", "") - return {"Authorization": f"token {token}", "Content-Type": "application/json"} - - -def _ensure_labels(label_names: list[str]) -> list[int]: - base = os.environ.get("FORGEJO_API_URL", "https://git.opensourcesolarpunk.com/api/v1") - repo = os.environ.get("FORGEJO_REPO", "Circuit-Forge/kiwi") - headers = _forgejo_headers() - resp = requests.get(f"{base}/repos/{repo}/labels", headers=headers, timeout=10) - existing = {lb["name"]: lb["id"] for lb in resp.json()} if resp.ok else {} - ids: list[int] = [] - for name in label_names: - if name in existing: - ids.append(existing[name]) - else: - r = requests.post( - f"{base}/repos/{repo}/labels", - headers=headers, - json={"name": name, "color": _LABEL_COLORS.get(name, "#ededed")}, - timeout=10, - ) - if r.ok: - ids.append(r.json()["id"]) - return ids - - -def _collect_context(tab: str) -> dict: - """Collect lightweight app context: tab, version, platform, timestamp.""" - try: - version = subprocess.check_output( - ["git", "describe", "--tags", "--always"], - cwd=_ROOT, text=True, timeout=5, - ).strip() - except Exception: - version = "dev" - - return { - "tab": tab, - "version": version, - "demo_mode": settings.DEMO_MODE, - "cloud_mode": settings.CLOUD_MODE, - "platform": platform.platform(), - "timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), - } - - -def _build_issue_body(form: dict, context: dict) -> str: - _TYPE_LABELS = {"bug": "🐛 Bug", "feature": "✨ Feature Request", "other": "💬 Other"} - lines: list[str] = [ - f"## {_TYPE_LABELS.get(form.get('type', 'other'), '💬 Other')}", - "", - form.get("description", ""), - "", - ] - if form.get("type") == "bug" and form.get("repro"): - lines += ["### Reproduction Steps", "", form["repro"], ""] - - lines += ["### Context", ""] - for k, v in context.items(): - lines.append(f"- **{k}:** {v}") - lines.append("") - - if form.get("submitter"): - lines += ["---", f"*Submitted by: {form['submitter']}*"] - - return "\n".join(lines) - - -# ── Schemas ──────────────────────────────────────────────────────────────────── - -class FeedbackRequest(BaseModel): - title: str - description: str - type: Literal["bug", "feature", "other"] = "other" - repro: str = "" - tab: str = "unknown" - submitter: str = "" # optional "Name " attribution - - -class FeedbackResponse(BaseModel): - issue_number: int - issue_url: str - - -# ── Routes ───────────────────────────────────────────────────────────────────── - -@router.get("/status") -def feedback_status() -> dict: - """Return whether feedback submission is configured on this instance.""" - return {"enabled": bool(os.environ.get("FORGEJO_API_TOKEN")) and not settings.DEMO_MODE} - - -@router.post("", response_model=FeedbackResponse) -def submit_feedback(payload: FeedbackRequest) -> FeedbackResponse: - """ - File a Forgejo issue from in-app feedback. - Silently disabled when FORGEJO_API_TOKEN is not set (demo/offline mode). - """ - token = os.environ.get("FORGEJO_API_TOKEN", "") - if not token: - raise HTTPException( - status_code=503, - detail="Feedback disabled: FORGEJO_API_TOKEN not configured.", - ) - if settings.DEMO_MODE: - raise HTTPException(status_code=403, detail="Feedback disabled in demo mode.") - - context = _collect_context(payload.tab) - form = { - "type": payload.type, - "description": payload.description, - "repro": payload.repro, - "submitter": payload.submitter, - } - body = _build_issue_body(form, context) - labels = ["beta-feedback", "needs-triage"] - labels.append({"bug": "bug", "feature": "feature-request"}.get(payload.type, "question")) - - base = os.environ.get("FORGEJO_API_URL", "https://git.opensourcesolarpunk.com/api/v1") - repo = os.environ.get("FORGEJO_REPO", "Circuit-Forge/kiwi") - headers = _forgejo_headers() - - label_ids = _ensure_labels(labels) - resp = requests.post( - f"{base}/repos/{repo}/issues", - headers=headers, - json={"title": payload.title, "body": body, "labels": label_ids}, - timeout=15, - ) - if not resp.ok: - raise HTTPException(status_code=502, detail=f"Forgejo error: {resp.text[:200]}") - - data = resp.json() - return FeedbackResponse(issue_number=data["number"], issue_url=data["html_url"]) diff --git a/app/api/endpoints/inventory.py b/app/api/endpoints/inventory.py index cb27fe6..5045dd0 100644 --- a/app/api/endpoints/inventory.py +++ b/app/api/endpoints/inventory.py @@ -369,23 +369,6 @@ async def list_tags( # ── Stats ───────────────────────────────────────────────────────────────────── -@router.post("/recalculate-expiry") -async def recalculate_expiry( - session: CloudUser = Depends(get_session), - store: Store = Depends(get_store), -) -> dict: - """Re-run the expiration predictor over all available inventory items. - - Uses each item's stored purchase_date and current location. Safe to call - multiple times — idempotent per session. - """ - def _run(s: Store) -> tuple[int, int]: - return s.recalculate_expiry(tier=session.tier, has_byok=session.has_byok) - - updated, skipped = await asyncio.to_thread(_run, store) - return {"updated": updated, "skipped": skipped} - - @router.get("/stats", response_model=InventoryStats) async def get_inventory_stats(store: Store = Depends(get_store)): def _stats(): diff --git a/app/api/endpoints/recipes.py b/app/api/endpoints/recipes.py deleted file mode 100644 index 12db086..0000000 --- a/app/api/endpoints/recipes.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Recipe suggestion endpoints.""" -from __future__ import annotations - -import asyncio -from pathlib import Path - -from fastapi import APIRouter, Depends, HTTPException - -from app.cloud_session import CloudUser, get_session -from app.db.store import Store -from app.models.schemas.recipe import RecipeRequest, RecipeResult -from app.services.recipe.recipe_engine import RecipeEngine -from app.tiers import can_use - -router = APIRouter() - - -def _suggest_in_thread(db_path: Path, req: RecipeRequest) -> RecipeResult: - """Run recipe suggestion in a worker thread with its own Store connection. - - SQLite connections cannot be shared across threads. This function creates - a fresh Store (and therefore a fresh sqlite3.Connection) in the same thread - where it will be used, avoiding ProgrammingError: SQLite objects created in - a thread can only be used in that same thread. - """ - store = Store(db_path) - try: - return RecipeEngine(store).suggest(req) - finally: - store.close() - - -@router.post("/suggest", response_model=RecipeResult) -async def suggest_recipes( - req: RecipeRequest, - session: CloudUser = Depends(get_session), -) -> RecipeResult: - # Inject session-authoritative tier/byok immediately — client-supplied values are ignored. - req = req.model_copy(update={"tier": session.tier, "has_byok": session.has_byok}) - if req.level == 4 and not req.wildcard_confirmed: - raise HTTPException( - status_code=400, - detail="Level 4 (Wildcard) requires wildcard_confirmed=true.", - ) - if req.level in (3, 4) and not can_use("recipe_suggestions", req.tier, req.has_byok): - raise HTTPException( - status_code=403, - detail="LLM recipe levels require Paid tier or a configured LLM backend.", - ) - if req.style_id and not can_use("style_picker", req.tier): - raise HTTPException(status_code=403, detail="Style picker requires Paid tier.") - return await asyncio.to_thread(_suggest_in_thread, session.db, req) - - -@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: - store = Store(db_path) - try: - return store.get_recipe(rid) - finally: - store.close() - - recipe = await asyncio.to_thread(_get, session.db, recipe_id) - if not recipe: - raise HTTPException(status_code=404, detail="Recipe not found.") - return recipe diff --git a/app/api/endpoints/settings.py b/app/api/endpoints/settings.py deleted file mode 100644 index 1570cdc..0000000 --- a/app/api/endpoints/settings.py +++ /dev/null @@ -1,46 +0,0 @@ -"""User settings endpoints.""" -from __future__ import annotations - -from fastapi import APIRouter, Depends, HTTPException -from pydantic import BaseModel - -from app.cloud_session import CloudUser, get_session -from app.db.session import get_store -from app.db.store import Store - -router = APIRouter() - -_ALLOWED_KEYS = frozenset({"cooking_equipment"}) - - -class SettingBody(BaseModel): - value: str - - -@router.get("/{key}") -async def get_setting( - key: str, - session: CloudUser = Depends(get_session), - store: Store = Depends(get_store), -) -> dict: - """Return the stored value for a settings key.""" - if key not in _ALLOWED_KEYS: - raise HTTPException(status_code=422, detail=f"Unknown settings key: '{key}'.") - value = store.get_setting(key) - if value is None: - raise HTTPException(status_code=404, detail=f"Setting '{key}' not found.") - return {"key": key, "value": value} - - -@router.put("/{key}") -async def set_setting( - key: str, - body: SettingBody, - session: CloudUser = Depends(get_session), - store: Store = Depends(get_store), -) -> dict: - """Upsert a settings key-value pair.""" - if key not in _ALLOWED_KEYS: - raise HTTPException(status_code=422, detail=f"Unknown settings key: '{key}'.") - store.set_setting(key, body.value) - return {"key": key, "value": body.value} diff --git a/app/api/endpoints/staples.py b/app/api/endpoints/staples.py deleted file mode 100644 index 8660da5..0000000 --- a/app/api/endpoints/staples.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Staple library endpoints.""" -from __future__ import annotations - -from fastapi import APIRouter, HTTPException - -from app.services.recipe.staple_library import StapleLibrary - -router = APIRouter() -_lib = StapleLibrary() - - -@router.get("/") -async def list_staples(dietary: str | None = None) -> list[dict]: - staples = _lib.filter_by_dietary(dietary) if dietary else _lib.list_all() - return [ - { - "slug": s.slug, - "name": s.name, - "description": s.description, - "dietary_labels": s.dietary_labels, - "yield_formats": list(s.yield_formats.keys()), - } - for s in staples - ] - - -@router.get("/{slug}") -async def get_staple(slug: str) -> dict: - staple = _lib.get(slug) - if not staple: - raise HTTPException(status_code=404, detail=f"Staple '{slug}' not found.") - return { - "slug": staple.slug, - "name": staple.name, - "description": staple.description, - "dietary_labels": staple.dietary_labels, - "base_ingredients": staple.base_ingredients, - "base_method": staple.base_method, - "base_time_minutes": staple.base_time_minutes, - "yield_formats": staple.yield_formats, - "compatible_styles": staple.compatible_styles, - } diff --git a/app/api/routes.py b/app/api/routes.py index 79395a2..2405e56 100644 --- a/app/api/routes.py +++ b/app/api/routes.py @@ -1,14 +1,10 @@ from fastapi import APIRouter -from app.api.endpoints import health, receipts, export, inventory, ocr, recipes, settings, staples, feedback +from app.api.endpoints import health, receipts, export, inventory, ocr api_router = APIRouter() -api_router.include_router(health.router, prefix="/health", tags=["health"]) -api_router.include_router(receipts.router, prefix="/receipts", tags=["receipts"]) -api_router.include_router(ocr.router, prefix="/receipts", tags=["ocr"]) -api_router.include_router(export.router, tags=["export"]) -api_router.include_router(inventory.router, prefix="/inventory", tags=["inventory"]) -api_router.include_router(recipes.router, prefix="/recipes", tags=["recipes"]) -api_router.include_router(settings.router, prefix="/settings", tags=["settings"]) -api_router.include_router(staples.router, prefix="/staples", tags=["staples"]) -api_router.include_router(feedback.router, prefix="/feedback", tags=["feedback"]) \ No newline at end of file +api_router.include_router(health.router, prefix="/health", tags=["health"]) +api_router.include_router(receipts.router, prefix="/receipts", tags=["receipts"]) +api_router.include_router(ocr.router, prefix="/receipts", tags=["ocr"]) # OCR endpoints under /receipts +api_router.include_router(export.router, tags=["export"]) # No prefix, uses /export in the router +api_router.include_router(inventory.router, prefix="/inventory", tags=["inventory"]) \ No newline at end of file diff --git a/app/cloud_session.py b/app/cloud_session.py index ba35bbb..4cba4a1 100644 --- a/app/cloud_session.py +++ b/app/cloud_session.py @@ -37,43 +37,6 @@ DIRECTUS_JWT_SECRET: str = os.environ.get("DIRECTUS_JWT_SECRET", "") HEIMDALL_URL: str = os.environ.get("HEIMDALL_URL", "https://license.circuitforge.tech") HEIMDALL_ADMIN_TOKEN: str = os.environ.get("HEIMDALL_ADMIN_TOKEN", "") -# Dev bypass: comma-separated IPs or CIDR ranges that skip JWT auth. -# NEVER set this in production. Intended only for LAN developer testing when -# the request doesn't pass through Caddy (which normally injects X-CF-Session). -# Example: CLOUD_AUTH_BYPASS_IPS=10.1.10.0/24,127.0.0.1 -import ipaddress as _ipaddress - -_BYPASS_RAW: list[str] = [ - e.strip() - for e in os.environ.get("CLOUD_AUTH_BYPASS_IPS", "").split(",") - if e.strip() -] - -_BYPASS_NETS: list[_ipaddress.IPv4Network | _ipaddress.IPv6Network] = [] -_BYPASS_IPS: frozenset[str] = frozenset() - -if _BYPASS_RAW: - _nets, _ips = [], set() - for entry in _BYPASS_RAW: - try: - _nets.append(_ipaddress.ip_network(entry, strict=False)) - except ValueError: - _ips.add(entry) # treat non-parseable entries as bare IPs - _BYPASS_NETS = _nets - _BYPASS_IPS = frozenset(_ips) - - -def _is_bypass_ip(ip: str) -> bool: - if not ip: - return False - if ip in _BYPASS_IPS: - return True - try: - addr = _ipaddress.ip_address(ip) - return any(addr in net for net in _BYPASS_NETS) - except ValueError: - return False - _LOCAL_KIWI_DB: Path = Path(os.environ.get("KIWI_DB", "data/kiwi.db")) _TIER_CACHE: dict[str, tuple[str, float]] = {} @@ -190,28 +153,12 @@ def get_session(request: Request) -> CloudUser: Local mode: fully-privileged "local" user pointing at local DB. Cloud mode: validates X-CF-Session JWT, provisions license, resolves tier. - Dev bypass: if CLOUD_AUTH_BYPASS_IPS is set and the client IP matches, - returns a "local" session without JWT validation (dev/LAN use only). """ has_byok = _detect_byok() if not CLOUD_MODE: return CloudUser(user_id="local", tier="local", db=_LOCAL_KIWI_DB, has_byok=has_byok) - # Prefer X-Real-IP (set by nginx from the actual client address) over the - # TCP peer address (which is nginx's container IP when behind the proxy). - # Prefer X-Real-IP (set by nginx from the actual client address) over the - # TCP peer address (which is nginx's container IP when behind the proxy). - client_ip = ( - request.headers.get("x-real-ip", "") - or (request.client.host if request.client else "") - ) - if (_BYPASS_IPS or _BYPASS_NETS) and _is_bypass_ip(client_ip): - log.debug("CLOUD_AUTH_BYPASS_IPS match for %s — returning local session", client_ip) - # Use a dev DB under CLOUD_DATA_ROOT so the container has a writable path. - dev_db = _user_db_path("local-dev") - return CloudUser(user_id="local-dev", tier="local", db=dev_db, has_byok=has_byok) - raw_header = ( request.headers.get("x-cf-session", "") or request.headers.get("cookie", "") @@ -219,7 +166,7 @@ def get_session(request: Request) -> CloudUser: if not raw_header: raise HTTPException(status_code=401, detail="Not authenticated") - token = _extract_session_token(raw_header) # gitleaks:allow — function name, not a secret + token = _extract_session_token(raw_header) if not token: raise HTTPException(status_code=401, detail="Not authenticated") diff --git a/app/core/config.py b/app/core/config.py index 091b574..1f8015d 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -43,13 +43,6 @@ class Settings: # Quality MIN_QUALITY_SCORE: float = float(os.environ.get("MIN_QUALITY_SCORE", "50.0")) - # CF-core resource coordinator (VRAM lease management) - COORDINATOR_URL: str = os.environ.get("COORDINATOR_URL", "http://localhost:7700") - - # Hosted cf-orch coordinator — bearer token for managed cloud GPU inference (Paid+) - # CFOrchClient reads CF_LICENSE_KEY automatically; exposed here for startup validation. - CF_LICENSE_KEY: str | None = os.environ.get("CF_LICENSE_KEY") - # Feature flags ENABLE_OCR: bool = os.environ.get("ENABLE_OCR", "false").lower() in ("1", "true", "yes") diff --git a/app/db/migrations/005_receipt_staged_status.sql b/app/db/migrations/005_receipt_staged_status.sql index 286fd41..d323526 100644 --- a/app/db/migrations/005_receipt_staged_status.sql +++ b/app/db/migrations/005_receipt_staged_status.sql @@ -9,7 +9,6 @@ CREATE TABLE receipts_new ( id INTEGER PRIMARY KEY AUTOINCREMENT, filename TEXT NOT NULL, original_path TEXT NOT NULL, - processed_path TEXT, status TEXT NOT NULL DEFAULT 'uploaded' CHECK (status IN ( 'uploaded', diff --git a/app/db/migrations/013_background_tasks.sql b/app/db/migrations/006_background_tasks.sql similarity index 100% rename from app/db/migrations/013_background_tasks.sql rename to app/db/migrations/006_background_tasks.sql diff --git a/app/db/migrations/006_element_profiles.sql b/app/db/migrations/006_element_profiles.sql deleted file mode 100644 index 09c9367..0000000 --- a/app/db/migrations/006_element_profiles.sql +++ /dev/null @@ -1,48 +0,0 @@ --- Migration 006: Ingredient element profiles + FlavorGraph molecule index. - -CREATE TABLE ingredient_profiles ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - name_variants TEXT NOT NULL DEFAULT '[]', -- JSON array of aliases/alternate spellings - elements TEXT NOT NULL DEFAULT '[]', -- JSON array: ["Richness","Depth"] - -- Functional submetadata (from USDA FDC) - fat_pct REAL DEFAULT 0.0, - fat_saturated_pct REAL DEFAULT 0.0, - moisture_pct REAL DEFAULT 0.0, - protein_pct REAL DEFAULT 0.0, - starch_pct REAL DEFAULT 0.0, - binding_score INTEGER DEFAULT 0 CHECK (binding_score BETWEEN 0 AND 3), - glutamate_mg REAL DEFAULT 0.0, - ph_estimate REAL, - sodium_mg_per_100g REAL DEFAULT 0.0, - smoke_point_c REAL, - is_fermented INTEGER NOT NULL DEFAULT 0, - is_emulsifier INTEGER NOT NULL DEFAULT 0, - -- Aroma submetadata - flavor_molecule_ids TEXT NOT NULL DEFAULT '[]', -- JSON array of FlavorGraph compound IDs - heat_stable INTEGER NOT NULL DEFAULT 1, - add_timing TEXT NOT NULL DEFAULT 'any' - CHECK (add_timing IN ('early','finish','any')), - -- Brightness submetadata - acid_type TEXT CHECK (acid_type IN ('citric','acetic','lactic',NULL)), - -- Texture submetadata - texture_profile TEXT NOT NULL DEFAULT 'neutral', - water_activity REAL, - -- Source - usda_fdc_id TEXT, - source TEXT NOT NULL DEFAULT 'usda', - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE UNIQUE INDEX idx_ingredient_profiles_name ON ingredient_profiles (name); -CREATE INDEX idx_ingredient_profiles_elements ON ingredient_profiles (elements); - -CREATE TABLE flavor_molecules ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - compound_id TEXT NOT NULL UNIQUE, -- FlavorGraph node ID - compound_name TEXT NOT NULL, - ingredient_names TEXT NOT NULL DEFAULT '[]', -- JSON array of ingredient names - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX idx_flavor_molecules_compound_id ON flavor_molecules (compound_id); diff --git a/app/db/migrations/007_recipe_corpus.sql b/app/db/migrations/007_recipe_corpus.sql deleted file mode 100644 index bc8fdaf..0000000 --- a/app/db/migrations/007_recipe_corpus.sql +++ /dev/null @@ -1,24 +0,0 @@ --- Migration 007: Recipe corpus index (food.com dataset). - -CREATE TABLE recipes ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - external_id TEXT, - title TEXT NOT NULL, - ingredients TEXT NOT NULL DEFAULT '[]', -- JSON array of raw ingredient strings - ingredient_names TEXT NOT NULL DEFAULT '[]', -- JSON array of normalized names - directions TEXT NOT NULL DEFAULT '[]', -- JSON array of step strings - category TEXT, - keywords TEXT NOT NULL DEFAULT '[]', -- JSON array - calories REAL, - fat_g REAL, - protein_g REAL, - sodium_mg REAL, - -- Element coverage scores computed at import time - element_coverage TEXT NOT NULL DEFAULT '{}', -- JSON {element: 0.0-1.0} - source TEXT NOT NULL DEFAULT 'foodcom', - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX idx_recipes_title ON recipes (title); -CREATE INDEX idx_recipes_category ON recipes (category); -CREATE UNIQUE INDEX idx_recipes_external_id ON recipes (external_id); diff --git a/app/db/migrations/008_substitution_pairs.sql b/app/db/migrations/008_substitution_pairs.sql deleted file mode 100644 index fe1c12a..0000000 --- a/app/db/migrations/008_substitution_pairs.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Migration 008: Derived substitution pairs. --- Source: diff of lishuyang/recipepairs (GPL-3.0 derivation — raw data not shipped). - -CREATE TABLE substitution_pairs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - original_name TEXT NOT NULL, - substitute_name TEXT NOT NULL, - constraint_label TEXT NOT NULL, -- 'vegan'|'vegetarian'|'dairy_free'|'gluten_free'|'low_fat'|'low_sodium' - fat_delta REAL DEFAULT 0.0, - moisture_delta REAL DEFAULT 0.0, - glutamate_delta REAL DEFAULT 0.0, - protein_delta REAL DEFAULT 0.0, - occurrence_count INTEGER DEFAULT 1, - compensation_hints TEXT NOT NULL DEFAULT '[]', -- JSON [{ingredient, reason, element}] - source TEXT NOT NULL DEFAULT 'derived', - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX idx_substitution_pairs_original ON substitution_pairs (original_name); -CREATE INDEX idx_substitution_pairs_constraint ON substitution_pairs (constraint_label); -CREATE UNIQUE INDEX idx_substitution_pairs_pair - ON substitution_pairs (original_name, substitute_name, constraint_label); diff --git a/app/db/migrations/009_staple_library.sql b/app/db/migrations/009_staple_library.sql deleted file mode 100644 index ec9d7d7..0000000 --- a/app/db/migrations/009_staple_library.sql +++ /dev/null @@ -1,27 +0,0 @@ --- Migration 009: Staple library (bulk-preparable base components). - -CREATE TABLE staples ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - slug TEXT NOT NULL UNIQUE, - name TEXT NOT NULL, - description TEXT, - base_ingredients TEXT NOT NULL DEFAULT '[]', -- JSON array of ingredient strings - base_method TEXT, - base_time_minutes INTEGER, - yield_formats TEXT NOT NULL DEFAULT '{}', -- JSON {format_name: {elements, shelf_days, methods, texture}} - dietary_labels TEXT NOT NULL DEFAULT '[]', -- JSON ['vegan','high-protein'] - compatible_styles TEXT NOT NULL DEFAULT '[]', -- JSON [style_id] - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE TABLE user_staples ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - staple_slug TEXT NOT NULL REFERENCES staples(slug) ON DELETE CASCADE, - active_format TEXT NOT NULL, - quantity_g REAL, - prepared_at TEXT, - notes TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX idx_user_staples_slug ON user_staples (staple_slug); diff --git a/app/db/migrations/010_recipe_feedback.sql b/app/db/migrations/010_recipe_feedback.sql deleted file mode 100644 index c4f358e..0000000 --- a/app/db/migrations/010_recipe_feedback.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Migration 010: User substitution approval log (opt-in dataset moat). - -CREATE TABLE substitution_feedback ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - original_name TEXT NOT NULL, - substitute_name TEXT NOT NULL, - constraint_label TEXT, - compensation_used TEXT NOT NULL DEFAULT '[]', -- JSON array of compensation ingredient names - approved INTEGER NOT NULL DEFAULT 0, - opted_in INTEGER NOT NULL DEFAULT 0, -- user consented to anonymized sharing - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX idx_substitution_feedback_original ON substitution_feedback (original_name); -CREATE INDEX idx_substitution_feedback_opted_in ON substitution_feedback (opted_in); diff --git a/app/db/migrations/011_rate_limits.sql b/app/db/migrations/011_rate_limits.sql deleted file mode 100644 index 421002a..0000000 --- a/app/db/migrations/011_rate_limits.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Migration 011: Daily rate limits (leftover mode: 5/day free tier). - -CREATE TABLE rate_limits ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - feature TEXT NOT NULL, - window_date TEXT NOT NULL, -- YYYY-MM-DD - count INTEGER NOT NULL DEFAULT 0, - UNIQUE (feature, window_date) -); - -CREATE INDEX idx_rate_limits_feature_date ON rate_limits (feature, window_date); diff --git a/app/db/migrations/012_user_settings.sql b/app/db/migrations/012_user_settings.sql deleted file mode 100644 index 0c2e40f..0000000 --- a/app/db/migrations/012_user_settings.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Migration 012: User settings key-value store. - -CREATE TABLE IF NOT EXISTS user_settings ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL -); diff --git a/app/db/migrations/014_nutrition_macros.sql b/app/db/migrations/014_nutrition_macros.sql deleted file mode 100644 index fef90f2..0000000 --- a/app/db/migrations/014_nutrition_macros.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Migration 014: Add macro nutrition columns to recipes and ingredient_profiles. --- --- recipes: sugar, carbs, fiber, servings, and an estimated flag. --- ingredient_profiles: carbs, fiber, calories, sugar per 100g (for estimation fallback). - -ALTER TABLE recipes ADD COLUMN sugar_g REAL; -ALTER TABLE recipes ADD COLUMN carbs_g REAL; -ALTER TABLE recipes ADD COLUMN fiber_g REAL; -ALTER TABLE recipes ADD COLUMN servings REAL; -ALTER TABLE recipes ADD COLUMN nutrition_estimated INTEGER NOT NULL DEFAULT 0; - -ALTER TABLE ingredient_profiles ADD COLUMN carbs_g_per_100g REAL DEFAULT 0.0; -ALTER TABLE ingredient_profiles ADD COLUMN fiber_g_per_100g REAL DEFAULT 0.0; -ALTER TABLE ingredient_profiles ADD COLUMN calories_per_100g REAL DEFAULT 0.0; -ALTER TABLE ingredient_profiles ADD COLUMN sugar_g_per_100g REAL DEFAULT 0.0; - -CREATE INDEX idx_recipes_sugar_g ON recipes (sugar_g); -CREATE INDEX idx_recipes_carbs_g ON recipes (carbs_g); diff --git a/app/db/migrations/015_recipe_fts.sql b/app/db/migrations/015_recipe_fts.sql deleted file mode 100644 index dbd7c11..0000000 --- a/app/db/migrations/015_recipe_fts.sql +++ /dev/null @@ -1,38 +0,0 @@ --- Migration 015: FTS5 inverted index for recipe ingredient lookup. --- --- Content table backed by `recipes` — stores only the inverted index, no text duplication. --- MATCH queries replace O(N) LIKE scans with O(log N) token lookups. --- --- One-time rebuild cost on 3.2M rows: ~15-30 seconds at startup. --- Subsequent startups skip this migration entirely. - -CREATE VIRTUAL TABLE IF NOT EXISTS recipes_fts USING fts5( - ingredient_names, - content=recipes, - content_rowid=id, - tokenize="unicode61" -); - -INSERT INTO recipes_fts(recipes_fts) VALUES('rebuild'); - --- Triggers to keep the FTS index in sync with the recipes table. --- Without these, rows inserted after the initial rebuild are invisible to FTS queries. -CREATE TRIGGER IF NOT EXISTS recipes_fts_ai - AFTER INSERT ON recipes BEGIN - INSERT INTO recipes_fts(rowid, ingredient_names) - VALUES (new.id, new.ingredient_names); -END; - -CREATE TRIGGER IF NOT EXISTS recipes_fts_ad - AFTER DELETE ON recipes BEGIN - INSERT INTO recipes_fts(recipes_fts, rowid, ingredient_names) - VALUES ('delete', old.id, old.ingredient_names); -END; - -CREATE TRIGGER IF NOT EXISTS recipes_fts_au - AFTER UPDATE ON recipes BEGIN - INSERT INTO recipes_fts(recipes_fts, rowid, ingredient_names) - VALUES ('delete', old.id, old.ingredient_names); - INSERT INTO recipes_fts(rowid, ingredient_names) - VALUES (new.id, new.ingredient_names); -END; diff --git a/app/db/migrations/016_recipe_fts_triggers.sql b/app/db/migrations/016_recipe_fts_triggers.sql deleted file mode 100644 index 43a76c0..0000000 --- a/app/db/migrations/016_recipe_fts_triggers.sql +++ /dev/null @@ -1,27 +0,0 @@ --- Migration 016: Add FTS5 sync triggers for the recipes_fts content table. --- --- Migration 015 created recipes_fts and did a one-time rebuild, but omitted --- triggers. Without them, INSERT/UPDATE/DELETE on recipes does not update the --- FTS index, so new rows are invisible to MATCH queries. --- --- CREATE TRIGGER IF NOT EXISTS is idempotent — safe to re-run. - -CREATE TRIGGER IF NOT EXISTS recipes_fts_ai - AFTER INSERT ON recipes BEGIN - INSERT INTO recipes_fts(rowid, ingredient_names) - VALUES (new.id, new.ingredient_names); -END; - -CREATE TRIGGER IF NOT EXISTS recipes_fts_ad - AFTER DELETE ON recipes BEGIN - INSERT INTO recipes_fts(recipes_fts, rowid, ingredient_names) - VALUES ('delete', old.id, old.ingredient_names); -END; - -CREATE TRIGGER IF NOT EXISTS recipes_fts_au - AFTER UPDATE ON recipes BEGIN - INSERT INTO recipes_fts(recipes_fts, rowid, ingredient_names) - VALUES ('delete', old.id, old.ingredient_names); - INSERT INTO recipes_fts(rowid, ingredient_names) - VALUES (new.id, new.ingredient_names); -END; diff --git a/app/db/store.py b/app/db/store.py index ad9333b..9a0e366 100644 --- a/app/db/store.py +++ b/app/db/store.py @@ -32,10 +32,7 @@ class Store: # Deserialise any TEXT columns that contain JSON for key in ("metadata", "nutrition_data", "source_data", "items", "metrics", "improvement_suggestions", "confidence_scores", - "warnings", - # recipe columns - "ingredients", "ingredient_names", "directions", - "keywords", "element_coverage"): + "warnings"): if key in d and isinstance(d[key], str): try: d[key] = json.loads(d[key]) @@ -232,72 +229,6 @@ class Store: (str(days),), ) - def recalculate_expiry( - self, - tier: str = "local", - has_byok: bool = False, - ) -> tuple[int, int]: - """Re-run the expiration predictor over all available inventory items. - - Uses each item's existing purchase_date (falls back to today if NULL) - and its current location. Skips items that have an explicit - expiration_date from a source other than auto-prediction (i.e. items - whose expiry was found on a receipt or entered by the user) cannot be - distinguished — all available items are recalculated. - - Returns (updated_count, skipped_count). - """ - from datetime import date - from app.services.expiration_predictor import ExpirationPredictor - - predictor = ExpirationPredictor() - rows = self._fetch_all( - """SELECT i.id, i.location, i.purchase_date, - p.name AS product_name, p.category AS product_category - FROM inventory_items i - JOIN products p ON p.id = i.product_id - WHERE i.status = 'available'""", - (), - ) - - updated = skipped = 0 - for row in rows: - cat = predictor.get_category_from_product( - row["product_name"] or "", - product_category=row.get("product_category"), - location=row.get("location"), - ) - purchase_date_raw = row.get("purchase_date") - try: - purchase_date = ( - date.fromisoformat(purchase_date_raw) - if purchase_date_raw - else date.today() - ) - except (ValueError, TypeError): - purchase_date = date.today() - - exp = predictor.predict_expiration( - cat, - row["location"] or "pantry", - purchase_date=purchase_date, - product_name=row["product_name"], - tier=tier, - has_byok=has_byok, - ) - if exp is None: - skipped += 1 - continue - - self.conn.execute( - "UPDATE inventory_items SET expiration_date = ?, updated_at = datetime('now') WHERE id = ?", - (str(exp), row["id"]), - ) - updated += 1 - - self.conn.commit() - return updated, skipped - # ── receipt_data ────────────────────────────────────────────────────── def upsert_receipt_data(self, receipt_id: int, data: dict) -> dict[str, Any]: @@ -329,409 +260,3 @@ class Store: return self._fetch_one( "SELECT * FROM receipt_data WHERE receipt_id = ?", (receipt_id,) ) - - # ── recipes ─────────────────────────────────────────────────────────── - - def _fts_ready(self) -> bool: - """Return True if the recipes_fts virtual table exists.""" - row = self._fetch_one( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name='recipes_fts'" - ) - return row is not None - - # Words that carry no recipe-ingredient signal and should be filtered - # out when tokenising multi-word product names for FTS expansion. - _FTS_TOKEN_STOPWORDS: frozenset[str] = frozenset({ - # Common English stopwords - "a", "an", "the", "of", "in", "for", "with", "and", "or", "to", - "from", "at", "by", "as", "on", "into", - # Brand / marketing words that appear in product names - "lean", "cuisine", "healthy", "choice", "stouffer", "original", - "classic", "deluxe", "homestyle", "family", "style", "grade", - "premium", "select", "natural", "organic", "fresh", "lite", - "ready", "quick", "easy", "instant", "microwave", "frozen", - "brand", "size", "large", "small", "medium", "extra", - # Plant-based / alt-meat brand names - "daring", "gardein", "morningstar", "lightlife", "tofurky", - "quorn", "omni", "nuggs", "simulate", "simulate", - # Preparation states — "cut up chicken" is still chicken - "cut", "diced", "sliced", "chopped", "minced", "shredded", - "cooked", "raw", "whole", "boneless", "skinless", "trimmed", - "pre", "prepared", "marinated", "seasoned", "breaded", "battered", - "grilled", "roasted", "smoked", "canned", "dried", "dehydrated", - "pieces", "piece", "strips", "strip", "chunks", "chunk", - "fillets", "fillet", "cutlets", "cutlet", "tenders", "nuggets", - # Units / packaging - "oz", "lb", "lbs", "pkg", "pack", "box", "can", "bag", "jar", - }) - - # Maps substrings found in product-label names to canonical recipe-corpus - # ingredient terms. Checked as substring matches against the lower-cased - # full product name, then against each individual token. - _FTS_SYNONYMS: dict[str, str] = { - # Ground / minced beef - "burger patt": "hamburger", - "beef patt": "hamburger", - "ground beef": "hamburger", - "ground chuck": "hamburger", - "ground round": "hamburger", - "mince": "hamburger", - "veggie burger": "hamburger", - "beyond burger": "hamburger", - "impossible burger": "hamburger", - "plant burger": "hamburger", - "chicken patt": "hamburger", # FTS match only — recipe scoring still works - # Sausages - "kielbasa": "sausage", - "bratwurst": "sausage", - "brat ": "sausage", - "frankfurter": "hotdog", - "wiener": "hotdog", - # Chicken cuts + plant-based chicken → generic chicken for broader matching - "chicken breast": "chicken", - "chicken thigh": "chicken", - "chicken drumstick": "chicken", - "chicken wing": "chicken", - "rotisserie chicken": "chicken", - "chicken tender": "chicken", - "chicken strip": "chicken", - "chicken piece": "chicken", - "fake chicken": "chicken", - "plant chicken": "chicken", - "vegan chicken": "chicken", - "daring": "chicken", # Daring Foods brand - "gardein chick": "chicken", - "quorn chick": "chicken", - "chick'n": "chicken", - "chikn": "chicken", - "not-chicken": "chicken", - "no-chicken": "chicken", - # Plant-based beef subs — map to broad "beef" not "hamburger" - # (texture varies: strips ≠ ground; let corpus handle the specific form) - "not-beef": "beef", - "no-beef": "beef", - "plant beef": "beef", - "vegan beef": "beef", - # Plant-based pork subs - "not-pork": "pork", - "no-pork": "pork", - "plant pork": "pork", - "vegan pork": "pork", - "omnipork": "pork", - "omni pork": "pork", - # Generic alt-meat catch-alls → broad "beef" (safer than hamburger) - "fake meat": "beef", - "plant meat": "beef", - "vegan meat": "beef", - "meat-free": "beef", - "meatless": "beef", - # Pork cuts - "pork chop": "pork", - "pork loin": "pork", - "pork tenderloin": "pork", - # Tomato-based sauces - "marinara": "tomato sauce", - "pasta sauce": "tomato sauce", - "spaghetti sauce": "tomato sauce", - "pizza sauce": "tomato sauce", - # Pasta shapes — map to generic "pasta" so FTS finds any pasta recipe - "macaroni": "pasta", - "noodles": "pasta", - "spaghetti": "pasta", - "penne": "pasta", - "fettuccine": "pasta", - "rigatoni": "pasta", - "linguine": "pasta", - "rotini": "pasta", - "farfalle": "pasta", - # Cheese variants → "cheese" for broad matching - "shredded cheese": "cheese", - "sliced cheese": "cheese", - "american cheese": "cheese", - "cheddar": "cheese", - "mozzarella": "cheese", - # Cream variants - "heavy cream": "cream", - "whipping cream": "cream", - "half and half": "cream", - # Buns / rolls - "burger bun": "buns", - "hamburger bun": "buns", - "hot dog bun": "buns", - "bread roll": "buns", - "dinner roll": "buns", - # Tortillas / wraps - "flour tortilla": "tortillas", - "corn tortilla": "tortillas", - "tortilla wrap": "tortillas", - "soft taco shell": "tortillas", - "taco shell": "taco shells", - "pita bread": "pita", - "flatbread": "flatbread", - # Canned beans - "black bean": "beans", - "pinto bean": "beans", - "kidney bean": "beans", - "refried bean": "beans", - "chickpea": "beans", - "garbanzo": "beans", - # Rice variants - "white rice": "rice", - "brown rice": "rice", - "jasmine rice": "rice", - "basmati rice": "rice", - "instant rice": "rice", - "microwavable rice": "rice", - # Salsa / hot sauce - "hot sauce": "salsa", - "taco sauce": "salsa", - "enchilada sauce": "salsa", - # Sour cream substitute - "greek yogurt": "sour cream", - # Prepackaged meals - "lean cuisine": "casserole", - "stouffer": "casserole", - "healthy choice": "casserole", - "marie callender": "casserole", - } - - @staticmethod - def _normalize_for_fts(name: str) -> list[str]: - """Expand one pantry item to all FTS search terms it should contribute. - - Returns the original name plus: - - Any synonym-map canonical terms (handles product-label → corpus name) - - Individual significant tokens from multi-word product names - (handles packaged meals like "Lean Cuisine Chicken Alfredo" → also - searches for "chicken" and "alfredo" independently) - """ - lower = name.lower().strip() - if not lower: - return [] - - terms: list[str] = [lower] - - # Substring synonym check on full name - for pattern, canonical in Store._FTS_SYNONYMS.items(): - if pattern in lower: - terms.append(canonical) - - # For multi-word product names, also add individual significant tokens - if " " in lower: - for token in lower.split(): - if len(token) <= 3 or token in Store._FTS_TOKEN_STOPWORDS: - continue - if token not in terms: - terms.append(token) - # Synonym-expand individual tokens too - if token in Store._FTS_SYNONYMS: - canonical = Store._FTS_SYNONYMS[token] - if canonical not in terms: - terms.append(canonical) - - return terms - - @staticmethod - def _build_fts_query(ingredient_names: list[str]) -> str: - """Build an FTS5 MATCH expression ORing all ingredient terms. - - Each pantry item is expanded via _normalize_for_fts so that - product-label names (e.g. "burger patties") also search for their - recipe-corpus equivalents (e.g. "hamburger"), and multi-word packaged - product names contribute their individual ingredient tokens. - """ - parts: list[str] = [] - seen: set[str] = set() - for name in ingredient_names: - for term in Store._normalize_for_fts(name): - # Strip characters that break FTS5 query syntax - clean = term.replace('"', "").replace("'", "") - if not clean or clean in seen: - continue - seen.add(clean) - parts.append(f'"{clean}"') - return " OR ".join(parts) - - def search_recipes_by_ingredients( - self, - ingredient_names: list[str], - limit: int = 20, - category: str | None = None, - max_calories: float | None = None, - max_sugar_g: float | None = None, - max_carbs_g: float | None = None, - max_sodium_mg: float | None = None, - excluded_ids: list[int] | None = None, - ) -> list[dict]: - """Find recipes containing any of the given ingredient names. - Scores by match count and returns highest-scoring first. - - Uses FTS5 index (migration 015) when available — O(log N) per query. - Falls back to LIKE scans on older databases. - - Nutrition filters use NULL-passthrough: rows without nutrition data - always pass (they may be estimated or absent entirely). - """ - if not ingredient_names: - return [] - - extra_clauses: list[str] = [] - extra_params: list = [] - if category: - extra_clauses.append("r.category = ?") - extra_params.append(category) - if max_calories is not None: - extra_clauses.append("(r.calories IS NULL OR r.calories <= ?)") - extra_params.append(max_calories) - if max_sugar_g is not None: - extra_clauses.append("(r.sugar_g IS NULL OR r.sugar_g <= ?)") - extra_params.append(max_sugar_g) - if max_carbs_g is not None: - extra_clauses.append("(r.carbs_g IS NULL OR r.carbs_g <= ?)") - extra_params.append(max_carbs_g) - if max_sodium_mg is not None: - extra_clauses.append("(r.sodium_mg IS NULL OR r.sodium_mg <= ?)") - extra_params.append(max_sodium_mg) - if excluded_ids: - placeholders = ",".join("?" * len(excluded_ids)) - extra_clauses.append(f"r.id NOT IN ({placeholders})") - extra_params.extend(excluded_ids) - where_extra = (" AND " + " AND ".join(extra_clauses)) if extra_clauses else "" - - if self._fts_ready(): - return self._search_recipes_fts( - ingredient_names, limit, where_extra, extra_params - ) - return self._search_recipes_like( - ingredient_names, limit, where_extra, extra_params - ) - - def _search_recipes_fts( - self, - ingredient_names: list[str], - limit: int, - where_extra: str, - extra_params: list, - ) -> list[dict]: - """FTS5-backed ingredient search. Candidates fetched via inverted index; - match_count computed in Python over the small candidate set.""" - fts_query = self._build_fts_query(ingredient_names) - if not fts_query: - return [] - - # Pull up to 10× limit candidates so ranking has enough headroom. - sql = f""" - SELECT r.* - FROM recipes_fts - JOIN recipes r ON r.id = recipes_fts.rowid - WHERE recipes_fts MATCH ? - {where_extra} - LIMIT ? - """ - rows = self._fetch_all(sql, (fts_query, *extra_params, limit * 10)) - - pantry_set = {n.lower().strip() for n in ingredient_names} - scored: list[dict] = [] - for row in rows: - raw = row.get("ingredient_names") or [] - names: list[str] = raw if isinstance(raw, list) else json.loads(raw or "[]") - match_count = sum(1 for n in names if n.lower() in pantry_set) - scored.append({**row, "match_count": match_count}) - - scored.sort(key=lambda r: (-r["match_count"], r["id"])) - return scored[:limit] - - def _search_recipes_like( - self, - ingredient_names: list[str], - limit: int, - where_extra: str, - extra_params: list, - ) -> list[dict]: - """Legacy LIKE-based ingredient search (O(N×rows) — slow on large corpora).""" - like_params = [f'%"{n}"%' for n in ingredient_names] - like_clauses = " OR ".join( - "r.ingredient_names LIKE ?" for _ in ingredient_names - ) - match_score = " + ".join( - "CASE WHEN r.ingredient_names LIKE ? THEN 1 ELSE 0 END" - for _ in ingredient_names - ) - sql = f""" - SELECT r.*, ({match_score}) AS match_count - FROM recipes r - WHERE ({like_clauses}) - {where_extra} - ORDER BY match_count DESC, r.id ASC - LIMIT ? - """ - all_params = like_params + like_params + extra_params + [limit] - return self._fetch_all(sql, tuple(all_params)) - - def get_recipe(self, recipe_id: int) -> dict | None: - return self._fetch_one("SELECT * FROM recipes WHERE id = ?", (recipe_id,)) - - # ── rate limits ─────────────────────────────────────────────────────── - - def check_and_increment_rate_limit( - self, feature: str, daily_max: int - ) -> tuple[bool, int]: - """Check daily counter for feature; only increment if under the limit. - Returns (allowed, current_count). Rejected calls do not consume quota.""" - from datetime import date - today = date.today().isoformat() - row = self._fetch_one( - "SELECT count FROM rate_limits WHERE feature = ? AND window_date = ?", - (feature, today), - ) - current = row["count"] if row else 0 - if current >= daily_max: - return (False, current) - self.conn.execute(""" - INSERT INTO rate_limits (feature, window_date, count) - VALUES (?, ?, 1) - ON CONFLICT(feature, window_date) DO UPDATE SET count = count + 1 - """, (feature, today)) - self.conn.commit() - return (True, current + 1) - - # ── user settings ──────────────────────────────────────────────────── - - def get_setting(self, key: str) -> str | None: - """Return the value for a settings key, or None if not set.""" - row = self._fetch_one( - "SELECT value FROM user_settings WHERE key = ?", (key,) - ) - return row["value"] if row else None - - def set_setting(self, key: str, value: str) -> None: - """Upsert a settings key-value pair.""" - self.conn.execute( - "INSERT INTO user_settings (key, value) VALUES (?, ?)" - " ON CONFLICT(key) DO UPDATE SET value = excluded.value", - (key, value), - ) - self.conn.commit() - - # ── substitution feedback ───────────────────────────────────────────── - - def log_substitution_feedback( - self, - original: str, - substitute: str, - constraint: str | None, - compensation_used: list[str], - approved: bool, - opted_in: bool, - ) -> None: - self.conn.execute(""" - INSERT INTO substitution_feedback - (original_name, substitute_name, constraint_label, - compensation_used, approved, opted_in) - VALUES (?,?,?,?,?,?) - """, ( - original, substitute, constraint, - self._dump(compensation_used), - int(approved), int(opted_in), - )) - self.conn.commit() diff --git a/app/models/schemas/recipe.py b/app/models/schemas/recipe.py deleted file mode 100644 index 7985342..0000000 --- a/app/models/schemas/recipe.py +++ /dev/null @@ -1,81 +0,0 @@ -"""Pydantic schemas for the recipe engine API.""" -from __future__ import annotations - -from pydantic import BaseModel, Field - - -class SwapCandidate(BaseModel): - original_name: str - substitute_name: str - constraint_label: str - explanation: str - compensation_hints: list[dict] = Field(default_factory=list) - - -class NutritionPanel(BaseModel): - """Per-recipe macro summary. All values are per-serving when servings is known, - otherwise for the full recipe. None means data is unavailable.""" - calories: float | None = None - fat_g: float | None = None - protein_g: float | None = None - carbs_g: float | None = None - fiber_g: float | None = None - sugar_g: float | None = None - sodium_mg: float | None = None - servings: float | None = None - estimated: bool = False # True when nutrition was inferred from ingredient profiles - - -class RecipeSuggestion(BaseModel): - id: int - title: str - match_count: int - element_coverage: dict[str, float] = Field(default_factory=dict) - swap_candidates: list[SwapCandidate] = Field(default_factory=list) - missing_ingredients: list[str] = Field(default_factory=list) - directions: list[str] = Field(default_factory=list) - prep_notes: list[str] = Field(default_factory=list) - notes: str = "" - level: int = 1 - is_wildcard: bool = False - nutrition: NutritionPanel | None = None - - -class GroceryLink(BaseModel): - ingredient: str - retailer: str - url: str - - -class RecipeResult(BaseModel): - suggestions: list[RecipeSuggestion] - element_gaps: list[str] - grocery_list: list[str] = Field(default_factory=list) - grocery_links: list[GroceryLink] = Field(default_factory=list) - rate_limited: bool = False - rate_limit_count: int = 0 - - -class NutritionFilters(BaseModel): - """Optional per-serving upper bounds for macro filtering. None = no filter.""" - max_calories: float | None = None - max_sugar_g: float | None = None - max_carbs_g: float | None = None - max_sodium_mg: float | None = None - - -class RecipeRequest(BaseModel): - pantry_items: list[str] - level: int = Field(default=1, ge=1, le=4) - constraints: list[str] = Field(default_factory=list) - expiry_first: bool = False - hard_day_mode: bool = False - max_missing: int | None = None - style_id: str | None = None - category: str | None = None - tier: str = "free" - has_byok: bool = False - wildcard_confirmed: bool = False - allergies: list[str] = Field(default_factory=list) - nutrition_filters: NutritionFilters = Field(default_factory=NutritionFilters) - excluded_ids: list[int] = Field(default_factory=list) diff --git a/app/services/barcode_scanner.py b/app/services/barcode_scanner.py index f5f667b..889e807 100644 --- a/app/services/barcode_scanner.py +++ b/app/services/barcode_scanner.py @@ -5,8 +5,6 @@ This module provides functionality to detect and decode barcodes from images (UPC, EAN, QR codes, etc.). """ -import io - import cv2 import numpy as np from pyzbar import pyzbar @@ -14,12 +12,6 @@ from pathlib import Path from typing import List, Dict, Any, Optional import logging -try: - from PIL import Image as _PILImage - _HAS_PIL = True -except ImportError: - _HAS_PIL = False - logger = logging.getLogger(__name__) @@ -84,7 +76,9 @@ class BarcodeScanner: # 4. Try rotations if still no barcodes found (handles tilted/rotated barcodes) if not barcodes: logger.info("No barcodes found in standard orientation, trying rotations...") - for angle in [90, 180, 270, 45, 135]: + # Try incremental angles: 30°, 60°, 90° (covers 0-90° range) + # 0° already tried, 180° is functionally same as 0°, 90°/270° are same axis + for angle in [30, 60, 90]: rotated_gray = self._rotate_image(gray, angle) rotated_color = self._rotate_image(image, angle) detected = self._detect_barcodes(rotated_gray, rotated_color) @@ -270,26 +264,6 @@ class BarcodeScanner: return list(seen.values()) - def _fix_exif_orientation(self, image_bytes: bytes) -> bytes: - """Apply EXIF orientation correction so cv2 sees an upright image. - - Phone cameras embed rotation in EXIF; cv2.imdecode ignores it, - so a photo taken in portrait may arrive physically sideways in memory. - """ - if not _HAS_PIL: - return image_bytes - try: - pil = _PILImage.open(io.BytesIO(image_bytes)) - pil = _PILImage.fromarray(np.array(pil)) # strips EXIF but applies orientation via PIL - # Use ImageOps.exif_transpose for proper EXIF-aware rotation - import PIL.ImageOps - pil = PIL.ImageOps.exif_transpose(pil) - buf = io.BytesIO() - pil.save(buf, format="JPEG") - return buf.getvalue() - except Exception: - return image_bytes - def scan_from_bytes(self, image_bytes: bytes) -> List[Dict[str, Any]]: """ Scan barcodes from image bytes (uploaded file). @@ -301,10 +275,6 @@ class BarcodeScanner: List of detected barcodes """ try: - # Apply EXIF orientation correction first (phone cameras embed rotation in EXIF; - # cv2.imdecode ignores it, causing sideways barcodes to appear rotated in memory). - image_bytes = self._fix_exif_orientation(image_bytes) - # Convert bytes to numpy array nparr = np.frombuffer(image_bytes, np.uint8) image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) @@ -330,12 +300,11 @@ class BarcodeScanner: ) barcodes.extend(self._detect_barcodes(thresh, image)) - # 3. Try all 90° rotations + common tilt angles - # 90/270 catches truly sideways barcodes; 180 catches upside-down; - # 45/135 catches tilted barcodes on flat surfaces. + # 3. Try rotations if still no barcodes found if not barcodes: logger.info("No barcodes found in uploaded image, trying rotations...") - for angle in [90, 180, 270, 45, 135]: + # Try incremental angles: 30°, 60°, 90° (covers 0-90° range) + for angle in [30, 60, 90]: rotated_gray = self._rotate_image(gray, angle) rotated_color = self._rotate_image(image, angle) detected = self._detect_barcodes(rotated_gray, rotated_color) diff --git a/app/services/expiration_predictor.py b/app/services/expiration_predictor.py index 22eca01..d51919d 100644 --- a/app/services/expiration_predictor.py +++ b/app/services/expiration_predictor.py @@ -21,29 +21,6 @@ logger = logging.getLogger(__name__) class ExpirationPredictor: """Predict expiration dates based on product category and storage location.""" - # Canonical location names and their aliases. - # All location strings are normalised through this before table lookup. - LOCATION_ALIASES: dict[str, str] = { - 'garage_freezer': 'freezer', - 'chest_freezer': 'freezer', - 'deep_freezer': 'freezer', - 'upright_freezer': 'freezer', - 'refrigerator': 'fridge', - 'frig': 'fridge', - 'cupboard': 'cabinet', - 'shelf': 'pantry', - 'counter': 'pantry', - } - - # When a category has no entry for the requested location, try these - # alternatives in order — prioritising same-temperature storage first. - LOCATION_FALLBACK: dict[str, tuple[str, ...]] = { - 'freezer': ('freezer', 'fridge', 'pantry', 'cabinet'), - 'fridge': ('fridge', 'pantry', 'cabinet', 'freezer'), - 'pantry': ('pantry', 'cabinet', 'fridge', 'freezer'), - 'cabinet': ('cabinet', 'pantry', 'fridge', 'freezer'), - } - # Default shelf life in days by category and location # Sources: USDA FoodKeeper app, FDA guidelines SHELF_LIFE = { @@ -62,8 +39,6 @@ class ExpirationPredictor: 'poultry': {'fridge': 2, 'freezer': 270}, 'chicken': {'fridge': 2, 'freezer': 270}, 'turkey': {'fridge': 2, 'freezer': 270}, - 'tempeh': {'fridge': 10, 'freezer': 365}, - 'tofu': {'fridge': 5, 'freezer': 180}, 'ground_meat': {'fridge': 2, 'freezer': 120}, # Seafood 'fish': {'fridge': 2, 'freezer': 180}, @@ -84,9 +59,9 @@ class ExpirationPredictor: 'bread': {'pantry': 5, 'freezer': 90}, 'bakery': {'pantry': 3, 'fridge': 7, 'freezer': 90}, # Frozen - 'frozen_foods': {'freezer': 180, 'fridge': 3}, - 'frozen_vegetables': {'freezer': 270, 'fridge': 4}, - 'frozen_fruit': {'freezer': 365, 'fridge': 4}, + 'frozen_foods': {'freezer': 180}, + 'frozen_vegetables': {'freezer': 270}, + 'frozen_fruit': {'freezer': 365}, 'ice_cream': {'freezer': 60}, # Pantry Staples 'canned_goods': {'pantry': 730, 'cabinet': 730}, @@ -116,127 +91,44 @@ class ExpirationPredictor: 'prepared_foods': {'fridge': 4, 'freezer': 90}, } - # Keyword lists are checked in declaration order — most specific first. - # Rules: - # - canned/processed goods BEFORE raw-meat terms (canned chicken != raw chicken) - # - frozen prepared foods BEFORE generic protein terms - # - multi-word phrases before single words where ambiguity exists CATEGORY_KEYWORDS = { - # ── Frozen prepared foods ───────────────────────────────────────────── - # Before raw protein entries so plant-based frozen products don't - # inherit 2–3 day raw-meat shelf lives. - 'ice_cream': ['ice cream', 'gelato', 'frozen yogurt', 'sorbet', 'sherbet'], - 'frozen_fruit': [ - 'frozen berries', 'frozen mango', 'frozen strawberries', - 'frozen blueberries', 'frozen raspberries', 'frozen peaches', - 'frozen fruit', 'frozen cherries', - ], - 'frozen_vegetables': [ - 'frozen veg', 'frozen corn', 'frozen peas', 'frozen broccoli', - 'frozen spinach', 'frozen edamame', 'frozen green beans', - 'frozen mixed vegetables', 'frozen carrots', - 'peas & carrots', 'peas and carrots', 'mixed vegetables', - 'spring rolls', 'vegetable spring rolls', - ], - 'frozen_foods': [ - 'plant-based', 'plant based', 'meatless', 'impossible', - "chik'n", 'chikn', 'veggie burger', 'veggie patty', - 'nugget', 'tater tot', 'waffle fries', 'hash brown', - 'onion ring', 'fish stick', 'fish fillet', 'potsticker', - 'dumpling', 'egg roll', 'empanada', 'tamale', 'falafel', - 'mac & cheese bite', 'cauliflower wing', 'ranchero potato', - ], - # ── Canned / shelf-stable processed goods ───────────────────────────── - # Before raw protein keywords so "canned chicken", "cream of chicken", - # and "lentil soup" resolve here rather than to raw chicken/cream. - 'canned_goods': [ - 'canned', 'can of', 'tin of', 'tinned', - 'cream of ', 'condensed soup', 'condensed cream', - 'baked beans', 'refried beans', - 'canned beans', 'canned tomatoes', 'canned corn', 'canned peas', - 'canned soup', 'canned tuna', 'canned salmon', 'canned chicken', - 'canned fruit', 'canned peaches', 'canned pears', - 'enchilada sauce', 'tomato sauce', 'tomato paste', - 'lentil soup', 'bean soup', 'chicken noodle soup', - ], - # ── Condiments & brined items ───────────────────────────────────────── - # Before produce/protein terms so brined olives, jarred peppers, etc. - # don't inherit raw vegetable shelf lives. - 'ketchup': ['ketchup', 'catsup'], - 'mustard': ['mustard', 'dijon', 'dijion', 'stoneground mustard'], - 'mayo': ['mayo', 'mayonnaise', 'miracle whip'], - 'soy_sauce': ['soy sauce', 'tamari', 'shoyu'], - 'salad_dressing': ['salad dressing', 'ranch', 'italian dressing', 'vinaigrette'], - 'condiments': [ - # brined / jarred items - 'dill chips', 'hamburger chips', 'gherkin', - 'olive', 'capers', 'jalapeño', 'jalapeno', 'pepperoncini', - 'pimiento', 'banana pepper', 'cornichon', - # sauces - 'hot sauce', 'hot pepper sauce', 'sriracha', 'cholula', - 'worcestershire', 'barbecue sauce', 'bbq sauce', - 'chipotle sauce', 'chipotle mayo', 'chipotle creamy', - 'salsa', 'chutney', 'relish', - 'teriyaki', 'hoisin', 'oyster sauce', 'fish sauce', - 'miso', 'ssamjang', 'gochujang', 'doenjang', - 'soybean paste', 'fermented soybean', - # nut butters / spreads - 'peanut butter', 'almond butter', 'tahini', 'hummus', - # seasoning mixes - 'seasoning', 'spice blend', 'borracho', - # other shelf-stable sauces - 'yuzu', 'ponzu', 'lizano', - ], - # ── Soy / fermented proteins ────────────────────────────────────────── - 'tempeh': ['tempeh'], - 'tofu': ['tofu', 'bean curd'], - # ── Dairy ───────────────────────────────────────────────────────────── 'milk': ['milk', 'whole milk', '2% milk', 'skim milk', 'almond milk', 'oat milk', 'soy milk'], - 'cheese': ['cheese', 'cheddar', 'mozzarella', 'swiss', 'parmesan', 'feta', 'gouda', 'velveeta'], + 'cheese': ['cheese', 'cheddar', 'mozzarella', 'swiss', 'parmesan', 'feta', 'gouda'], 'yogurt': ['yogurt', 'greek yogurt', 'yoghurt'], 'butter': ['butter', 'margarine'], - # Bare 'cream' removed — "cream of X" is canned_goods (matched above). - 'cream': ['heavy cream', 'whipping cream', 'sour cream', 'crème fraîche', - 'cream cheese', 'whipped topping', 'whipped cream'], + 'cream': ['cream', 'heavy cream', 'whipping cream', 'sour cream'], 'eggs': ['eggs', 'egg'], - # ── Raw proteins ────────────────────────────────────────────────────── - # After canned/frozen so "canned chicken" is already resolved above. + 'beef': ['beef', 'steak', 'roast', 'brisket', 'ribeye', 'sirloin'], + 'pork': ['pork', 'bacon', 'ham', 'sausage', 'pork chop'], + 'chicken': ['chicken', 'chicken breast', 'chicken thigh', 'chicken wings'], + 'turkey': ['turkey', 'turkey breast', 'ground turkey'], + 'ground_meat': ['ground beef', 'ground pork', 'ground chicken', 'hamburger'], + 'fish': ['fish', 'cod', 'tilapia', 'halibut'], 'salmon': ['salmon'], 'shrimp': ['shrimp', 'prawns'], - 'fish': ['fish', 'cod', 'tilapia', 'halibut', 'pollock'], - # Specific chicken cuts only — bare 'chicken' handled in generic fallback - 'chicken': ['chicken breast', 'chicken thigh', 'chicken wings', 'chicken leg', - 'whole chicken', 'rotisserie chicken', 'raw chicken'], - 'turkey': ['turkey breast', 'whole turkey'], - 'ground_meat': ['ground beef', 'ground pork', 'ground chicken', 'ground turkey', - 'ground lamb', 'ground bison'], - 'pork': ['pork', 'bacon', 'ham', 'pork chop', 'pork loin'], - 'beef': ['beef', 'steak', 'brisket', 'ribeye', 'sirloin', 'roast beef'], - 'deli_meat': ['deli', 'sliced turkey', 'sliced ham', 'lunch meat', 'cold cuts', - 'prosciutto', 'salami', 'pepperoni'], - # ── Produce ─────────────────────────────────────────────────────────── - 'leafy_greens': ['lettuce', 'spinach', 'kale', 'arugula', 'mixed greens'], + 'leafy_greens': ['lettuce', 'spinach', 'kale', 'arugula', 'mixed greens', 'salad'], 'berries': ['strawberries', 'blueberries', 'raspberries', 'blackberries'], 'apples': ['apple', 'apples'], 'bananas': ['banana', 'bananas'], 'citrus': ['orange', 'lemon', 'lime', 'grapefruit', 'tangerine'], - # ── Bakery ──────────────────────────────────────────────────────────── - 'bakery': [ - 'muffin', 'croissant', 'donut', 'danish', 'puff pastry', 'pastry puff', - 'cinnamon roll', 'dinner roll', 'parkerhouse roll', 'scone', - ], - 'bread': ['bread', 'loaf', 'baguette', 'bagel', 'bun', 'pita', 'naan', - 'english muffin', 'sourdough'], - # ── Dry pantry staples ──────────────────────────────────────────────── - 'pasta': ['pasta', 'spaghetti', 'penne', 'macaroni', 'noodles', 'couscous', 'orzo'], - 'rice': ['rice', 'brown rice', 'white rice', 'jasmine rice', 'basmati', - 'spanish rice', 'rice mix'], + 'bread': ['bread', 'loaf', 'baguette', 'roll', 'bagel', 'bun'], + 'bakery': ['muffin', 'croissant', 'donut', 'danish', 'pastry'], + 'deli_meat': ['deli', 'sliced turkey', 'sliced ham', 'lunch meat', 'cold cuts'], + 'frozen_vegetables': ['frozen veg', 'frozen corn', 'frozen peas', 'frozen broccoli'], + 'frozen_fruit': ['frozen berries', 'frozen mango', 'frozen strawberries'], + 'ice_cream': ['ice cream', 'gelato', 'frozen yogurt'], + 'pasta': ['pasta', 'spaghetti', 'penne', 'macaroni', 'noodles'], + 'rice': ['rice', 'brown rice', 'white rice', 'jasmine'], 'cereal': ['cereal', 'granola', 'oatmeal'], - 'chips': ['chips', 'crisps', 'tortilla chips', 'pretzel', 'popcorn'], - 'cookies': ['cookies', 'biscuits', 'crackers', 'graham cracker', 'wafer'], - # ── Beverages ───────────────────────────────────────────────────────── - 'juice': ['juice', 'orange juice', 'apple juice', 'lemonade'], - 'soda': ['soda', 'cola', 'sprite', 'pepsi', 'coke', 'carbonated soft drink'], + 'chips': ['chips', 'crisps', 'tortilla chips'], + 'cookies': ['cookies', 'biscuits', 'crackers'], + 'ketchup': ['ketchup', 'catsup'], + 'mustard': ['mustard'], + 'mayo': ['mayo', 'mayonnaise', 'miracle whip'], + 'salad_dressing': ['salad dressing', 'ranch', 'italian dressing', 'vinaigrette'], + 'soy_sauce': ['soy sauce', 'tamari'], + 'juice': ['juice', 'orange juice', 'apple juice'], + 'soda': ['soda', 'pop', 'cola', 'sprite', 'pepsi', 'coke'], } def __init__(self) -> None: @@ -284,13 +176,8 @@ class ExpirationPredictor: product_name: str, product_category: Optional[str] = None, tags: Optional[List[str]] = None, - location: Optional[str] = None, ) -> Optional[str]: - """Determine category from product name, existing category, and tags. - - location is used as a last-resort hint: unknown items in the freezer - default to frozen_foods rather than dry_goods. - """ + """Determine category from product name, existing category, and tags.""" if product_category: cat = product_category.lower().strip() if cat in self.SHELF_LIFE: @@ -310,36 +197,21 @@ class ExpirationPredictor: if any(kw in name for kw in keywords): return category - # Generic single-word fallbacks — checked after the keyword dict so - # multi-word phrases (e.g. "canned chicken") already matched above. for words, fallback in [ - (['frozen'], 'frozen_foods'), - (['canned', 'tinned'], 'canned_goods'), - # bare 'chicken' / 'sausage' / 'ham' kept here so raw-meat names - # that don't appear in the specific keyword lists still resolve. - (['chicken', 'turkey'], 'poultry'), - (['sausage', 'ham', 'bacon'], 'pork'), - (['beef', 'steak'], 'beef'), - (['meat', 'pork'], 'meat'), + (['meat', 'beef', 'pork', 'chicken'], 'meat'), (['vegetable', 'veggie', 'produce'], 'vegetables'), (['fruit'], 'fruits'), (['dairy'], 'dairy'), + (['frozen'], 'frozen_foods'), ]: if any(w in name for w in words): return fallback - # Location-aware final fallback: unknown item in a freezer → frozen_foods. - # This handles unlabelled frozen products (e.g. "Birthday Littles", - # "Pulled BBQ Crumbles") without requiring every brand name to be listed. - canon_loc = self._normalize_location(location or '') - if canon_loc == 'freezer': - return 'frozen_foods' - return 'dry_goods' def get_shelf_life_info(self, category: str, location: str) -> Optional[int]: """Shelf life in days for a given category + location, or None.""" - return self._lookup_days(category, location) + return self.SHELF_LIFE.get(category.lower().strip(), {}).get(location) def list_categories(self) -> List[str]: return list(self.SHELF_LIFE.keys()) @@ -352,18 +224,8 @@ class ExpirationPredictor: # ── Private helpers ─────────────────────────────────────────────────────── - def _normalize_location(self, location: str) -> str: - """Resolve location aliases to canonical names.""" - loc = location.lower().strip() - return self.LOCATION_ALIASES.get(loc, loc) - def _lookup_days(self, category: Optional[str], location: str) -> Optional[int]: - """Pure deterministic lookup — no I/O. - - Normalises location aliases (e.g. garage_freezer → freezer) and uses - a context-aware fallback order so pantry items don't accidentally get - fridge shelf-life and vice versa. - """ + """Pure deterministic lookup — no I/O.""" if not category: return None cat = category.lower().strip() @@ -375,19 +237,13 @@ class ExpirationPredictor: else: return None - canon_loc = self._normalize_location(location) - shelf = self.SHELF_LIFE[cat] - - # Try the canonical location first, then work through the - # context-aware fallback chain for that location type. - fallback_order = self.LOCATION_FALLBACK.get( - canon_loc, (canon_loc, 'pantry', 'fridge', 'cabinet', 'freezer') - ) - for loc in fallback_order: - days = shelf.get(loc) - if days is not None: - return days - return None + days = self.SHELF_LIFE[cat].get(location) + if days is None: + for loc in ('fridge', 'pantry', 'freezer', 'cabinet'): + days = self.SHELF_LIFE[cat].get(loc) + if days is not None: + break + return days def _llm_predict_days( self, diff --git a/app/services/ocr/docuvision_client.py b/app/services/ocr/docuvision_client.py deleted file mode 100644 index dfa1fed..0000000 --- a/app/services/ocr/docuvision_client.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Thin HTTP client for the cf-docuvision document vision service.""" -from __future__ import annotations - -import base64 -from dataclasses import dataclass -from pathlib import Path - -import httpx - - -@dataclass -class DocuvisionResult: - text: str - confidence: float | None = None - raw: dict | None = None - - -class DocuvisionClient: - """Thin client for the cf-docuvision service.""" - - def __init__(self, base_url: str) -> None: - self._base_url = base_url.rstrip("/") - - def extract_text(self, image_path: str | Path) -> DocuvisionResult: - """Send an image to docuvision and return extracted text.""" - image_bytes = Path(image_path).read_bytes() - b64 = base64.b64encode(image_bytes).decode() - - with httpx.Client(timeout=30.0) as client: - resp = client.post( - f"{self._base_url}/extract", - json={"image": b64}, - ) - resp.raise_for_status() - data = resp.json() - - return DocuvisionResult( - text=data.get("text", ""), - confidence=data.get("confidence"), - raw=data, - ) - - async def extract_text_async(self, image_path: str | Path) -> DocuvisionResult: - """Async version.""" - image_bytes = Path(image_path).read_bytes() - b64 = base64.b64encode(image_bytes).decode() - - async with httpx.AsyncClient(timeout=30.0) as client: - resp = await client.post( - f"{self._base_url}/extract", - json={"image": b64}, - ) - resp.raise_for_status() - data = resp.json() - - return DocuvisionResult( - text=data.get("text", ""), - confidence=data.get("confidence"), - raw=data, - ) diff --git a/app/services/ocr/vl_model.py b/app/services/ocr/vl_model.py index f7580ca..feea1f2 100644 --- a/app/services/ocr/vl_model.py +++ b/app/services/ocr/vl_model.py @@ -8,7 +8,6 @@ OCR with understanding of receipt structure to extract structured JSON data. import json import logging -import os import re from pathlib import Path from typing import Dict, Any, Optional, List @@ -27,32 +26,6 @@ from app.core.config import settings logger = logging.getLogger(__name__) -def _try_docuvision(image_path: str | Path) -> str | None: - """Try to extract text via cf-docuvision. Returns None if unavailable.""" - cf_orch_url = os.environ.get("CF_ORCH_URL") - if not cf_orch_url: - return None - try: - from circuitforge_core.resources import CFOrchClient - from app.services.ocr.docuvision_client import DocuvisionClient - - client = CFOrchClient(cf_orch_url) - with client.allocate( - service="cf-docuvision", - model_candidates=["cf-docuvision"], - ttl_s=60.0, - caller="kiwi-ocr", - ) as alloc: - if alloc is None: - return None - doc_client = DocuvisionClient(alloc.url) - result = doc_client.extract_text(image_path) - return result.text if result.text else None - except Exception as exc: - logger.debug("cf-docuvision fast-path failed, falling back: %s", exc) - return None - - class VisionLanguageOCR: """Vision-Language Model for receipt OCR and structured extraction.""" @@ -67,7 +40,7 @@ class VisionLanguageOCR: self.processor = None self.device = "cuda" if torch.cuda.is_available() and settings.USE_GPU else "cpu" self.use_quantization = use_quantization - self.model_name = "Qwen/Qwen2.5-VL-7B-Instruct" + self.model_name = "Qwen/Qwen2-VL-2B-Instruct" logger.info(f"Initializing VisionLanguageOCR with device: {self.device}") @@ -139,18 +112,6 @@ class VisionLanguageOCR: "warnings": [...] } """ - # Try docuvision fast path first (skips heavy local VLM if available) - docuvision_text = _try_docuvision(image_path) - if docuvision_text is not None: - parsed = self._parse_json_from_text(docuvision_text) - # Only accept the docuvision result if it yielded meaningful content; - # an empty-skeleton dict (no items, no merchant) means the text was - # garbled and we should fall through to the local VLM instead. - if parsed.get("items") or parsed.get("merchant"): - parsed["raw_text"] = docuvision_text - return self._validate_result(parsed) - # Parsed result has no meaningful content — fall through to local VLM - self._load_model() try: diff --git a/app/services/recipe/__init__.py b/app/services/recipe/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/services/recipe/assembly_recipes.py b/app/services/recipe/assembly_recipes.py deleted file mode 100644 index 4a9fe9b..0000000 --- a/app/services/recipe/assembly_recipes.py +++ /dev/null @@ -1,647 +0,0 @@ -""" -Assembly-dish template matcher for Level 1/2. - -Assembly dishes (burritos, stir fry, fried rice, omelettes, sandwiches, etc.) -are defined by structural roles -- container + filler + sauce -- not by a fixed -ingredient list. The corpus can never fully cover them. - -This module fires when the pantry covers all *required* roles of a template. -Results are injected at the top of the Level 1/2 suggestion list with negative -ids (client displays them identically to corpus recipes). - -Templates define: - - required: list of role sets -- ALL must have at least one pantry match - - optional: role sets whose matched items are shown as extras - - directions: short cooking instructions - - notes: serving suggestions / variations -""" -from __future__ import annotations - -import hashlib -from dataclasses import dataclass - -from app.models.schemas.recipe import RecipeSuggestion - - -# IDs in range -100..-1 are reserved for assembly-generated suggestions -_ASSEMBLY_ID_START = -1 - - -@dataclass -class AssemblyRole: - """One role in a template (e.g. 'protein'). - - display: human-readable role label - keywords: substrings matched against pantry item (lowercased) - """ - display: str - keywords: list[str] - - -@dataclass -class AssemblyTemplate: - """A template assembly dish.""" - id: int - title: str - required: list[AssemblyRole] - optional: list[AssemblyRole] - directions: list[str] - notes: str = "" - - -def _matches_role(role: AssemblyRole, pantry_set: set[str]) -> list[str]: - """Return pantry items that satisfy this role. - - Single-word keywords use whole-word matching (word must appear as a - discrete token) so short words like 'pea', 'ham', 'egg' don't false-match - inside longer words like 'peanut', 'hamburger', 'eggnog'. - Multi-word keywords (e.g. 'burger patt') use substring matching. - """ - hits: list[str] = [] - for item in pantry_set: - item_lower = item.lower() - item_words = set(item_lower.split()) - for kw in role.keywords: - if " " in kw: - # Multi-word: substring match - if kw in item_lower: - hits.append(item) - break - else: - # Single-word: whole-word match only - if kw in item_words: - hits.append(item) - break - return hits - - -def _pick_one(items: list[str], seed: int) -> str: - """Deterministically pick one item from a list using a seed.""" - return sorted(items)[seed % len(items)] - - -def _pantry_hash(pantry_set: set[str]) -> int: - """Stable integer derived from pantry contents — used for deterministic picks.""" - key = ",".join(sorted(pantry_set)) - return int(hashlib.md5(key.encode()).hexdigest(), 16) # noqa: S324 — non-crypto use - - -def _keyword_label(item: str, role: AssemblyRole) -> str: - """Return a short, clean label derived from the keyword that matched. - - Uses the longest matching keyword (most specific) as the base label, - then title-cases it. This avoids pasting full raw pantry names like - 'Organic Extra Firm Tofu' into titles — just 'Tofu' instead. - """ - lower = item.lower() - best_kw = "" - for kw in role.keywords: - if kw in lower and len(kw) > len(best_kw): - best_kw = kw - label = (best_kw or item).strip().title() - # Drop trailing 's' from keywords like "beans" → "Bean" when it reads better - return label - - -def _personalized_title(tmpl: AssemblyTemplate, pantry_set: set[str], seed: int) -> str: - """Build a specific title using actual pantry items, e.g. 'Chicken & Broccoli Burrito'. - - Uses the matched keyword as the label (not the full pantry item name) so - 'Organic Extra Firm Tofu Block' → 'Tofu' in the title. - Picks at most two roles; prefers protein then vegetable. - """ - priority_displays = ["protein", "vegetables", "sauce base", "cheese"] - - picked: list[str] = [] - for display in priority_displays: - for role in tmpl.optional: - if role.display != display: - continue - hits = _matches_role(role, pantry_set) - if hits: - item = _pick_one(hits, seed) - label = _keyword_label(item, role) - if label not in picked: - picked.append(label) - if len(picked) >= 2: - break - - if not picked: - return tmpl.title - return f"{' & '.join(picked)} {tmpl.title}" - - -# --------------------------------------------------------------------------- -# Template definitions -# --------------------------------------------------------------------------- - -ASSEMBLY_TEMPLATES: list[AssemblyTemplate] = [ - AssemblyTemplate( - id=-1, - title="Burrito / Taco", - required=[ - AssemblyRole("tortilla or wrap", [ - "tortilla", "wrap", "taco shell", "flatbread", "pita", - ]), - ], - optional=[ - AssemblyRole("protein", [ - "chicken", "beef", "steak", "pork", "sausage", "hamburger", - "burger patt", "shrimp", "egg", "tofu", "beans", "bean", - ]), - AssemblyRole("rice or starch", ["rice", "quinoa", "potato"]), - AssemblyRole("cheese", [ - "cheese", "cheddar", "mozzarella", "monterey", "queso", - ]), - AssemblyRole("salsa or sauce", [ - "salsa", "hot sauce", "taco sauce", "enchilada", "guacamole", - ]), - AssemblyRole("sour cream or yogurt", ["sour cream", "greek yogurt", "crema"]), - AssemblyRole("vegetables", [ - "pepper", "onion", "tomato", "lettuce", "corn", "avocado", - "spinach", "broccoli", "zucchini", - ]), - ], - directions=[ - "Warm the tortilla in a dry skillet or microwave for 20 seconds.", - "Heat any proteins or vegetables in a pan until cooked through.", - "Layer ingredients down the center: rice first, then protein, then vegetables.", - "Add cheese, salsa, and sour cream last so they stay cool.", - "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).", - ), - AssemblyTemplate( - id=-2, - title="Fried Rice", - required=[ - AssemblyRole("cooked rice", [ - "rice", "leftover rice", "instant rice", "microwavable rice", - ]), - ], - optional=[ - AssemblyRole("protein", [ - "chicken", "beef", "pork", "shrimp", "egg", "tofu", - "sausage", "ham", "spam", - ]), - AssemblyRole("soy sauce or seasoning", [ - "soy sauce", "tamari", "teriyaki", "oyster sauce", "fish sauce", - ]), - AssemblyRole("oil", ["oil", "butter", "sesame"]), - AssemblyRole("egg", ["egg"]), - AssemblyRole("vegetables", [ - "carrot", "peas", "corn", "onion", "scallion", "green onion", - "broccoli", "bok choy", "bean sprout", "zucchini", "spinach", - ]), - AssemblyRole("garlic or ginger", ["garlic", "ginger"]), - ], - directions=[ - "Use day-old cold rice if available -- it fries better than fresh.", - "Heat oil in a large skillet or wok over high heat.", - "Add garlic/ginger and any raw vegetables; stir fry 2-3 minutes.", - "Push to the side, scramble eggs in the same pan if using.", - "Add protein (pre-cooked or raw) and cook through.", - "Add rice, breaking up clumps. Stir fry until heated and lightly toasted.", - "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.", - ), - AssemblyTemplate( - id=-3, - title="Omelette / Scramble", - required=[ - AssemblyRole("eggs", ["egg"]), - ], - optional=[ - AssemblyRole("cheese", [ - "cheese", "cheddar", "mozzarella", "feta", "parmesan", - ]), - AssemblyRole("vegetables", [ - "pepper", "onion", "tomato", "spinach", "mushroom", - "broccoli", "zucchini", "scallion", "avocado", - ]), - AssemblyRole("protein", [ - "ham", "bacon", "sausage", "chicken", "turkey", - "smoked salmon", - ]), - AssemblyRole("herbs or seasoning", [ - "herb", "basil", "chive", "parsley", "salt", "pepper", - "hot sauce", "salsa", - ]), - ], - directions=[ - "Beat eggs with a splash of water or milk and a pinch of salt.", - "Saute any vegetables and proteins in butter or oil over medium heat until softened.", - "Pour eggs over fillings (scramble) or pour into a clean buttered pan (omelette).", - "For omelette: cook until nearly set, add fillings to one side, fold over.", - "For scramble: stir gently over medium-low heat until just set.", - "Season and serve immediately.", - ], - notes="Works for breakfast, lunch, or a quick dinner. Any leftover vegetables work well.", - ), - AssemblyTemplate( - id=-4, - title="Stir Fry", - required=[ - AssemblyRole("vegetables", [ - "pepper", "broccoli", "carrot", "snap pea", "bok choy", - "zucchini", "mushroom", "corn", "onion", "bean sprout", - "cabbage", "spinach", "asparagus", - ]), - ], - optional=[ - AssemblyRole("protein", [ - "chicken", "beef", "pork", "shrimp", "tofu", "egg", - ]), - AssemblyRole("sauce", [ - "soy sauce", "teriyaki", "oyster sauce", "hoisin", - "stir fry sauce", "sesame", - ]), - AssemblyRole("starch base", ["rice", "noodle", "pasta", "ramen"]), - AssemblyRole("garlic or ginger", ["garlic", "ginger"]), - AssemblyRole("oil", ["oil", "sesame"]), - ], - directions=[ - "Cut all proteins and vegetables into similar-sized pieces for even cooking.", - "Heat oil in a wok or large skillet over the highest heat your stove allows.", - "Cook protein first until nearly done; remove and set aside.", - "Add dense vegetables (carrots, broccoli) first; quick-cooking veg last.", - "Return protein, add sauce, and toss everything together for 1-2 minutes.", - "Serve over rice or noodles.", - ], - notes="High heat is the key. Do not crowd the pan -- cook in batches if needed.", - ), - AssemblyTemplate( - id=-5, - title="Pasta with Whatever You Have", - required=[ - AssemblyRole("pasta", [ - "pasta", "spaghetti", "penne", "fettuccine", "rigatoni", - "linguine", "rotini", "farfalle", "macaroni", "noodle", - ]), - ], - optional=[ - AssemblyRole("sauce base", [ - "tomato", "marinara", "pasta sauce", "cream", "butter", - "olive oil", "pesto", - ]), - AssemblyRole("protein", [ - "chicken", "beef", "pork", "shrimp", "sausage", "bacon", - "ham", "tuna", "canned fish", - ]), - AssemblyRole("cheese", [ - "parmesan", "romano", "mozzarella", "ricotta", "feta", - ]), - AssemblyRole("vegetables", [ - "tomato", "spinach", "mushroom", "pepper", "zucchini", - "broccoli", "artichoke", "olive", "onion", - ]), - AssemblyRole("garlic", ["garlic"]), - ], - directions=[ - "Cook pasta in well-salted boiling water until al dente. Reserve 1 cup pasta water.", - "While pasta cooks, saute garlic in olive oil over medium heat.", - "Add proteins and cook through; add vegetables until tender.", - "Add sauce base and simmer 5 minutes. Add pasta water to loosen if needed.", - "Toss cooked pasta with sauce. Finish with cheese if using.", - ], - notes="Pasta water is the secret -- the starch thickens and binds any sauce.", - ), - AssemblyTemplate( - id=-6, - title="Sandwich / Wrap", - required=[ - AssemblyRole("bread or wrap", [ - "bread", "roll", "bun", "wrap", "tortilla", "pita", - "bagel", "english muffin", "croissant", "flatbread", - ]), - ], - optional=[ - AssemblyRole("protein", [ - "chicken", "turkey", "ham", "roast beef", "tuna", "egg", - "bacon", "salami", "pepperoni", "tofu", "tempeh", - ]), - AssemblyRole("cheese", [ - "cheese", "cheddar", "swiss", "provolone", "mozzarella", - ]), - AssemblyRole("condiment", [ - "mayo", "mustard", "ketchup", "hot sauce", "ranch", - "hummus", "pesto", "aioli", - ]), - AssemblyRole("vegetables", [ - "lettuce", "tomato", "onion", "cucumber", "avocado", - "pepper", "sprout", "arugula", - ]), - ], - directions=[ - "Toast bread if desired.", - "Spread condiments on both inner surfaces.", - "Layer protein first, then cheese, then vegetables.", - "Press together and cut diagonally.", - ], - notes="Leftovers, deli meat, canned fish -- nearly anything works between bread.", - ), - AssemblyTemplate( - id=-7, - title="Grain Bowl", - required=[ - AssemblyRole("grain base", [ - "rice", "quinoa", "farro", "barley", "couscous", - "bulgur", "freekeh", "polenta", - ]), - ], - optional=[ - AssemblyRole("protein", [ - "chicken", "beef", "pork", "tofu", "egg", "shrimp", - "beans", "bean", "lentil", "chickpea", - ]), - AssemblyRole("vegetables", [ - "roasted", "broccoli", "carrot", "kale", "spinach", - "cucumber", "tomato", "corn", "edamame", "avocado", - "beet", "sweet potato", - ]), - AssemblyRole("dressing or sauce", [ - "dressing", "tahini", "vinaigrette", "sauce", - "olive oil", "lemon", "soy sauce", - ]), - AssemblyRole("toppings", [ - "nut", "seed", "feta", "parmesan", "herb", - ]), - ], - directions=[ - "Cook grain base according to package directions; season with salt.", - "Roast or saute vegetables with oil, salt, and pepper until tender.", - "Cook or slice protein.", - "Arrange grain in a bowl, top with protein and vegetables.", - "Drizzle with dressing and add toppings.", - ], - notes="Great for meal prep -- cook grains and proteins in bulk, assemble bowls all week.", - ), - AssemblyTemplate( - id=-8, - title="Soup / Stew", - required=[ - AssemblyRole("broth or liquid base", [ - "broth", "stock", "bouillon", - "tomato sauce", "coconut milk", "cream of", - ]), - ], - optional=[ - AssemblyRole("protein", [ - "chicken", "beef", "pork", "sausage", "shrimp", - "beans", "bean", "lentil", "tofu", - ]), - AssemblyRole("vegetables", [ - "carrot", "celery", "onion", "potato", "tomato", - "spinach", "kale", "corn", "pea", "zucchini", - ]), - AssemblyRole("starch thickener", [ - "potato", "pasta", "noodle", "rice", "barley", - "flour", "cornstarch", - ]), - AssemblyRole("seasoning", [ - "garlic", "herb", "bay leaf", "thyme", "rosemary", - "cumin", "paprika", "chili", - ]), - ], - directions=[ - "Saute onion, celery, and garlic in oil until softened, about 5 minutes.", - "Add any raw proteins and cook until browned.", - "Add broth or liquid base and bring to a simmer.", - "Add dense vegetables (carrots, potatoes) first; quick-cooking veg in the last 10 minutes.", - "Add starches and cook until tender.", - "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.", - ), - AssemblyTemplate( - id=-9, - title="Casserole / Bake", - required=[ - AssemblyRole("starch or base", [ - "pasta", "rice", "potato", "noodle", "bread", - "tortilla", "polenta", "grits", "macaroni", - ]), - AssemblyRole("binder or sauce", [ - "cream of", "cheese", "cream cheese", "sour cream", - "soup mix", "gravy", "tomato sauce", "marinara", - "broth", "stock", "milk", "cream", - ]), - ], - optional=[ - AssemblyRole("protein", [ - "chicken", "beef", "pork", "tuna", "ham", "sausage", - "ground", "shrimp", "beans", "bean", "lentil", - ]), - AssemblyRole("vegetables", [ - "broccoli", "corn", "pea", "onion", "mushroom", - "spinach", "zucchini", "tomato", "pepper", "carrot", - ]), - AssemblyRole("cheese topping", [ - "cheddar", "mozzarella", "parmesan", "swiss", - "cheese", "breadcrumb", - ]), - AssemblyRole("seasoning", [ - "garlic", "herb", "thyme", "rosemary", "paprika", - "onion powder", "salt", "pepper", - ]), - ], - directions=[ - "Preheat oven to 375 F (190 C). Grease a 9x13 baking dish.", - "Cook starch base (pasta, rice, potato) until just underdone -- it finishes in the oven.", - "Mix cooked starch with sauce/binder, protein, and vegetables in the dish.", - "Season generously -- casseroles need salt.", - "Top with cheese or breadcrumbs if using.", - "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.", - ), - AssemblyTemplate( - id=-10, - title="Pancakes / Waffles / Quick Bread", - required=[ - AssemblyRole("flour or baking mix", [ - "flour", "bisquick", "pancake mix", "waffle mix", - "baking mix", "cornmeal", "oats", - ]), - AssemblyRole("leavening or egg", [ - "egg", "baking powder", "baking soda", "yeast", - ]), - ], - optional=[ - AssemblyRole("liquid", [ - "milk", "buttermilk", "water", "juice", - "almond milk", "oat milk", "sour cream", - ]), - AssemblyRole("fat", [ - "butter", "oil", "margarine", - ]), - AssemblyRole("sweetener", [ - "sugar", "honey", "maple syrup", "brown sugar", - ]), - AssemblyRole("mix-ins", [ - "blueberr", "banana", "apple", "chocolate chip", - "nut", "berry", "cinnamon", "vanilla", - ]), - ], - directions=[ - "Whisk dry ingredients (flour, leavening, sugar, salt) together in a bowl.", - "Whisk wet ingredients (egg, milk, melted butter) in a separate bowl.", - "Fold wet into dry until just combined -- lumps are fine, do not overmix.", - "For pancakes: cook on a buttered griddle over medium heat, flip when bubbles form.", - "For waffles: pour into preheated waffle iron according to manufacturer instructions.", - "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.", - ), - AssemblyTemplate( - id=-11, - title="Porridge / Oatmeal", - required=[ - AssemblyRole("oats or grain porridge", [ - "oat", "porridge", "grits", "semolina", "cream of wheat", - "polenta", "congee", "rice porridge", - ]), - ], - optional=[ - AssemblyRole("liquid", ["milk", "water", "almond milk", "oat milk", "coconut milk"]), - AssemblyRole("sweetener", ["sugar", "honey", "maple syrup", "brown sugar", "agave"]), - AssemblyRole("fruit", ["banana", "berry", "apple", "raisin", "date", "mango"]), - AssemblyRole("toppings", ["nut", "seed", "granola", "coconut", "chocolate"]), - AssemblyRole("spice", ["cinnamon", "nutmeg", "vanilla", "cardamom"]), - ], - directions=[ - "Combine oats with liquid in a pot — typically 1 part oats to 2 parts liquid.", - "Bring to a gentle simmer over medium heat, stirring occasionally.", - "Cook 5 minutes (rolled oats) or 2 minutes (quick oats) until thickened to your liking.", - "Stir in sweetener and spices.", - "Top with fruit, nuts, or seeds and serve immediately.", - ], - notes="Overnight oats: skip cooking — soak oats in cold milk overnight in the fridge.", - ), - AssemblyTemplate( - id=-12, - title="Pie / Pot Pie", - required=[ - AssemblyRole("pastry or crust", [ - "pastry", "puff pastry", "pie crust", "shortcrust", - "pie shell", "phyllo", "filo", "biscuit", - ]), - ], - optional=[ - AssemblyRole("protein filling", [ - "chicken", "beef", "pork", "lamb", "turkey", "tofu", - "mushroom", "beans", "bean", "lentil", "tuna", "salmon", - ]), - AssemblyRole("vegetables", [ - "carrot", "pea", "corn", "potato", "onion", "leek", - "broccoli", "spinach", "mushroom", "parsnip", "swede", - ]), - AssemblyRole("sauce or binder", [ - "gravy", "cream of", "stock", "broth", "cream", - "white sauce", "bechamel", "cheese sauce", - ]), - AssemblyRole("seasoning", [ - "thyme", "rosemary", "sage", "garlic", "herb", - "mustard", "worcestershire", - ]), - AssemblyRole("sweet filling", [ - "apple", "berry", "cherry", "pear", "peach", - "rhubarb", "plum", "custard", - ]), - ], - directions=[ - "For pot pie: make a sauce by combining stock or cream-of-something with cooked vegetables and protein.", - "Season generously — fillings need more salt than you think.", - "Pour filling into a baking dish and top with pastry, pressing edges to seal.", - "Cut a few slits in the top to release steam. Brush with egg wash or milk if available.", - "Bake at 400 F (200 C) for 25-35 minutes until pastry is golden brown.", - "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.", - ), - AssemblyTemplate( - id=-13, - title="Pudding / Custard", - required=[ - AssemblyRole("dairy or dairy-free milk", [ - "milk", "cream", "oat milk", "almond milk", - "soy milk", "coconut milk", - ]), - AssemblyRole("thickener or set", [ - "egg", "cornstarch", "custard powder", "gelatin", - "agar", "tapioca", "arrowroot", - ]), - ], - optional=[ - AssemblyRole("sweetener", ["sugar", "honey", "maple syrup", "condensed milk"]), - AssemblyRole("flavouring", [ - "vanilla", "chocolate", "cocoa", "caramel", - "lemon", "orange", "cinnamon", "nutmeg", - ]), - AssemblyRole("starchy base", [ - "rice", "bread", "sponge", "cake", "biscuit", - ]), - AssemblyRole("fruit", ["raisin", "sultana", "berry", "banana", "apple"]), - ], - directions=[ - "For stovetop custard: whisk eggs and sugar together, heat milk until steaming.", - "Slowly pour hot milk into egg mixture while whisking constantly (tempering).", - "Return to low heat and stir until mixture coats the back of a spoon.", - "For cornstarch pudding: whisk cornstarch into cold milk first, then heat while stirring.", - "Add flavourings (vanilla, cocoa) once off heat.", - "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.", - ), -] - - -# --------------------------------------------------------------------------- -# Public API -# --------------------------------------------------------------------------- - -def match_assembly_templates( - pantry_items: list[str], - pantry_set: set[str], - excluded_ids: list[int], -) -> list[RecipeSuggestion]: - """Return assembly-dish suggestions whose required roles are all satisfied. - - Titles are personalized with specific pantry items (deterministically chosen - from the pantry contents so the same pantry always produces the same title). - Skips templates whose id is in excluded_ids (dismiss/load-more support). - """ - excluded = set(excluded_ids) - seed = _pantry_hash(pantry_set) - results: list[RecipeSuggestion] = [] - - for tmpl in ASSEMBLY_TEMPLATES: - if tmpl.id in excluded: - continue - - # All required roles must be satisfied - if any(not _matches_role(role, pantry_set) for role in tmpl.required): - continue - - optional_hit_count = sum( - 1 for role in tmpl.optional if _matches_role(role, pantry_set) - ) - - results.append(RecipeSuggestion( - id=tmpl.id, - title=_personalized_title(tmpl, pantry_set, seed + tmpl.id), - match_count=len(tmpl.required) + optional_hit_count, - element_coverage={}, - swap_candidates=[], - missing_ingredients=[], - directions=tmpl.directions, - notes=tmpl.notes, - level=1, - is_wildcard=False, - nutrition=None, - )) - - # Sort by optional coverage descending — best-matched templates first - results.sort(key=lambda s: s.match_count, reverse=True) - return results diff --git a/app/services/recipe/element_classifier.py b/app/services/recipe/element_classifier.py deleted file mode 100644 index 991aa00..0000000 --- a/app/services/recipe/element_classifier.py +++ /dev/null @@ -1,135 +0,0 @@ -""" -ElementClassifier -- classify pantry items into culinary element tags. - -Lookup order: - 1. ingredient_profiles table (pre-computed from USDA FDC) - 2. Keyword heuristic fallback (for unlisted ingredients) -""" -from __future__ import annotations - -import json -from dataclasses import dataclass, field -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from app.db.store import Store - -# All valid ingredient-level element labels (Method is recipe-level, not ingredient-level) -ELEMENTS = frozenset({ - "Seasoning", "Richness", "Brightness", "Depth", - "Aroma", "Structure", "Texture", -}) - -_HEURISTIC: list[tuple[list[str], str]] = [ - (["vinegar", "lemon", "lime", "citrus", "wine", "yogurt", "kefir", - "buttermilk", "tomato", "tamarind"], "Brightness"), - (["oil", "butter", "cream", "lard", "fat", "avocado", "coconut milk", - "ghee", "shortening", "crisco"], "Richness"), - (["salt", "soy", "miso", "tamari", "fish sauce", "worcestershire", - "anchov", "capers", "olive", "brine"], "Seasoning"), - (["mushroom", "parmesan", "miso", "nutritional yeast", "bouillon", - "broth", "umami", "anchov", "dried tomato", "soy"], "Depth"), - (["garlic", "onion", "shallot", "herb", "basil", "oregano", "thyme", - "rosemary", "spice", "cumin", "coriander", "paprika", "chili", - "ginger", "cinnamon", "pepper", "cilantro", "dill", "fennel", - "cardamom", "turmeric", "smoke"], "Aroma"), - (["flour", "starch", "cornstarch", "arrowroot", "egg", "gelatin", - "agar", "breadcrumb", "panko", "roux"], "Structure"), - (["nut", "seed", "cracker", "crisp", "wafer", "chip", "crouton", - "granola", "tofu", "tempeh"], "Texture"), -] - - -def _safe_json_list(val) -> list: - if isinstance(val, list): - return val - if isinstance(val, str): - try: - return json.loads(val) - except Exception: - return [] - return [] - - -@dataclass(frozen=True) -class IngredientProfile: - name: str - elements: list[str] - fat_pct: float = 0.0 - fat_saturated_pct: float = 0.0 - moisture_pct: float = 0.0 - protein_pct: float = 0.0 - starch_pct: float = 0.0 - binding_score: int = 0 - glutamate_mg: float = 0.0 - ph_estimate: float | None = None - flavor_molecule_ids: list[str] = field(default_factory=list) - heat_stable: bool = True - add_timing: str = "any" - acid_type: str | None = None - sodium_mg_per_100g: float = 0.0 - is_fermented: bool = False - texture_profile: str = "neutral" - smoke_point_c: float | None = None - is_emulsifier: bool = False - source: str = "heuristic" - - -class ElementClassifier: - def __init__(self, store: "Store") -> None: - self._store = store - - def classify(self, ingredient_name: str) -> IngredientProfile: - """Return element profile for a single ingredient name.""" - name = ingredient_name.lower().strip() - if not name: - return IngredientProfile(name="", elements=[], source="heuristic") - row = self._store._fetch_one( - "SELECT * FROM ingredient_profiles WHERE name = ?", (name,) - ) - if row: - return self._row_to_profile(row) - return self._heuristic_profile(name) - - def classify_batch(self, names: list[str]) -> list[IngredientProfile]: - return [self.classify(n) for n in names] - - def identify_gaps(self, profiles: list[IngredientProfile]) -> list[str]: - """Return element names that have no coverage in the given profile list.""" - covered = set() - for p in profiles: - covered.update(p.elements) - return sorted(ELEMENTS - covered) - - def _row_to_profile(self, row: dict) -> IngredientProfile: - return IngredientProfile( - name=row["name"], - elements=_safe_json_list(row.get("elements")), - fat_pct=row.get("fat_pct") or 0.0, - fat_saturated_pct=row.get("fat_saturated_pct") or 0.0, - moisture_pct=row.get("moisture_pct") or 0.0, - protein_pct=row.get("protein_pct") or 0.0, - starch_pct=row.get("starch_pct") or 0.0, - binding_score=row.get("binding_score") or 0, - glutamate_mg=row.get("glutamate_mg") or 0.0, - ph_estimate=row.get("ph_estimate"), - flavor_molecule_ids=_safe_json_list(row.get("flavor_molecule_ids")), - heat_stable=bool(row.get("heat_stable", 1)), - add_timing=row.get("add_timing") or "any", - acid_type=row.get("acid_type"), - sodium_mg_per_100g=row.get("sodium_mg_per_100g") or 0.0, - is_fermented=bool(row.get("is_fermented", 0)), - texture_profile=row.get("texture_profile") or "neutral", - smoke_point_c=row.get("smoke_point_c"), - is_emulsifier=bool(row.get("is_emulsifier", 0)), - source="db", - ) - - def _heuristic_profile(self, name: str) -> IngredientProfile: - seen: set[str] = set() - elements: list[str] = [] - for keywords, element in _HEURISTIC: - if element not in seen and any(kw in name for kw in keywords): - elements.append(element) - seen.add(element) - return IngredientProfile(name=name, elements=elements, source="heuristic") diff --git a/app/services/recipe/grocery_links.py b/app/services/recipe/grocery_links.py deleted file mode 100644 index c974c60..0000000 --- a/app/services/recipe/grocery_links.py +++ /dev/null @@ -1,75 +0,0 @@ -""" -GroceryLinkBuilder — affiliate deeplinks for missing ingredient grocery lists. - -Free tier: URL construction only (Amazon Fresh, Walmart, Instacart). -Paid+: live product search API (stubbed — future task). - -Config (env vars, all optional — missing = retailer disabled): - AMAZON_AFFILIATE_TAG — e.g. "circuitforge-20" - INSTACART_AFFILIATE_ID — e.g. "circuitforge" - WALMART_AFFILIATE_ID — e.g. "circuitforge" (Impact affiliate network) -""" -from __future__ import annotations - -import os -from urllib.parse import quote_plus - -from app.models.schemas.recipe import GroceryLink - - -def _amazon_link(ingredient: str, tag: str) -> GroceryLink: - q = quote_plus(ingredient) - url = f"https://www.amazon.com/s?k={q}&i=amazonfresh&tag={tag}" - return GroceryLink(ingredient=ingredient, retailer="Amazon Fresh", url=url) - - -def _walmart_link(ingredient: str, affiliate_id: str) -> GroceryLink: - q = quote_plus(ingredient) - # Walmart Impact affiliate deeplink pattern - url = f"https://goto.walmart.com/c/{affiliate_id}/walmart?u=https://www.walmart.com/search?q={q}" - return GroceryLink(ingredient=ingredient, retailer="Walmart Grocery", url=url) - - -def _instacart_link(ingredient: str, affiliate_id: str) -> GroceryLink: - q = quote_plus(ingredient) - url = f"https://www.instacart.com/store/s?k={q}&aff={affiliate_id}" - return GroceryLink(ingredient=ingredient, retailer="Instacart", url=url) - - -class GroceryLinkBuilder: - def __init__(self, tier: str = "free", has_byok: bool = False) -> None: - self._tier = tier - self._has_byok = has_byok - self._amazon_tag = os.environ.get("AMAZON_AFFILIATE_TAG", "") - self._instacart_id = os.environ.get("INSTACART_AFFILIATE_ID", "") - self._walmart_id = os.environ.get("WALMART_AFFILIATE_ID", "") - - def build_links(self, ingredient: str) -> list[GroceryLink]: - """Build affiliate deeplinks for a single ingredient. - - Free tier: URL construction only. - Paid+: would call live product search APIs (stubbed). - """ - if not ingredient.strip(): - return [] - links: list[GroceryLink] = [] - - if self._amazon_tag: - links.append(_amazon_link(ingredient, self._amazon_tag)) - if self._walmart_id: - links.append(_walmart_link(ingredient, self._walmart_id)) - if self._instacart_id: - links.append(_instacart_link(ingredient, self._instacart_id)) - - # Paid+: live API stub (future task) - # if self._tier in ("paid", "premium") and not self._has_byok: - # links.extend(self._search_kroger_api(ingredient)) - - return links - - def build_all(self, ingredients: list[str]) -> list[GroceryLink]: - """Build links for a list of ingredients.""" - links: list[GroceryLink] = [] - for ingredient in ingredients: - links.extend(self.build_links(ingredient)) - return links diff --git a/app/services/recipe/llm_recipe.py b/app/services/recipe/llm_recipe.py deleted file mode 100644 index 11ccd02..0000000 --- a/app/services/recipe/llm_recipe.py +++ /dev/null @@ -1,313 +0,0 @@ -"""LLM-driven recipe generator for Levels 3 and 4.""" -from __future__ import annotations - -import logging -import os -import re -from contextlib import nullcontext -from typing import TYPE_CHECKING - -from openai import OpenAI - -if TYPE_CHECKING: - from app.db.store import Store - -from app.models.schemas.recipe import RecipeRequest, RecipeResult, RecipeSuggestion -from app.services.recipe.element_classifier import IngredientProfile -from app.services.recipe.style_adapter import StyleAdapter - -logger = logging.getLogger(__name__) - - -def _filter_allergies(pantry_items: list[str], allergies: list[str]) -> list[str]: - """Return pantry items with allergy matches removed (bidirectional substring).""" - if not allergies: - return list(pantry_items) - return [ - item for item in pantry_items - if not any( - allergy.lower() in item.lower() or item.lower() in allergy.lower() - for allergy in allergies - ) - ] - - -class LLMRecipeGenerator: - def __init__(self, store: "Store") -> None: - self._store = store - self._style_adapter = StyleAdapter() - - def build_level3_prompt( - self, - req: RecipeRequest, - profiles: list[IngredientProfile], - gaps: list[str], - ) -> str: - """Build a structured element-scaffold prompt for Level 3.""" - allergy_list = req.allergies - safe_pantry = _filter_allergies(req.pantry_items, allergy_list) - - covered_elements: list[str] = [] - for profile in profiles: - for element in profile.elements: - if element not in covered_elements: - covered_elements.append(element) - - lines: list[str] = [ - "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. Plain yoghurt, plain cream, and plain dairy are fine in savoury cooking.", - "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(safe_pantry)}", - ] - - if req.constraints: - lines.append(f"Dietary constraints: {', '.join(req.constraints)}") - - if allergy_list: - lines.append(f"IMPORTANT — must NOT contain: {', '.join(allergy_list)}") - - lines.append("") - lines.append(f"Covered culinary elements: {', '.join(covered_elements) or 'none'}") - - if gaps: - lines.append( - f"Missing elements to address: {', '.join(gaps)}. " - "Incorporate ingredients or techniques to fill these gaps." - ) - - if req.style_id: - template = self._style_adapter.get(req.style_id) - if template: - lines.append(f"Cuisine style: {template.name}") - if template.aromatics: - lines.append(f"Preferred aromatics: {', '.join(template.aromatics[:4])}") - - lines += [ - "", - "Reply using EXACTLY this plain-text format — no markdown, no bold, no extra commentary:", - "Title: ", - "Ingredients: ", - "Directions:", - "1. ", - "2. ", - "3. ", - "Notes: ", - ] - - return "\n".join(lines) - - def build_level4_prompt( - self, - req: RecipeRequest, - ) -> str: - """Build a minimal wildcard prompt for Level 4.""" - allergy_list = req.allergies - safe_pantry = _filter_allergies(req.pantry_items, allergy_list) - - lines: list[str] = [ - "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(safe_pantry)}", - ] - - if req.constraints: - lines.append(f"Constraints: {', '.join(req.constraints)}") - - if allergy_list: - lines.append(f"Must NOT contain: {', '.join(allergy_list)}") - - lines += [ - "Treat any mystery ingredient as a wildcard — use your imagination.", - "Reply using EXACTLY this plain-text format — no markdown, no bold:", - "Title: ", - "Ingredients: ", - "Directions:", - "1. ", - "2. ", - "Notes: ", - ] - - return "\n".join(lines) - - _MODEL_CANDIDATES: list[str] = ["Ouro-2.6B-Thinking", "Ouro-1.4B"] - - def _get_llm_context(self): - """Return a sync context manager that yields an Allocation or None. - - When CF_ORCH_URL is set, uses CFOrchClient to acquire a vLLM allocation - (which handles service lifecycle and VRAM). Falls back to nullcontext(None) - when the env var is absent or CFOrchClient raises on construction. - """ - cf_orch_url = os.environ.get("CF_ORCH_URL") - if cf_orch_url: - try: - from circuitforge_core.resources import CFOrchClient - client = CFOrchClient(cf_orch_url) - return client.allocate( - service="vllm", - model_candidates=self._MODEL_CANDIDATES, - ttl_s=300.0, - caller="kiwi-recipe", - ) - except Exception as exc: - logger.debug("CFOrchClient init failed, falling back to direct URL: %s", exc) - return nullcontext(None) - - def _call_llm(self, prompt: str) -> str: - """Call the LLM, using CFOrchClient allocation when CF_ORCH_URL is set. - - With CF_ORCH_URL set: acquires a vLLM allocation via CFOrchClient and - calls the OpenAI-compatible API directly against the allocated service URL. - Without CF_ORCH_URL: falls back to LLMRouter using its configured backends. - """ - try: - with self._get_llm_context() as alloc: - if alloc is not None: - base_url = alloc.url.rstrip("/") + "/v1" - client = OpenAI(base_url=base_url, api_key="any") - model = alloc.model or "__auto__" - if model == "__auto__": - model = client.models.list().data[0].id - resp = client.chat.completions.create( - model=model, - messages=[{"role": "user", "content": prompt}], - ) - return resp.choices[0].message.content or "" - else: - from circuitforge_core.llm.router import LLMRouter - router = LLMRouter() - return router.complete(prompt) - except Exception as exc: - logger.error("LLM call failed: %s", exc) - return "" - - # Strips markdown bold/italic markers so "**Directions:**" parses like "Directions:" - _MD_BOLD = re.compile(r"\*{1,2}([^*]+)\*{1,2}") - - def _strip_md(self, text: str) -> str: - return self._MD_BOLD.sub(r"\1", text).strip() - - def _parse_response(self, response: str) -> dict[str, str | list[str]]: - """Parse LLM response text into structured recipe fields. - - Handles both plain-text and markdown-formatted responses. Directions are - preserved as newline-separated text so the caller can split on step numbers. - """ - result: dict[str, str | list[str]] = { - "title": "", - "ingredients": [], - "directions": "", - "notes": "", - } - - current_key: str | None = None - buffer: list[str] = [] - - def _flush(key: str | None, buf: list[str]) -> None: - if key is None or not buf: - return - if key == "directions": - result["directions"] = "\n".join(buf) - elif key == "ingredients": - text = " ".join(buf) - result["ingredients"] = [i.strip() for i in text.split(",") if i.strip()] - else: - result[key] = " ".join(buf).strip() - - for raw_line in response.splitlines(): - line = self._strip_md(raw_line) - lower = line.lower() - if lower.startswith("title:"): - _flush(current_key, buffer) - current_key, buffer = "title", [line.split(":", 1)[1].strip()] - elif lower.startswith("ingredients:"): - _flush(current_key, buffer) - current_key, buffer = "ingredients", [line.split(":", 1)[1].strip()] - elif lower.startswith("directions:"): - _flush(current_key, buffer) - rest = line.split(":", 1)[1].strip() - current_key, buffer = "directions", ([rest] if rest else []) - elif lower.startswith("notes:"): - _flush(current_key, buffer) - current_key, buffer = "notes", [line.split(":", 1)[1].strip()] - elif current_key and line.strip(): - buffer.append(line.strip()) - elif current_key is None and line.strip() and ":" not in line: - # Before any section header: a 2-10 word colon-free line is the dish name - words = line.split() - if 2 <= len(words) <= 10 and not result["title"]: - result["title"] = line.strip() - - _flush(current_key, buffer) - return result - - def generate( - self, - req: RecipeRequest, - profiles: list[IngredientProfile], - gaps: list[str], - ) -> RecipeResult: - """Generate a recipe via LLM and return a RecipeResult.""" - if req.level == 4: - prompt = self.build_level4_prompt(req) - else: - prompt = self.build_level3_prompt(req, profiles, gaps) - - response = self._call_llm(prompt) - - if not response: - return RecipeResult(suggestions=[], element_gaps=gaps) - - parsed = self._parse_response(response) - - raw_directions = parsed.get("directions", "") - if isinstance(raw_directions, str): - # Split on newlines; strip leading step numbers ("1.", "2.", "- ", "* ") - _step_prefix = re.compile(r"^\s*(?:\d+[.)]\s*|[-*]\s+)") - directions_list = [ - _step_prefix.sub("", s).strip() - for s in raw_directions.splitlines() - if s.strip() - ] - else: - directions_list = list(raw_directions) - raw_notes = parsed.get("notes", "") - notes_str: str = raw_notes if isinstance(raw_notes, str) else "" - - all_ingredients: list[str] = list(parsed.get("ingredients", [])) - pantry_set = {item.lower() for item in (req.pantry_items or [])} - - # Strip leading quantities/units (e.g. "2 cups rice" → "rice") before - # checking against pantry, since LLMs return formatted ingredient strings. - _qty_re = re.compile( - r"^\s*[\d½¼¾⅓⅔]+[\s/\-]*" # leading digits or fractions - r"(?:cup|cups|tbsp|tsp|tablespoon|teaspoon|oz|lb|lbs|g|kg|" - r"can|cans|clove|cloves|bunch|package|pkg|slice|slices|" - r"piece|pieces|pinch|dash|handful|head|heads|large|small|medium" - r")s?\b[,\s]*", - re.IGNORECASE, - ) - missing = [] - for ing in all_ingredients: - bare = _qty_re.sub("", ing).strip().lower() - if bare not in pantry_set and ing.lower() not in pantry_set: - missing.append(bare or ing) - - suggestion = RecipeSuggestion( - id=0, - title=parsed.get("title") or "LLM Recipe", - match_count=len(req.pantry_items), - element_coverage={}, - missing_ingredients=missing, - directions=directions_list, - notes=notes_str, - level=req.level, - is_wildcard=(req.level == 4), - ) - - return RecipeResult( - suggestions=[suggestion], - element_gaps=gaps, - ) diff --git a/app/services/recipe/recipe_engine.py b/app/services/recipe/recipe_engine.py deleted file mode 100644 index febf32f..0000000 --- a/app/services/recipe/recipe_engine.py +++ /dev/null @@ -1,583 +0,0 @@ -""" -RecipeEngine — orchestrates the four creativity levels. - -Level 1: corpus lookup ranked by ingredient match + expiry urgency -Level 2: Level 1 + deterministic substitution swaps -Level 3: element scaffold → LLM constrained prompt (see llm_recipe.py) -Level 4: wildcard LLM (see llm_recipe.py) - -Amendments: -- max_missing: filter to recipes missing ≤ N pantry items -- hard_day_mode: filter to easy-method recipes only -- grocery_list: aggregated missing ingredients across suggestions -""" -from __future__ import annotations - -import json -import re -from typing import TYPE_CHECKING - -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 - -_LEFTOVER_DAILY_MAX_FREE = 5 - -# Words that carry no ingredient-identity signal — stripped before overlap scoring -_SWAP_STOPWORDS = frozenset({ - "a", "an", "the", "of", "in", "for", "with", "and", "or", - "to", "from", "at", "by", "as", "on", -}) - -# Maps product-label substrings to recipe-corpus canonical terms. -# Kept in sync with Store._FTS_SYNONYMS — both must agree on canonical names. -# Used to expand pantry_set so single-word recipe ingredients can match -# multi-word product names (e.g. "hamburger" satisfied by "burger patties"). -_PANTRY_LABEL_SYNONYMS: dict[str, str] = { - "burger patt": "hamburger", - "beef patt": "hamburger", - "ground beef": "hamburger", - "ground chuck": "hamburger", - "ground round": "hamburger", - "mince": "hamburger", - "veggie burger": "hamburger", - "beyond burger": "hamburger", - "impossible burger": "hamburger", - "plant burger": "hamburger", - "chicken patt": "chicken patty", - "kielbasa": "sausage", - "bratwurst": "sausage", - "frankfurter": "hotdog", - "wiener": "hotdog", - "chicken breast": "chicken", - "chicken thigh": "chicken", - "chicken drumstick": "chicken", - "chicken wing": "chicken", - "rotisserie chicken": "chicken", - "chicken tender": "chicken", - "chicken strip": "chicken", - "chicken piece": "chicken", - "fake chicken": "chicken", - "plant chicken": "chicken", - "vegan chicken": "chicken", - "daring": "chicken", - "gardein chick": "chicken", - "quorn chick": "chicken", - "chick'n": "chicken", - "chikn": "chicken", - "not-chicken": "chicken", - "no-chicken": "chicken", - # Plant-based beef subs → broad "beef" (strips ≠ ground; texture matters) - "not-beef": "beef", - "no-beef": "beef", - "plant beef": "beef", - "vegan beef": "beef", - # Plant-based pork subs - "not-pork": "pork", - "no-pork": "pork", - "plant pork": "pork", - "vegan pork": "pork", - "omnipork": "pork", - "omni pork": "pork", - # Generic alt-meat catch-alls → broad "beef" - "fake meat": "beef", - "plant meat": "beef", - "vegan meat": "beef", - "meat-free": "beef", - "meatless": "beef", - "pork chop": "pork", - "pork loin": "pork", - "pork tenderloin": "pork", - "marinara": "tomato sauce", - "pasta sauce": "tomato sauce", - "spaghetti sauce": "tomato sauce", - "pizza sauce": "tomato sauce", - "macaroni": "pasta", - "noodles": "pasta", - "spaghetti": "pasta", - "penne": "pasta", - "fettuccine": "pasta", - "rigatoni": "pasta", - "linguine": "pasta", - "rotini": "pasta", - "farfalle": "pasta", - "shredded cheese": "cheese", - "sliced cheese": "cheese", - "american cheese": "cheese", - "cheddar": "cheese", - "mozzarella": "cheese", - "heavy cream": "cream", - "whipping cream": "cream", - "half and half": "cream", - "burger bun": "buns", - "hamburger bun": "buns", - "hot dog bun": "buns", - "bread roll": "buns", - "dinner roll": "buns", - # Tortillas / wraps — assembly dishes (burritos, tacos, quesadillas) - "flour tortilla": "tortillas", - "corn tortilla": "tortillas", - "tortilla wrap": "tortillas", - "soft taco shell": "tortillas", - "taco shell": "taco shells", - "pita bread": "pita", - "flatbread": "flatbread", - # Canned beans — extremely interchangeable in assembly dishes - "black bean": "beans", - "pinto bean": "beans", - "kidney bean": "beans", - "refried bean": "beans", - "chickpea": "beans", - "garbanzo": "beans", - # Rice variants - "white rice": "rice", - "brown rice": "rice", - "jasmine rice": "rice", - "basmati rice": "rice", - "instant rice": "rice", - "microwavable rice": "rice", - # Salsa / hot sauce - "hot sauce": "salsa", - "taco sauce": "salsa", - "enchilada sauce": "salsa", - # Sour cream / Greek yogurt — functional substitutes - "greek yogurt": "sour cream", - # Frozen/prepackaged meal token extraction — handled by individual token - # fallback in _normalize_for_fts; these are the most common single-serve meal types - "lean cuisine": "casserole", - "stouffer": "casserole", - "healthy choice": "casserole", - "marie callender": "casserole", -} - - -# Matches leading quantity/unit prefixes in recipe ingredient strings, -# e.g. "2 cups flour" → "flour", "1/2 c. ketchup" → "ketchup", -# "3 oz. butter" → "butter" -_QUANTITY_PREFIX = re.compile( - r"^\s*(?:\d+(?:[./]\d+)?\s*)?" # optional leading number (1, 1/2, 2.5) - r"(?:to\s+\d+\s*)?" # optional "to N" range - r"(?:c\.|cup|cups|tbsp|tsp|oz|lb|lbs|g|kg|ml|l|" - r"can|cans|pkg|pkg\.|package|slice|slices|clove|cloves|" - r"small|medium|large|bunch|head|piece|pieces|" - r"pinch|dash|handful|sprig|sprigs)\s*\b", - re.IGNORECASE, -) - - -# Preparation-state words that modify an ingredient without changing what it is. -# Stripped from both ends so "melted butter", "butter, melted" both → "butter". -_PREP_STATES = re.compile( - r"\b(melted|softened|cold|warm|hot|room.temperature|" - r"diced|sliced|chopped|minced|grated|shredded|shredded|beaten|whipped|" - r"cooked|raw|frozen|canned|dried|dehydrated|marinated|seasoned|" - r"roasted|toasted|ground|crushed|pressed|peeled|seeded|pitted|" - r"boneless|skinless|trimmed|halved|quartered|julienned|" - r"thinly|finely|roughly|coarsely|freshly|lightly|" - r"packed|heaping|level|sifted|divided|optional)\b", - re.IGNORECASE, -) -# Trailing comma + optional prep state (e.g. "butter, melted") -_TRAILING_PREP = re.compile(r",\s*\w+$") - - -# Maps prep-state words to human-readable instruction templates. -# {ingredient} is replaced with the actual ingredient name. -# None means the state is passive (frozen, canned) — no note needed. -_PREP_INSTRUCTIONS: dict[str, str | None] = { - "melted": "Melt the {ingredient} before starting.", - "softened": "Let the {ingredient} soften to room temperature before using.", - "room temperature": "Bring the {ingredient} to room temperature before using.", - "beaten": "Beat the {ingredient} lightly before adding.", - "whipped": "Whip the {ingredient} until soft peaks form.", - "sifted": "Sift the {ingredient} before measuring.", - "toasted": "Toast the {ingredient} in a dry pan until fragrant.", - "roasted": "Roast the {ingredient} before using.", - "pressed": "Press the {ingredient} to remove excess moisture.", - "diced": "Dice the {ingredient} into small pieces.", - "sliced": "Slice the {ingredient} thinly.", - "chopped": "Chop the {ingredient} roughly.", - "minced": "Mince the {ingredient} finely.", - "grated": "Grate the {ingredient}.", - "shredded": "Shred the {ingredient}.", - "ground": "Grind the {ingredient}.", - "crushed": "Crush the {ingredient}.", - "peeled": "Peel the {ingredient} before use.", - "seeded": "Remove seeds from the {ingredient}.", - "pitted": "Pit the {ingredient} before use.", - "trimmed": "Trim any excess from the {ingredient}.", - "julienned": "Cut the {ingredient} into thin matchstick strips.", - "cooked": "Pre-cook the {ingredient} before adding.", - # Passive states — ingredient is used as-is, no prep note needed - "cold": None, - "warm": None, - "hot": None, - "raw": None, - "frozen": None, - "canned": None, - "dried": None, - "dehydrated": None, - "marinated": None, - "seasoned": None, - "boneless": None, - "skinless": None, - "divided": None, - "optional": None, - "fresh": None, - "freshly": None, - "thinly": None, - "finely": None, - "roughly": None, - "coarsely": None, - "lightly": None, - "packed": None, - "heaping": None, - "level": None, -} - -# Finds the first actionable prep state in an ingredient string -_PREP_STATE_SEARCH = re.compile( - r"\b(" + "|".join(re.escape(k) for k in _PREP_INSTRUCTIONS) + r")\b", - re.IGNORECASE, -) - - -def _strip_quantity(ingredient: str) -> str: - """Remove leading quantity/unit and preparation-state words from a recipe ingredient. - - e.g. "2 tbsp melted butter" → "butter" - "butter, melted" → "butter" - "1/4 cup flour, sifted" → "flour" - """ - stripped = _QUANTITY_PREFIX.sub("", ingredient).strip() - # Strip any remaining leading number (e.g. "3 eggs" → "eggs") - stripped = re.sub(r"^\d+\s+", "", stripped) - # Strip trailing ", prep_state" - stripped = _TRAILING_PREP.sub("", stripped).strip() - # Strip prep-state words (may be leading or embedded) - stripped = _PREP_STATES.sub("", stripped).strip() - # Clean up any double spaces left behind - stripped = re.sub(r"\s{2,}", " ", stripped).strip() - return stripped or ingredient - - -def _prep_note_for(ingredient: str) -> str | None: - """Return a human-readable prep instruction for this ingredient string, or None. - - e.g. "2 tbsp melted butter" → "Melt the butter before starting." - "onion, diced" → "Dice the onion into small pieces." - "frozen peas" → None (passive state, no action needed) - """ - match = _PREP_STATE_SEARCH.search(ingredient) - if not match: - return None - state = match.group(1).lower() - template = _PREP_INSTRUCTIONS.get(state) - if not template: - return None - # Use the stripped ingredient name as the subject - ingredient_name = _strip_quantity(ingredient) - return template.format(ingredient=ingredient_name) - - -def _expand_pantry_set(pantry_items: list[str]) -> set[str]: - """Return pantry_set expanded with canonical recipe-corpus synonyms. - - For each pantry item, checks _PANTRY_LABEL_SYNONYMS for substring matches - and adds the canonical form. This lets single-word recipe ingredients - ("hamburger", "chicken") match product-label pantry entries - ("burger patties", "rotisserie chicken"). - """ - expanded: set[str] = set() - for item in pantry_items: - lower = item.lower().strip() - expanded.add(lower) - for pattern, canonical in _PANTRY_LABEL_SYNONYMS.items(): - if pattern in lower: - expanded.add(canonical) - return expanded - - -def _ingredient_in_pantry(ingredient: str, pantry_set: set[str]) -> bool: - """Return True if the recipe ingredient is satisfied by the pantry. - - Checks three layers in order: - 1. Exact match after quantity stripping - 2. Synonym lookup: ingredient → canonical → in pantry_set - (handles "ground beef" matched by "burger patties" via shared canonical) - 3. Token subset: all content tokens of the ingredient appear in pantry - (handles "diced onions" when "onions" is in pantry) - """ - clean = _strip_quantity(ingredient).lower() - if clean in pantry_set: - return True - - # Check if this recipe ingredient maps to a canonical that's in pantry - for pattern, canonical in _PANTRY_LABEL_SYNONYMS.items(): - if pattern in clean and canonical in pantry_set: - return True - - # Single-token ingredient whose token appears in pantry (e.g. "ketchup" in "c. ketchup") - tokens = [t for t in clean.split() if t not in _SWAP_STOPWORDS and len(t) > 2] - if tokens and all(t in pantry_set for t in tokens): - return True - - return False - - -def _content_tokens(text: str) -> frozenset[str]: - return frozenset( - w for w in text.lower().split() - if w not in _SWAP_STOPWORDS and len(w) > 1 - ) - - -def _pantry_creative_swap(required: str, pantry_items: set[str]) -> str | None: - """Return a pantry item that's a plausible creative substitute, or None. - - Requires ≥2 shared content tokens AND ≥50% bidirectional overlap so that - single-word differences (cream-of-mushroom vs cream-of-potato) qualify while - single-word ingredients (butter, flour) don't accidentally match supersets - (peanut butter, bread flour). - """ - req_tokens = _content_tokens(required) - if len(req_tokens) < 2: - return None # single-word ingredients must already be in pantry_set - - best: str | None = None - best_score = 0.0 - for item in pantry_items: - if item.lower() == required.lower(): - continue - pan_tokens = _content_tokens(item) - if not pan_tokens: - continue - overlap = len(req_tokens & pan_tokens) - if overlap < 2: - continue - score = min(overlap / len(req_tokens), overlap / len(pan_tokens)) - if score >= 0.5 and score > best_score: - best_score = score - best = item - return best - - -# Method complexity classification patterns -_EASY_METHODS = re.compile( - r"\b(microwave|mix|stir|blend|toast|assemble|heat)\b", re.IGNORECASE -) -_INVOLVED_METHODS = re.compile( - r"\b(braise|roast|knead|deep.?fry|fry|sauté|saute|bake|boil)\b", re.IGNORECASE -) - - -def _classify_method_complexity( - directions: list[str], - available_equipment: list[str] | None = None, -) -> str: - """Classify recipe method complexity from direction strings. - - Returns 'easy', 'moderate', or 'involved'. - available_equipment can expand the easy set (e.g. ['toaster', 'air fryer']). - """ - text = " ".join(directions).lower() - equipment_set = {e.lower() for e in (available_equipment or [])} - - if _INVOLVED_METHODS.search(text): - return "involved" - - if _EASY_METHODS.search(text): - return "easy" - - # Check equipment-specific easy methods - for equip in equipment_set: - if equip in text: - return "easy" - - return "moderate" - - -class RecipeEngine: - def __init__(self, store: "Store") -> None: - self._store = store - self._classifier = ElementClassifier(store) - self._substitution = SubstitutionEngine(store) - - def suggest( - self, - req: RecipeRequest, - available_equipment: list[str] | None = None, - ) -> RecipeResult: - # Load cooking equipment from user settings when hard_day_mode is active - if req.hard_day_mode and available_equipment is None: - equipment_json = self._store.get_setting("cooking_equipment") - if equipment_json: - try: - available_equipment = json.loads(equipment_json) - except (json.JSONDecodeError, TypeError): - available_equipment = [] - else: - available_equipment = [] - # Rate-limit leftover mode for free tier - if req.expiry_first and req.tier == "free": - allowed, count = self._store.check_and_increment_rate_limit( - "leftover_mode", _LEFTOVER_DAILY_MAX_FREE - ) - if not allowed: - return RecipeResult( - suggestions=[], element_gaps=[], rate_limited=True, rate_limit_count=count - ) - - profiles = self._classifier.classify_batch(req.pantry_items) - gaps = self._classifier.identify_gaps(profiles) - pantry_set = _expand_pantry_set(req.pantry_items) - - if req.level >= 3: - from app.services.recipe.llm_recipe import LLMRecipeGenerator - gen = LLMRecipeGenerator(self._store) - return gen.generate(req, profiles, gaps) - - # Level 1 & 2: deterministic path - nf = req.nutrition_filters - rows = self._store.search_recipes_by_ingredients( - req.pantry_items, - limit=20, - category=req.category or None, - max_calories=nf.max_calories, - max_sugar_g=nf.max_sugar_g, - max_carbs_g=nf.max_carbs_g, - max_sodium_mg=nf.max_sodium_mg, - excluded_ids=req.excluded_ids or [], - ) - suggestions = [] - - for row in rows: - ingredient_names: list[str] = row.get("ingredient_names") or [] - if isinstance(ingredient_names, str): - try: - ingredient_names = json.loads(ingredient_names) - except Exception: - ingredient_names = [] - - # Compute missing ingredients, detecting pantry coverage first. - # When covered, collect any prep-state annotations (e.g. "melted butter" - # → note "Melt the butter before starting.") to surface separately. - swap_candidates: list[SwapCandidate] = [] - missing: list[str] = [] - prep_note_set: set[str] = set() - for n in ingredient_names: - if _ingredient_in_pantry(n, pantry_set): - note = _prep_note_for(n) - if note: - prep_note_set.add(note) - continue - swap_item = _pantry_creative_swap(n, pantry_set) - if swap_item: - swap_candidates.append(SwapCandidate( - original_name=n, - substitute_name=swap_item, - constraint_label="pantry_swap", - explanation=f"You have {swap_item} — use it in place of {n}.", - compensation_hints=[], - )) - else: - missing.append(n) - - # Filter by max_missing (pantry swaps don't count as missing) - if req.max_missing is not None and len(missing) > req.max_missing: - continue - - # Filter by hard_day_mode - if req.hard_day_mode: - directions: list[str] = row.get("directions") or [] - if isinstance(directions, str): - try: - directions = json.loads(directions) - except Exception: - directions = [directions] - complexity = _classify_method_complexity(directions, available_equipment) - if complexity == "involved": - continue - - # Level 2: also add dietary constraint swaps from substitution_pairs - if req.level == 2 and req.constraints: - for ing in ingredient_names: - for constraint in req.constraints: - swaps = self._substitution.find_substitutes(ing, constraint) - for swap in swaps[:1]: - swap_candidates.append(SwapCandidate( - original_name=swap.original_name, - substitute_name=swap.substitute_name, - constraint_label=swap.constraint_label, - explanation=swap.explanation, - compensation_hints=swap.compensation_hints, - )) - - coverage_raw = row.get("element_coverage") or {} - if isinstance(coverage_raw, str): - try: - coverage_raw = json.loads(coverage_raw) - except Exception: - coverage_raw = {} - - servings = row.get("servings") or None - nutrition = NutritionPanel( - calories=row.get("calories"), - fat_g=row.get("fat_g"), - protein_g=row.get("protein_g"), - carbs_g=row.get("carbs_g"), - fiber_g=row.get("fiber_g"), - sugar_g=row.get("sugar_g"), - sodium_mg=row.get("sodium_mg"), - servings=servings, - estimated=bool(row.get("nutrition_estimated", 0)), - ) - has_nutrition = any( - v is not None - for v in (nutrition.calories, nutrition.sugar_g, nutrition.carbs_g) - ) - suggestions.append(RecipeSuggestion( - id=row["id"], - title=row["title"], - match_count=int(row.get("match_count") or 0), - element_coverage=coverage_raw, - swap_candidates=swap_candidates, - missing_ingredients=missing, - prep_notes=sorted(prep_note_set), - level=req.level, - nutrition=nutrition if has_nutrition else None, - )) - - # Prepend assembly-dish templates (burrito, stir fry, omelette, etc.) - # These fire regardless of corpus coverage — any pantry can make a burrito. - assembly = match_assembly_templates( - pantry_items=req.pantry_items, - pantry_set=pantry_set, - excluded_ids=req.excluded_ids or [], - ) - suggestions = assembly + suggestions - - # Build grocery list — deduplicated union of all missing ingredients - seen: set[str] = set() - grocery_list: list[str] = [] - for s in suggestions: - for item in s.missing_ingredients: - if item not in seen: - grocery_list.append(item) - seen.add(item) - - # Build grocery links — affiliate deeplinks for each missing ingredient - link_builder = GroceryLinkBuilder(tier=req.tier, has_byok=req.has_byok) - grocery_links = link_builder.build_all(grocery_list) - - return RecipeResult( - suggestions=suggestions, - element_gaps=gaps, - grocery_list=grocery_list, - grocery_links=grocery_links, - ) diff --git a/app/services/recipe/staple_library.py b/app/services/recipe/staple_library.py deleted file mode 100644 index 6ece0bc..0000000 --- a/app/services/recipe/staple_library.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -StapleLibrary -- bulk-preparable base component reference data. -Loaded from YAML files in app/staples/. -""" -from __future__ import annotations - -from dataclasses import dataclass -from pathlib import Path -from typing import Any - -import yaml - -_STAPLES_DIR = Path(__file__).parents[2] / "staples" - - -@dataclass(frozen=True) -class StapleEntry: - slug: str - name: str - description: str - dietary_labels: list[str] - base_ingredients: list[str] - base_method: str - base_time_minutes: int - yield_formats: dict[str, Any] - compatible_styles: list[str] - - -class StapleLibrary: - def __init__(self, staples_dir: Path = _STAPLES_DIR) -> None: - self._staples: dict[str, StapleEntry] = {} - for yaml_path in sorted(staples_dir.glob("*.yaml")): - entry = self._load(yaml_path) - self._staples[entry.slug] = entry - - def get(self, slug: str) -> StapleEntry | None: - return self._staples.get(slug) - - def list_all(self) -> list[StapleEntry]: - return list(self._staples.values()) - - def filter_by_dietary(self, label: str) -> list[StapleEntry]: - return [s for s in self._staples.values() if label in s.dietary_labels] - - def _load(self, path: Path) -> StapleEntry: - try: - data = yaml.safe_load(path.read_text()) - return StapleEntry( - slug=data["slug"], - name=data["name"], - description=data.get("description", ""), - dietary_labels=data.get("dietary_labels", []), - base_ingredients=data.get("base_ingredients", []), - base_method=data.get("base_method", ""), - base_time_minutes=int(data.get("base_time_minutes", 0)), - yield_formats=data.get("yield_formats", {}), - compatible_styles=data.get("compatible_styles", []), - ) - except (KeyError, yaml.YAMLError) as exc: - raise ValueError(f"Failed to load staple from {path}: {exc}") from exc diff --git a/app/services/recipe/style_adapter.py b/app/services/recipe/style_adapter.py deleted file mode 100644 index 5f405d4..0000000 --- a/app/services/recipe/style_adapter.py +++ /dev/null @@ -1,132 +0,0 @@ -""" -StyleAdapter — cuisine-mode overlay that biases element dimensions. -YAML templates in app/styles/. -""" -from __future__ import annotations - -from dataclasses import dataclass -from pathlib import Path - -import yaml - -_STYLES_DIR = Path(__file__).parents[2] / "styles" - - -@dataclass(frozen=True) -class StyleTemplate: - style_id: str - name: str - aromatics: tuple[str, ...] - depth_sources: tuple[str, ...] - brightness_sources: tuple[str, ...] - method_bias: dict[str, float] - structure_forms: tuple[str, ...] - seasoning_bias: str - finishing_fat_str: str - - def bias_aroma_selection(self, pantry_items: list[str]) -> list[str]: - """Return aromatics present in pantry (bidirectional substring match).""" - result = [] - for aroma in self.aromatics: - for item in pantry_items: - if aroma.lower() in item.lower() or item.lower() in aroma.lower(): - result.append(aroma) - break - return result - - def preferred_depth_sources(self, pantry_items: list[str]) -> list[str]: - """Return depth_sources present in pantry.""" - result = [] - for src in self.depth_sources: - for item in pantry_items: - if src.lower() in item.lower() or item.lower() in src.lower(): - result.append(src) - break - return result - - def preferred_structure_forms(self, pantry_items: list[str]) -> list[str]: - """Return structure_forms present in pantry.""" - result = [] - for form in self.structure_forms: - for item in pantry_items: - if form.lower() in item.lower() or item.lower() in form.lower(): - result.append(form) - break - return result - - def method_weights(self) -> dict[str, float]: - """Return method bias weights.""" - return dict(self.method_bias) - - def seasoning_vector(self) -> str: - """Return seasoning bias.""" - return self.seasoning_bias - - def finishing_fat(self) -> str: - """Return finishing fat.""" - return self.finishing_fat_str - - -class StyleAdapter: - def __init__(self, styles_dir: Path = _STYLES_DIR) -> None: - self._styles: dict[str, StyleTemplate] = {} - for yaml_path in sorted(styles_dir.glob("*.yaml")): - try: - template = self._load(yaml_path) - self._styles[template.style_id] = template - except (KeyError, yaml.YAMLError, TypeError) as exc: - raise ValueError(f"Failed to load style from {yaml_path}: {exc}") from exc - - @property - def styles(self) -> dict[str, StyleTemplate]: - return self._styles - - def get(self, style_id: str) -> StyleTemplate | None: - return self._styles.get(style_id) - - def list_all(self) -> list[StyleTemplate]: - return list(self._styles.values()) - - def bias_aroma_selection(self, style_id: str, pantry_items: list[str]) -> list[str]: - """Return pantry items that match the style's preferred aromatics. - Falls back to all pantry items if no match found.""" - template = self._styles.get(style_id) - if not template: - return pantry_items - matched = [ - item for item in pantry_items - if any( - aroma.lower() in item.lower() or item.lower() in aroma.lower() - for aroma in template.aromatics - ) - ] - return matched if matched else pantry_items - - def apply(self, style_id: str, pantry_items: list[str]) -> dict: - """Return style-biased ingredient guidance for each element dimension.""" - template = self._styles.get(style_id) - if not template: - return {} - return { - "aroma_candidates": self.bias_aroma_selection(style_id, pantry_items), - "depth_suggestions": list(template.depth_sources), - "brightness_suggestions": list(template.brightness_sources), - "method_bias": template.method_bias, - "structure_forms": list(template.structure_forms), - "seasoning_bias": template.seasoning_bias, - "finishing_fat": template.finishing_fat_str, - } - - def _load(self, path: Path) -> StyleTemplate: - data = yaml.safe_load(path.read_text()) - return StyleTemplate( - style_id=data["style_id"], - name=data["name"], - aromatics=tuple(data.get("aromatics", [])), - depth_sources=tuple(data.get("depth_sources", [])), - brightness_sources=tuple(data.get("brightness_sources", [])), - method_bias=dict(data.get("method_bias", {})), - structure_forms=tuple(data.get("structure_forms", [])), - seasoning_bias=data.get("seasoning_bias", ""), - finishing_fat_str=data.get("finishing_fat", ""), - ) diff --git a/app/services/recipe/substitution_engine.py b/app/services/recipe/substitution_engine.py deleted file mode 100644 index ec9f9c1..0000000 --- a/app/services/recipe/substitution_engine.py +++ /dev/null @@ -1,126 +0,0 @@ -""" -SubstitutionEngine — deterministic ingredient swap candidates with compensation hints. - -Powered by: - - substitution_pairs table (derived from lishuyang/recipepairs) - - ingredient_profiles functional metadata (USDA FDC) -""" -from __future__ import annotations - -import json -from dataclasses import dataclass, field -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from app.db.store import Store - -# Compensation threshold — if |delta| exceeds this, surface a hint -_FAT_THRESHOLD = 5.0 # grams per 100g -_GLUTAMATE_THRESHOLD = 1.0 # mg per 100g -_MOISTURE_THRESHOLD = 15.0 # grams per 100g - -_RICHNESS_COMPENSATORS = ["olive oil", "coconut oil", "butter", "shortening", "full-fat coconut milk"] -_DEPTH_COMPENSATORS = ["nutritional yeast", "soy sauce", "miso", "mushroom powder", - "better than bouillon not-beef", "smoked paprika"] -_MOISTURE_BINDERS = ["cornstarch", "flour", "arrowroot", "breadcrumbs"] - - -@dataclass(frozen=True) -class CompensationHint: - ingredient: str - reason: str - element: str - - -@dataclass(frozen=True) -class SubstitutionSwap: - original_name: str - substitute_name: str - constraint_label: str - fat_delta: float - moisture_delta: float - glutamate_delta: float - protein_delta: float - occurrence_count: int - compensation_hints: list[dict] = field(default_factory=list) - explanation: str = "" - - -class SubstitutionEngine: - def __init__(self, store: "Store") -> None: - self._store = store - - def find_substitutes( - self, - ingredient_name: str, - constraint: str, - ) -> list[SubstitutionSwap]: - rows = self._store._fetch_all(""" - SELECT substitute_name, constraint_label, - fat_delta, moisture_delta, glutamate_delta, protein_delta, - occurrence_count, compensation_hints - FROM substitution_pairs - WHERE original_name = ? AND constraint_label = ? - ORDER BY occurrence_count DESC - """, (ingredient_name.lower(), constraint)) - - return [self._row_to_swap(ingredient_name, row) for row in rows] - - def _row_to_swap(self, original: str, row: dict) -> SubstitutionSwap: - hints = self._build_hints(row) - explanation = self._build_explanation(original, row, hints) - return SubstitutionSwap( - original_name=original, - substitute_name=row["substitute_name"], - constraint_label=row["constraint_label"], - fat_delta=row.get("fat_delta") or 0.0, - moisture_delta=row.get("moisture_delta") or 0.0, - glutamate_delta=row.get("glutamate_delta") or 0.0, - protein_delta=row.get("protein_delta") or 0.0, - occurrence_count=row.get("occurrence_count") or 1, - compensation_hints=[{"ingredient": h.ingredient, "reason": h.reason, "element": h.element} for h in hints], - explanation=explanation, - ) - - def _build_hints(self, row: dict) -> list[CompensationHint]: - hints = [] - fat_delta = row.get("fat_delta") or 0.0 - glutamate_delta = row.get("glutamate_delta") or 0.0 - moisture_delta = row.get("moisture_delta") or 0.0 - - if fat_delta < -_FAT_THRESHOLD: - missing = abs(fat_delta) - sugg = _RICHNESS_COMPENSATORS[0] - hints.append(CompensationHint( - ingredient=sugg, - reason=f"substitute has ~{missing:.0f}g/100g less fat — add {sugg} to restore Richness", - element="Richness", - )) - - if glutamate_delta < -_GLUTAMATE_THRESHOLD: - sugg = _DEPTH_COMPENSATORS[0] - hints.append(CompensationHint( - ingredient=sugg, - reason=f"substitute is lower in umami — add {sugg} to restore Depth", - element="Depth", - )) - - if moisture_delta > _MOISTURE_THRESHOLD: - sugg = _MOISTURE_BINDERS[0] - hints.append(CompensationHint( - ingredient=sugg, - reason=f"substitute adds ~{moisture_delta:.0f}g/100g more moisture — add {sugg} to maintain Structure", - element="Structure", - )) - - return hints - - def _build_explanation( - self, original: str, row: dict, hints: list[CompensationHint] - ) -> str: - sub = row["substitute_name"] - count = row.get("occurrence_count") or 1 - base = f"Replace {original} with {sub} (seen in {count} recipes)." - if hints: - base += " To compensate: " + "; ".join(h.reason for h in hints) + "." - return base diff --git a/app/staples/seitan.yaml b/app/staples/seitan.yaml deleted file mode 100644 index 7d62500..0000000 --- a/app/staples/seitan.yaml +++ /dev/null @@ -1,38 +0,0 @@ -slug: seitan -name: Seitan (Wheat Meat) -description: High-protein wheat gluten that mimics the texture of meat. Can be made in bulk and stored in multiple formats. -dietary_labels: [vegan, high-protein] -base_ingredients: - - vital wheat gluten - - nutritional yeast - - soy sauce - - garlic powder - - vegetable broth -base_method: simmer -base_time_minutes: 45 -yield_formats: - fresh: - elements: [Structure, Depth, Richness] - shelf_days: 5 - storage: airtight container, refrigerated in broth - methods: [saute, braise, grill, stir-fry] - texture: chewy, meaty - frozen: - elements: [Structure, Depth] - shelf_days: 90 - storage: vacuum-sealed freezer bag - methods: [thaw then any method] - texture: slightly softer after thaw - braised: - elements: [Structure, Depth, Seasoning] - shelf_days: 4 - storage: covered in braising liquid, refrigerated - methods: [serve directly, slice for sandwiches] - texture: tender, falling-apart - grilled: - elements: [Structure, Aroma, Texture] - shelf_days: 3 - storage: refrigerated, uncovered to maintain crust - methods: [slice cold, reheat in pan] - texture: crisp exterior, chewy interior -compatible_styles: [italian, latin, east_asian, eastern_european] diff --git a/app/staples/tempeh.yaml b/app/staples/tempeh.yaml deleted file mode 100644 index 25ed2ef..0000000 --- a/app/staples/tempeh.yaml +++ /dev/null @@ -1,28 +0,0 @@ -slug: tempeh -name: Tempeh -description: Fermented soybean cake. Dense, nutty, high in protein. Excellent at absorbing marinades. -dietary_labels: [vegan, high-protein, fermented] -base_ingredients: - - tempeh block (store-bought or homemade from soybeans + starter) -base_method: steam then marinate -base_time_minutes: 20 -yield_formats: - raw: - elements: [Structure, Depth, Richness] - shelf_days: 7 - storage: refrigerated in original packaging or wrapped - methods: [steam, crumble, slice] - texture: dense, firm - marinated: - elements: [Structure, Depth, Seasoning, Aroma] - shelf_days: 5 - storage: submerged in marinade, refrigerated - methods: [bake, pan-fry, grill] - texture: chewy, flavor-dense - crumbled: - elements: [Structure, Depth, Texture] - shelf_days: 3 - storage: refrigerated, use quickly - methods: [saute as ground meat substitute, add to tacos or pasta] - texture: crumbly, browned bits -compatible_styles: [latin, east_asian, mediterranean] diff --git a/app/staples/tofu_firm.yaml b/app/staples/tofu_firm.yaml deleted file mode 100644 index 38d0a33..0000000 --- a/app/staples/tofu_firm.yaml +++ /dev/null @@ -1,34 +0,0 @@ -slug: tofu_firm -name: Firm Tofu -description: Pressed soybean curd. Neutral flavor, excellent at absorbing surrounding flavors. Freeze-thaw cycle creates meatier texture. -dietary_labels: [vegan, high-protein] -base_ingredients: - - firm or extra-firm tofu block -base_method: press (30 min) then prepare -base_time_minutes: 30 -yield_formats: - pressed_raw: - elements: [Structure] - shelf_days: 5 - storage: submerged in water, refrigerated, change water daily - methods: [cube, slice, crumble] - texture: dense, uniform - freeze_thawed: - elements: [Structure, Texture] - shelf_days: 5 - storage: refrigerated after thawing - methods: [squeeze dry, saute, bake] - texture: chewy, porous, absorbs marinades deeply - baked: - elements: [Structure, Texture, Aroma] - shelf_days: 4 - storage: refrigerated, uncovered - methods: [add to stir-fry, bowl, salad] - texture: crisp exterior, chewy interior - silken: - elements: [Richness, Structure] - shelf_days: 3 - storage: refrigerated, use within days of opening - methods: [blend into sauces, custards, dressings] - texture: silky, smooth -compatible_styles: [east_asian, mediterranean] diff --git a/app/styles/east_asian.yaml b/app/styles/east_asian.yaml deleted file mode 100644 index 5cfe8f8..0000000 --- a/app/styles/east_asian.yaml +++ /dev/null @@ -1,13 +0,0 @@ -style_id: east_asian -name: East Asian -aromatics: [ginger, scallion, sesame, star anise, five spice, sichuan pepper, lemongrass] -depth_sources: [soy sauce, miso, oyster sauce, shiitake, fish sauce, bonito] -brightness_sources: [rice vinegar, mirin, citrus zest, ponzu] -method_bias: - stir_fry: 0.35 - steam: 0.25 - braise: 0.20 - boil: 0.20 -structure_forms: [dumpling wrapper, thin noodle, rice, bao] -seasoning_bias: soy sauce -finishing_fat: toasted sesame oil diff --git a/app/styles/eastern_european.yaml b/app/styles/eastern_european.yaml deleted file mode 100644 index 00526d6..0000000 --- a/app/styles/eastern_european.yaml +++ /dev/null @@ -1,13 +0,0 @@ -style_id: eastern_european -name: Eastern European -aromatics: [dill, caraway, marjoram, parsley, horseradish, bay leaf] -depth_sources: [sour cream, smoked meats, bacon, dried mushrooms] -brightness_sources: [sauerkraut brine, apple cider vinegar, sour cream] -method_bias: - braise: 0.35 - boil: 0.30 - bake: 0.25 - roast: 0.10 -structure_forms: [dumpling wrapper, bread dough, stuffed cabbage] -seasoning_bias: kosher salt -finishing_fat: butter or lard diff --git a/app/styles/italian.yaml b/app/styles/italian.yaml deleted file mode 100644 index 856d0d7..0000000 --- a/app/styles/italian.yaml +++ /dev/null @@ -1,13 +0,0 @@ -style_id: italian -name: Italian -aromatics: [basil, oregano, garlic, onion, fennel, rosemary, thyme, sage, marjoram] -depth_sources: [parmesan, pecorino, anchovies, canned tomato, porcini mushrooms] -brightness_sources: [lemon, white wine, tomato, red wine vinegar] -method_bias: - braise: 0.30 - roast: 0.30 - saute: 0.25 - simmer: 0.15 -structure_forms: [pasta, wrapped, layered, risotto] -seasoning_bias: sea salt -finishing_fat: olive oil diff --git a/app/styles/latin.yaml b/app/styles/latin.yaml deleted file mode 100644 index 9ec9618..0000000 --- a/app/styles/latin.yaml +++ /dev/null @@ -1,13 +0,0 @@ -style_id: latin -name: Latin -aromatics: [cumin, chili, cilantro, epazote, mexican oregano, ancho, chipotle, smoked paprika] -depth_sources: [dried chilis, smoked peppers, chocolate, achiote] -brightness_sources: [lime, tomatillo, brined jalapeño, orange] -method_bias: - roast: 0.30 - braise: 0.30 - fry: 0.25 - grill: 0.15 -structure_forms: [wrapped in masa, pastry, stuffed, bowl] -seasoning_bias: kosher salt -finishing_fat: lard or neutral oil diff --git a/app/styles/mediterranean.yaml b/app/styles/mediterranean.yaml deleted file mode 100644 index 8c079c7..0000000 --- a/app/styles/mediterranean.yaml +++ /dev/null @@ -1,13 +0,0 @@ -style_id: mediterranean -name: Mediterranean -aromatics: [oregano, thyme, rosemary, mint, sumac, za'atar, preserved lemon] -depth_sources: [tahini, feta, halloumi, dried olives, harissa] -brightness_sources: [lemon, pomegranate molasses, yogurt, sumac] -method_bias: - roast: 0.35 - grill: 0.30 - braise: 0.25 - saute: 0.10 -structure_forms: [flatbread, stuffed vegetables, grain bowl, mezze plate] -seasoning_bias: sea salt -finishing_fat: olive oil diff --git a/app/tasks/runner.py b/app/tasks/runner.py index f9315c3..99da8ee 100644 --- a/app/tasks/runner.py +++ b/app/tasks/runner.py @@ -27,9 +27,6 @@ LLM_TASK_TYPES: frozenset[str] = frozenset({"expiry_llm_fallback"}) VRAM_BUDGETS: dict[str, float] = { # ExpirationPredictor uses a small LLM (16 tokens out, single pass). "expiry_llm_fallback": 2.0, - # Recipe LLM (levels 3-4): full recipe generation, ~200-500 tokens out. - # Budget assumes a quantized 7B-class model. - "recipe_llm": 4.0, } diff --git a/app/tasks/scheduler.py b/app/tasks/scheduler.py index 64bd268..b916852 100644 --- a/app/tasks/scheduler.py +++ b/app/tasks/scheduler.py @@ -10,7 +10,6 @@ from circuitforge_core.tasks.scheduler import ( reset_scheduler, # re-export for tests ) -from app.core.config import settings from app.tasks.runner import LLM_TASK_TYPES, VRAM_BUDGETS, run_task @@ -21,6 +20,4 @@ def get_scheduler(db_path: Path) -> TaskScheduler: run_task_fn=run_task, task_types=LLM_TASK_TYPES, vram_budgets=VRAM_BUDGETS, - coordinator_url=settings.COORDINATOR_URL, - service_name="kiwi", ) diff --git a/app/tiers.py b/app/tiers.py index 0d16a9e..133eb45 100644 --- a/app/tiers.py +++ b/app/tiers.py @@ -25,8 +25,6 @@ KIWI_FEATURES: dict[str, str] = { "receipt_upload": "free", "expiry_alerts": "free", "export_csv": "free", - "leftover_mode": "free", # Rate-limited at API layer, not tier-gated - "staple_library": "free", # Paid tier "receipt_ocr": "paid", # BYOK-unlockable @@ -34,28 +32,21 @@ KIWI_FEATURES: dict[str, str] = { "expiry_llm_matching": "paid", # BYOK-unlockable "meal_planning": "paid", "dietary_profiles": "paid", - "style_picker": "paid", # Premium tier "multi_household": "premium", "background_monitoring": "premium", + "leftover_mode": "premium", } def can_use(feature: str, tier: str, has_byok: bool = False) -> bool: - """Return True if the given tier can access the feature. - - The 'local' tier is assigned to dev-bypass and non-cloud sessions — - it has unrestricted access to all features. - """ - if tier == "local": - return True + """Return True if the given tier can access the feature.""" return _can_use( feature, tier, has_byok=has_byok, _features=KIWI_FEATURES, - _byok_unlockable=KIWI_BYOK_UNLOCKABLE, ) @@ -63,12 +54,7 @@ def require_feature(feature: str, tier: str, has_byok: bool = False) -> None: """Raise ValueError if the tier cannot access the feature.""" if not can_use(feature, tier, has_byok): from circuitforge_core.tiers.tiers import tier_label - needed = tier_label( - feature, - has_byok=has_byok, - _features=KIWI_FEATURES, - _byok_unlockable=KIWI_BYOK_UNLOCKABLE, - ) + needed = tier_label(feature, has_byok=has_byok, _features=KIWI_FEATURES) raise ValueError( f"Feature '{feature}' requires {needed} tier. " f"Current tier: {tier}." diff --git a/compose.cloud.yml b/compose.cloud.yml index 7c4fcfd..02c0efa 100644 --- a/compose.cloud.yml +++ b/compose.cloud.yml @@ -14,9 +14,6 @@ services: CLOUD_MODE: "true" CLOUD_DATA_ROOT: /devl/kiwi-cloud-data # DIRECTUS_JWT_SECRET, HEIMDALL_URL, HEIMDALL_ADMIN_TOKEN — set in .env - # DEV ONLY: comma-separated IPs that bypass JWT auth (LAN testing without Caddy). - # Production deployments must NOT set this. Leave blank or omit entirely. - CLOUD_AUTH_BYPASS_IPS: ${CLOUD_AUTH_BYPASS_IPS:-} volumes: - /devl/kiwi-cloud-data:/devl/kiwi-cloud-data # LLM config — shared with other CF products; read-only in container diff --git a/compose.override.yml b/compose.override.yml deleted file mode 100644 index c82728d..0000000 --- a/compose.override.yml +++ /dev/null @@ -1,24 +0,0 @@ -# compose.override.yml — local dev additions (auto-merged by docker compose) -# Not used in cloud or demo stacks (those use compose.cloud.yml / compose.demo.yml directly). - -services: - # cf-orch agent sidecar: registers kiwi as a GPU node with the coordinator. - # The API scheduler uses COORDINATOR_URL to lease VRAM cooperatively; this - # agent makes kiwi's VRAM usage visible on the orchestrator dashboard. - cf-orch-agent: - image: kiwi-api # reuse local api image — cf-core already installed there - network_mode: host - env_file: .env - environment: - # Override coordinator URL here or via .env - COORDINATOR_URL: ${COORDINATOR_URL:-http://10.1.10.71:7700} - command: > - conda run -n kiwi cf-orch agent - --coordinator ${COORDINATOR_URL:-http://10.1.10.71:7700} - --node-id kiwi - --host 0.0.0.0 - --port 7702 - --advertise-host ${CF_ORCH_ADVERTISE_HOST:-10.1.10.71} - restart: unless-stopped - depends_on: - - api diff --git a/docker/web/nginx.cloud.conf b/docker/web/nginx.cloud.conf index 3cc81b3..ea8d37a 100644 --- a/docker/web/nginx.cloud.conf +++ b/docker/web/nginx.cloud.conf @@ -14,17 +14,6 @@ server { proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; # Forward the session header injected by Caddy from cf_session cookie. proxy_set_header X-CF-Session $http_x_cf_session; - # Allow image uploads (barcode/receipt photos from phone cameras). - client_max_body_size 20m; - } - - # When accessed directly (localhost:8515) instead of via Caddy (/kiwi path-strip), - # Vite's /kiwi base URL means assets are requested at /kiwi/assets/... but stored - # at /assets/... in nginx's root. Alias /kiwi/ → root so direct port access works. - # ^~ prevents regex locations from overriding this prefix match for /kiwi/ paths. - location ^~ /kiwi/ { - alias /usr/share/nginx/html/; - try_files $uri $uri/ /index.html; } location = /index.html { diff --git a/docker/web/nginx.conf b/docker/web/nginx.conf index e341ee1..a987d0f 100644 --- a/docker/web/nginx.conf +++ b/docker/web/nginx.conf @@ -9,8 +9,6 @@ server { proxy_pass http://172.17.0.1:8512; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; - # Allow image uploads (barcode/receipt photos from phone cameras). - client_max_body_size 20m; } location = /index.html { diff --git a/environment.yml b/environment.yml index 3dc759b..836a5b9 100644 --- a/environment.yml +++ b/environment.yml @@ -14,14 +14,5 @@ dependencies: - numpy>=1.25 - pyzbar>=0.1.9 - httpx>=0.27 - - psutil>=5.9 - pydantic>=2.5 - PyJWT>=2.8 - - datasets - - huggingface_hub - - transformers - - sentence-transformers - - torch - - pyyaml - - pandas - - pyarrow diff --git a/frontend/index.html b/frontend/index.html index d6947bc..2b36112 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,26 +3,8 @@ - - Kiwi — Pantry Tracker - - - - - + + frontend
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index b27d978..8cea527 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -844,6 +844,7 @@ "integrity": "sha512-uWN8YqxXxqFMX2RqGOrumsKeti4LlmIMIyV0lgut4jx7KQBcBiW6vkDtIBvHnHIquwNfJhk8v2OtmO8zXWHfPA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~7.16.0" } @@ -1556,6 +1557,7 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -1719,6 +1721,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -1740,6 +1743,7 @@ "integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", @@ -1821,6 +1825,7 @@ "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.22.tgz", "integrity": "sha512-toaZjQ3a/G/mYaLSbV+QsQhIdMo9x5rrqIpYRObsJ6T/J+RyCSFwN2LHNVH9v8uIcljDNa3QzPVdv3Y6b9hAJQ==", "license": "MIT", + "peer": true, "dependencies": { "@vue/compiler-dom": "3.5.22", "@vue/compiler-sfc": "3.5.22", diff --git a/frontend/src/App.vue b/frontend/src/App.vue index fe179f8..81aa886 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,152 +1,46 @@ @@ -154,39 +48,11 @@ import { ref } from 'vue' import InventoryList from './components/InventoryList.vue' import ReceiptsView from './components/ReceiptsView.vue' -import RecipesView from './components/RecipesView.vue' -import SettingsView from './components/SettingsView.vue' -import FeedbackButton from './components/FeedbackButton.vue' -import { useInventoryStore } from './stores/inventory' -import { useEasterEggs } from './composables/useEasterEggs' -type Tab = 'inventory' | 'receipts' | 'recipes' | 'settings' +const currentTab = ref<'inventory' | 'receipts'>('inventory') -const currentTab = ref('inventory') -const sidebarCollapsed = ref(false) -const inventoryStore = useInventoryStore() -const { kiwiVisible, kiwiDirection } = useEasterEggs() - -// Wordmark click counter for chef mode easter egg -const wordmarkClicks = ref(0) -let wordmarkTimer: ReturnType | null = null -function onWordmarkClick() { - wordmarkClicks.value++ - if (wordmarkTimer) clearTimeout(wordmarkTimer) - if (wordmarkClicks.value >= 5) { - wordmarkClicks.value = 0 - document.querySelector('.wordmark-kiwi')?.classList.add('chef-spin') - setTimeout(() => document.querySelector('.wordmark-kiwi')?.classList.remove('chef-spin'), 800) - } else { - wordmarkTimer = setTimeout(() => { wordmarkClicks.value = 0 }, 1200) - } -} - -async function switchTab(tab: Tab) { +function switchTab(tab: 'inventory' | 'receipts') { currentTab.value = tab - if (tab === 'recipes' && inventoryStore.items.length === 0) { - await inventoryStore.fetchItems() - } } @@ -198,326 +64,136 @@ async function switchTab(tab: Tab) { } body { - font-family: var(--font-body); + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background: var(--color-bg-primary); color: var(--color-text-primary); } -.wordmark-kiwi { - font-family: var(--font-display); - font-style: italic; - font-weight: 700; - color: var(--color-primary); - letter-spacing: -0.01em; - line-height: 1; - white-space: nowrap; - overflow: hidden; -} - -/* ============================================ - MOBILE LAYOUT (< 769px) - sidebar hidden, bottom nav visible - ============================================ */ #app { min-height: 100vh; display: flex; flex-direction: column; } -.sidebar { display: none; } -.app-body { display: contents; } +.container { + max-width: 1400px; + margin: 0 auto; + padding: 0 20px; +} .app-header { - background: var(--gradient-header); - border-bottom: 1px solid var(--color-border); - padding: var(--spacing-sm) var(--spacing-md); - position: sticky; - top: 0; - z-index: 100; - backdrop-filter: blur(8px); + background: var(--gradient-primary); + color: white; + padding: var(--spacing-xl) 0; + box-shadow: var(--shadow-md); } -.header-inner { - display: flex; - align-items: center; - min-height: 44px; +.app-header h1 { + font-size: 32px; + margin-bottom: 5px; } -.header-inner .wordmark-kiwi { font-size: 24px; } +.app-header .tagline { + font-size: 16px; + opacity: 0.9; +} .app-main { flex: 1; - padding: var(--spacing-md) 0 var(--spacing-xl); - /* Clear fixed bottom nav — env() gives extra room for iPhone home bar */ - padding-bottom: calc(68px + env(safe-area-inset-bottom, 0px)); + padding: 20px 0; } -.container { - margin: 0 auto; - padding: 0 var(--spacing-md); -} - -.tab-content { min-height: 0; } - -/* ---- Bottom nav ---- */ -.bottom-nav { - position: fixed; - bottom: 0; - left: 0; - right: 0; - z-index: 200; +.app-footer { background: var(--color-bg-elevated); - border-top: 1px solid var(--color-border); - display: flex; - align-items: stretch; - padding-bottom: env(safe-area-inset-bottom, 0); - box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.25); -} - -.nav-item { - flex: 1; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 3px; - padding: 8px 4px 10px; - border: none; - background: transparent; - color: var(--color-text-muted); - cursor: pointer; - transition: color 0.18s ease, background 0.18s ease; - border-radius: 0; - position: relative; -} - -.nav-item::before { - content: ''; - position: absolute; - top: 0; - left: 20%; - right: 20%; - height: 2px; - background: var(--color-primary); - border-radius: 0 0 2px 2px; - transform: scaleX(0); - transition: transform 0.18s ease; -} - -.nav-item:hover { color: var(--color-text-secondary); - background: rgba(232, 168, 32, 0.06); - transform: none; - border-color: transparent; + padding: var(--spacing-lg) 0; + text-align: center; + margin-top: var(--spacing-xl); + border-top: 1px solid var(--color-border); } -.nav-item.active { color: var(--color-primary); } -.nav-item.active::before { transform: scaleX(1); } +.app-footer p { + font-size: var(--font-size-sm); + opacity: 0.8; +} -.nav-icon { width: 22px; height: 22px; flex-shrink: 0; } +/* Tabs */ +.tabs { + display: flex; + gap: 10px; + margin-bottom: 20px; +} -.nav-label { - font-family: var(--font-body); - font-size: 10px; +.tab { + background: rgba(255, 255, 255, 0.2); + color: white; + border: none; + padding: 15px 30px; + font-size: 16px; + border-radius: 8px; + cursor: pointer; + transition: all 0.3s; +} + +.tab:hover { + background: rgba(255, 255, 255, 0.3); +} + +.tab.active { + background: var(--color-bg-card); + color: var(--color-primary); font-weight: 600; - letter-spacing: 0.04em; - text-transform: uppercase; - line-height: 1; } +.tab-content { + animation: fadeIn 0.3s; +} + +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +/* Mobile Responsive Breakpoints */ @media (max-width: 480px) { - .container { padding: 0 var(--spacing-sm); } - .app-main { - padding: var(--spacing-sm) 0 var(--spacing-lg); - padding-bottom: calc(68px + env(safe-area-inset-bottom, 0px)); - } -} - -/* ============================================ - DESKTOP LAYOUT (≥ 769px) - sidebar visible, bottom nav hidden - ============================================ */ -@media (min-width: 769px) { - .bottom-nav { display: none; } - - #app { - flex-direction: row; - padding-bottom: 0; - min-height: 100vh; - } - - /* ---- Sidebar ---- */ - .sidebar { - display: flex; - flex-direction: column; - width: 200px; - min-height: 100vh; - background: var(--color-bg-elevated); - border-right: 1px solid var(--color-border); - position: sticky; - top: 0; - flex-shrink: 0; - transition: width 0.22s cubic-bezier(0.4, 0, 0.2, 1); - overflow: hidden; - z-index: 100; - } - - .sidebar-collapsed .sidebar { - width: 56px; - } - - .sidebar-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: var(--spacing-md) var(--spacing-md) var(--spacing-sm); - min-height: 56px; - gap: var(--spacing-sm); - } - - .sidebar-header .wordmark-kiwi { - font-size: 22px; - opacity: 1; - transition: opacity 0.15s ease, width 0.22s ease; - flex-shrink: 0; - } - - .sidebar-collapsed .sidebar-header .wordmark-kiwi { - opacity: 0; - width: 0; - pointer-events: none; - } - - .sidebar-toggle { - background: transparent; - border: none; - color: var(--color-text-muted); - cursor: pointer; - padding: 6px; - border-radius: var(--radius-md); - display: flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - transition: color 0.15s, background 0.15s; - } - - .sidebar-toggle:hover { - color: var(--color-text-primary); - background: var(--color-bg-secondary); - transform: none; - border-color: transparent; - } - - .sidebar-nav { - display: flex; - flex-direction: column; - gap: 2px; - padding: var(--spacing-sm); - } - - .sidebar-item { - display: flex; - align-items: center; - gap: var(--spacing-sm); - padding: 10px var(--spacing-sm); - border: none; - border-radius: var(--radius-md); - background: transparent; - color: var(--color-text-muted); - cursor: pointer; - transition: color 0.15s, background 0.15s; - white-space: nowrap; - width: 100%; - text-align: left; - } - - .sidebar-item:hover { - color: var(--color-text-primary); - background: var(--color-bg-secondary); - transform: none; - border-color: transparent; - } - - .sidebar-item.active { - color: var(--color-primary); - background: color-mix(in srgb, var(--color-primary) 10%, transparent); - } - - .sidebar-item .nav-icon { width: 20px; height: 20px; flex-shrink: 0; } - - .sidebar-label { - font-size: var(--font-size-sm); - font-weight: 600; - opacity: 1; - transition: opacity 0.12s ease; - overflow: hidden; - } - - .sidebar-collapsed .sidebar-label { - opacity: 0; - width: 0; - pointer-events: none; - } - - /* ---- Main body ---- */ - .app-body { - display: flex; - flex-direction: column; - flex: 1; - min-width: 0; /* prevent overflow */ - contents: unset; - } - - .app-header { display: none; } /* wordmark lives in sidebar on desktop */ - - /* Override style.css #app max-width so sidebar spans full viewport */ - #app { - max-width: none; - margin: 0; - } - - .app-main { - flex: 1; - padding: var(--spacing-xl) 0; - } - .container { - max-width: 860px; - padding: 0 var(--spacing-lg); + padding: 0 12px; + } + + .app-header h1 { + font-size: 24px; + } + + .app-header .tagline { + font-size: 14px; + } + + .tabs { + gap: 8px; + } + + .tab { + padding: 12px 20px; + font-size: 14px; + flex: 1; } } -@media (min-width: 1200px) { +@media (min-width: 481px) and (max-width: 768px) { .container { - max-width: 960px; - padding: 0 var(--spacing-xl); + padding: 0 16px; } -} -/* Easter egg: wordmark spin on 5× click */ -@keyframes chefSpin { - 0% { transform: rotate(0deg) scale(1); } - 30% { transform: rotate(180deg) scale(1.3); } - 60% { transform: rotate(340deg) scale(1.1); } - 100% { transform: rotate(360deg) scale(1); } -} + .app-header h1 { + font-size: 28px; + } -.wordmark-kiwi.chef-spin { - display: inline-block; - animation: chefSpin 0.8s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; -} - -/* Kiwi bird transition */ -.kiwi-fade-enter-active, -.kiwi-fade-leave-active { - transition: opacity 0.4s ease; -} - -.kiwi-fade-enter-from, -.kiwi-fade-leave-to { - opacity: 0; + .tab { + padding: 14px 25px; + } } diff --git a/frontend/src/components/EditItemModal.vue b/frontend/src/components/EditItemModal.vue index ab02389..a426f92 100644 --- a/frontend/src/components/EditItemModal.vue +++ b/frontend/src/components/EditItemModal.vue @@ -10,8 +10,8 @@
- {{ item.product_name || 'Unknown Product' }} - {{ item.category }} + {{ item.product.name }} + ({{ item.product.brand }})
@@ -228,183 +228,160 @@ function getExpiryHint(): string { left: 0; right: 0; bottom: 0; - background: rgba(0, 0, 0, 0.6); + background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; - backdrop-filter: blur(4px); } .modal-content { background: var(--color-bg-card); - border-radius: var(--radius-xl); + border-radius: var(--radius-lg); width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto; - box-shadow: var(--shadow-xl); - border: 1px solid var(--color-border); + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2); } .modal-header { display: flex; justify-content: space-between; align-items: center; - padding: var(--spacing-lg) var(--spacing-lg) var(--spacing-md); - border-bottom: 1px solid var(--color-border); + padding: 20px; + border-bottom: 1px solid #eee; } .modal-header h2 { margin: 0; font-size: var(--font-size-xl); - font-family: var(--font-display); - font-style: italic; - color: var(--color-text-primary); } .close-btn { background: none; border: none; - font-size: 28px; - color: var(--color-text-muted); + font-size: 32px; + color: #999; cursor: pointer; padding: 0; width: 32px; height: 32px; line-height: 1; - display: flex; - align-items: center; - justify-content: center; - border-radius: var(--radius-md); - transition: color 0.18s, background 0.18s; } .close-btn:hover { color: var(--color-text-primary); - background: var(--color-bg-elevated); } .edit-form { - padding: var(--spacing-lg); + padding: 20px; } .form-group { - margin-bottom: var(--spacing-md); + margin-bottom: 20px; } /* Using .form-row from theme.css */ .form-group label { display: block; - margin-bottom: var(--spacing-xs); + margin-bottom: 8px; font-weight: 600; - color: var(--color-text-secondary); - font-size: var(--font-size-xs); - text-transform: uppercase; - letter-spacing: 0.06em; + color: var(--color-text-primary); + font-size: var(--font-size-sm); } .form-input { width: 100%; - padding: var(--spacing-sm) var(--spacing-md); + padding: 10px; border: 1px solid var(--color-border); - border-radius: var(--radius-md); + border-radius: var(--radius-sm); font-size: var(--font-size-sm); - background: var(--color-bg-input); - color: var(--color-text-primary); - font-family: var(--font-body); - transition: border-color 0.18s, box-shadow 0.18s; - box-sizing: border-box; } .form-input:focus { outline: none; - border-color: var(--color-primary); - box-shadow: 0 0 0 3px var(--color-warning-bg); + border-color: #2196F3; + box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1); } .form-input.expiry-expired { - border-color: var(--color-error); + border-color: #f44336; } .form-input.expiry-soon { - border-color: var(--color-error-light); + border-color: #ff5722; } .form-input.expiry-warning { - border-color: var(--color-warning); + border-color: #ff9800; } .form-input.expiry-good { - border-color: var(--color-success); + border-color: #4CAF50; } textarea.form-input { resize: vertical; - font-family: var(--font-body); + font-family: inherit; } .product-info { - padding: var(--spacing-sm) var(--spacing-md); - background: var(--color-bg-secondary); - border-radius: var(--radius-md); + padding: 10px; + background: #f5f5f5; + border-radius: var(--radius-sm); font-size: var(--font-size-sm); - border: 1px solid var(--color-border); } .product-info .brand { color: var(--color-text-secondary); - margin-left: var(--spacing-sm); + margin-left: 8px; } .expiry-hint { display: block; - margin-top: var(--spacing-xs); + margin-top: 5px; font-size: var(--font-size-xs); color: var(--color-text-secondary); } .error-message { - background: var(--color-error-bg); - color: var(--color-error-light); - border: 1px solid var(--color-error-border); - padding: var(--spacing-sm) var(--spacing-md); - border-radius: var(--radius-md); - margin-bottom: var(--spacing-md); + background: #ffebee; + color: #c62828; + padding: 12px; + border-radius: var(--radius-sm); + margin-bottom: 15px; font-size: var(--font-size-sm); } .form-actions { display: flex; - gap: var(--spacing-sm); + gap: 10px; justify-content: flex-end; - margin-top: var(--spacing-lg); - padding-top: var(--spacing-md); - border-top: 1px solid var(--color-border); + margin-top: 25px; + padding-top: 20px; + border-top: 1px solid #eee; } .btn-cancel, .btn-save { - padding: var(--spacing-sm) var(--spacing-lg); + padding: 10px 24px; border: none; - border-radius: var(--radius-md); + border-radius: var(--radius-sm); font-size: var(--font-size-sm); font-weight: 600; - font-family: var(--font-body); cursor: pointer; - transition: all 0.18s; + transition: background 0.2s; } .btn-cancel { - background: var(--color-bg-elevated); - color: var(--color-text-secondary); - border: 1px solid var(--color-border); + background: #f5f5f5; + color: var(--color-text-primary); } .btn-cancel:hover { - background: var(--color-bg-primary); - color: var(--color-text-primary); + background: #e0e0e0; } .btn-save { @@ -417,7 +394,7 @@ textarea.form-input { } .btn-save:disabled { - opacity: 0.45; + background: var(--color-text-muted); cursor: not-allowed; } @@ -431,7 +408,7 @@ textarea.form-input { } .modal-header { - padding: var(--spacing-md); + padding: 15px; } .modal-header h2 { @@ -439,24 +416,23 @@ textarea.form-input { } .edit-form { - padding: var(--spacing-md); + padding: 15px; } .form-group { - margin-bottom: var(--spacing-sm); + margin-bottom: 15px; } /* Form actions stack on very small screens */ .form-actions { flex-direction: column-reverse; - gap: var(--spacing-sm); + gap: 10px; } .btn-cancel, .btn-save { width: 100%; - padding: var(--spacing-md); - text-align: center; + padding: 12px; } } @@ -464,5 +440,13 @@ textarea.form-input { .modal-content { width: 92%; } + + .modal-header { + padding: 18px; + } + + .edit-form { + padding: 18px; + } } diff --git a/frontend/src/components/FeedbackButton.vue b/frontend/src/components/FeedbackButton.vue deleted file mode 100644 index 9373256..0000000 --- a/frontend/src/components/FeedbackButton.vue +++ /dev/null @@ -1,413 +0,0 @@ -