Store nutrition per serving, and check the estimate before sending it

Recipes imported from a video caption have no nutrition data, so the values
have to be estimated. Mealie will accept anything: the fields are free-text
strings, a misspelt key is dropped silently, and a whole-recipe total looks
exactly like a per-serving one. The recipe page then renders whatever landed
as fact.

patch_recipe now validates a nutrition block first. Keys must be Mealie's own,
so a number cannot vanish into "carbs". Values are normalized to bare numbers,
matching how the library already stores them. Energy is checked against the
macros with the Atwater factors (4/9/4 kcal per gram) and refused if it is
more than 25% off, which is what catches an arithmetic slip.

Nutrition is per serving, and the text import left recipeServings at 0 --- it
set only the free-text recipeYield, so "4-6 personer" gave Mealie no number to
divide by or scale with. import_recipe_text now also sets recipeServings, from
the lower bound of a range, which is how this library already stores
"10-12 personer" (recipeServings 10). patch_recipe refuses nutrition while the
count is still missing, and accepts it when the same patch supplies it.

verify_recipe fails an import that has no nutrition, or has values without a
serving count.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-17 14:52:54 +02:00
parent 42d78f4060
commit 7d693ef429
4 changed files with 249 additions and 3 deletions
+119 -3
View File
@@ -334,6 +334,18 @@ def _text_lines(body: str) -> list[str]:
return [line.strip() for line in body.splitlines() if line.strip()]
def _servings_number(portions: str) -> int | None:
"""Read a serving count out of a Swedish yield line.
``recipeYield`` is free text, but Mealie scales ingredients and nutrition by
the numeric ``recipeServings`` — left at 0, per-serving figures have nothing
to divide by. A range takes its lower bound, which is how the rest of this
library stores "10-12 personer" (recipeServings 10).
"""
match = re.search(r"\d+", portions)
return int(match.group()) if match else None
@mcp.tool()
def import_recipe_text(text: str, source_url: str | None = None) -> dict[str, Any]:
"""Import a normalized recipe text block (OCR, transcript, or hand-built Swedish).
@@ -380,6 +392,9 @@ def import_recipe_text(text: str, source_url: str | None = None) -> dict[str, An
}
if sections.get("portioner"):
patch["recipeYield"] = sections["portioner"]
servings = _servings_number(sections["portioner"])
if servings:
patch["recipeServings"] = servings
if source_url:
patch["orgURL"] = source_url
@@ -460,6 +475,97 @@ def _resolve_organizers(field: str, entries: Any) -> Any:
return resolved
#: Mealie's own nutrition field names. Anything else is silently dropped by the
#: API, so a misspelt key has to be caught here or the number never lands.
_NUTRITION_FIELDS = frozenset({
"calories",
"carbohydrateContent",
"cholesterolContent",
"fatContent",
"fiberContent",
"proteinContent",
"saturatedFatContent",
"sodiumContent",
"sugarContent",
"transFatContent",
"unsaturatedFatContent",
})
#: Atwater factors: kcal per gram of each macronutrient.
_ENERGY_PER_GRAM = {"proteinContent": 4.0, "fatContent": 9.0, "carbohydrateContent": 4.0}
_NUMBER_RE = re.compile(r"^\s*(\d+(?:[.,]\d+)?)\s*(?:kcal|cal|kj|mg|g|gram|grams)?\s*$", re.I)
def _nutrition_number(field: str, value: Any) -> float:
if isinstance(value, (int, float)):
return float(value)
match = _NUMBER_RE.match(str(value))
if not match:
raise ValueError(
f"nutrition.{field} must be a plain number (Mealie renders the unit "
f"itself); got {value!r}"
)
return float(match.group(1).replace(",", "."))
def _validated_nutrition(nutrition: Any, servings: Any) -> dict[str, str]:
"""Check a nutrition block before it reaches Mealie, and normalize it.
Mealie stores these as free-text strings and validates nothing: a misspelt
key, a unit suffix, or a whole-recipe total in a per-serving field is all
accepted and then displayed as fact. Three things are checked instead:
* the keys are Mealie's own, so a number cannot vanish into `carbs`;
* every value is a bare number, matching how the library already stores them;
* energy agrees with the macros (4/9/4 kcal per gram) within 25%, which is
what catches an arithmetic slip in an estimate.
``recipeServings`` must be known, because Mealie's figures are per serving and
a recipe written "4-6 personer" carries no number Mealie can use.
"""
if not isinstance(nutrition, dict):
raise ValueError(f"nutrition must be an object; got {nutrition!r}")
unknown = sorted(set(nutrition) - _NUTRITION_FIELDS)
if unknown:
raise ValueError(
f"unknown nutrition fields {unknown}; Mealie's names are "
f"{sorted(_NUTRITION_FIELDS)}"
)
try:
portions = float(servings or 0)
except (TypeError, ValueError):
portions = 0.0
if portions <= 0:
raise ValueError(
"nutrition is stored per serving, but the recipe has no recipeServings; "
"set it in the same patch (a yield string like '4-6 personer' is not a "
"number Mealie can divide by)"
)
values = {
field: _nutrition_number(field, value)
for field, value in nutrition.items()
if value is not None
}
macros = {field: values[field] for field in _ENERGY_PER_GRAM if field in values}
if "calories" in values and len(macros) == len(_ENERGY_PER_GRAM):
expected = sum(grams * _ENERGY_PER_GRAM[field] for field, grams in macros.items())
stated = values["calories"]
if expected and abs(stated - expected) / expected > 0.25:
raise ValueError(
f"calories {stated:.0f} does not match the macros "
f"({macros['proteinContent']:.0f} g protein, {macros['fatContent']:.0f} g "
f"fat, {macros['carbohydrateContent']:.0f} g carbohydrate imply "
f"{expected:.0f} kcal). Recheck the estimate; both must be per serving."
)
return {field: f"{value:.0f}" for field, value in values.items()}
@mcp.tool()
def patch_recipe(slug_or_id: str, patch: dict[str, Any]) -> dict[str, Any]:
"""Apply an explicit Mealie recipe patch, then read the recipe back.
@@ -467,9 +573,15 @@ def patch_recipe(slug_or_id: str, patch: dict[str, Any]) -> dict[str, Any]:
Use this for tags and categories too — the bulk-action endpoints return 500 on
this instance. Patch ``recipeCategory`` and ``tags`` directly; a bare name or
``{"name": ...}`` is accepted and resolved to the existing organizer, or
created if the library has no such name. The stable recipe id is captured
before the PATCH because changing ``name`` also changes Mealie's slug, making
the old slug invalid for read-back.
created if the library has no such name.
``nutrition`` is checked before it is sent: Mealie's own field names, bare
numbers, and energy that agrees with the macros. The figures are per serving,
so ``recipeServings`` has to be set — patch it here if the import only left a
yield string.
The stable recipe id is captured before the PATCH because changing ``name``
also changes Mealie's slug, making the old slug invalid for read-back.
"""
before = get_recipe(slug_or_id)
stable_id = before.get("id") or slug_or_id
@@ -477,6 +589,10 @@ def patch_recipe(slug_or_id: str, patch: dict[str, Any]) -> dict[str, Any]:
field: _resolve_organizers(field, value) if field in _ORGANIZER_FIELDS else value
for field, value in patch.items()
}
if "nutrition" in patch:
patch["nutrition"] = _validated_nutrition(
patch["nutrition"], patch.get("recipeServings", before.get("recipeServings"))
)
_request("PATCH", f"/api/recipes/{slug_or_id}", json=patch)
return get_recipe(stable_id)