diet-guard/diet_guard/_claude_bank.py
Krzysztof kuhy Rudnicki 6cd3470502 Add the Claude meal estimator
estimate_meal(text, photo) -> Estimate runs Claude through
claude_agent_sdk in an isolated CLAUDE_CONFIG_DIR: a copy of the access
token (no refresh token, no MCP tokens) and the diet-food skill, never
kuhy's ~/.claude. The skill text is the system prompt; the closest curated
and derived food-bank rows ride in the user message; the photo is an image
block; the answer is constrained by a JSON schema and validated again.

Failure paths, all fail closed (an EstimateError code, nothing logged):
- no host login, CLI/API error, bad transport: estimate_failed
- more than 45 s: estimate_timeout
- no object, missing/mistyped field, NaN/inf/negative/absurd number,
  grams 0, blank or long desc: estimate_invalid
- neither text nor photo: ValueError before any model call
- failed token refresh is logged, the call then fails as estimate_failed

Live smoke (scratch HOME, nothing logged): "2 jajka sadzone i kromka
chleba" -> 315 kcal in 4.3 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
2026-11-17 21:05:41 +01:00

51 lines
1.8 KiB
Python

"""The food-bank rows handed to the estimator.
The skill looks the bank up first (kuhy's own logged numbers beat generic
ones), but the whole bank would bloat every prompt. So the rows are the
closest matches for each part of the typed meal plus the most-logged staples,
deduplicated. Curated and log-derived rows both come through
:func:`diet_guard._foodbank_search.search_foods`.
"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Final
from diet_guard._foodbank_search import search_foods
if TYPE_CHECKING:
from diet_guard._estimator import Nutrition
#: Splits a meal typed as a list: commas, plus, "i"/"oraz"/"and"/"with".
_PARTS: Final = re.compile(
r"\s*(?:,|;|\+|\bi\b|\boraz\b|\band\b|\bz\b)\s*", re.IGNORECASE
)
PER_QUERY: Final = 4
STAPLES: Final = 6
MAX_ROWS: Final = 20
def _row(name: str, nutrition: Nutrition) -> str:
"""One bank row as a compact line the model can scale."""
return (
f"{name} | {nutrition.grams:g} g | {nutrition.kcal:g} kcal | "
f"P{nutrition.protein_g:g} C{nutrition.carbs_g:g} F{nutrition.fat_g:g}"
)
def bank_rows(text: str | None) -> list[str]:
"""Bank rows relevant to ``text``, best first, at most :data:`MAX_ROWS`.
A photo-only request (``text`` None or blank) gets the staples alone.
"""
queries = [text.strip()] if text and text.strip() else []
queries += [part for part in _PARTS.split(text or "") if part.strip()]
rows: dict[str, str] = {}
for query in dict.fromkeys(queries):
for name, nutrition in search_foods(query, PER_QUERY):
rows.setdefault(name.casefold(), _row(name, nutrition))
for name, nutrition in search_foods("", STAPLES):
rows.setdefault(name.casefold(), _row(name, nutrition))
return list(rows.values())[:MAX_ROWS]