feat: Listen-Dialog mit Mengen/Einheiten, Mitai ohne Kochrezepte
Roh-Kombinationen statt Rezept-Sprache; Zutaten suchen, EL/TL/Prise auf Gramm. Gekochte Gerichte und Ausbeute bleiben Tandoor. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a7e5511039
commit
fa542e0fb9
17 files changed
+776
-203
No files matched your search
@@ -168,6 +168,8 @@ def export_food_knowledge(cur, profile_id: str) -> dict[str, Any]:
|
||||
"source_name_normalized": ing.get("source_name_normalized"),
|
||||
"quantity_raw": ing.get("quantity_raw"),
|
||||
"quantity_g": _jsonable(ing.get("quantity_g")),
|
||||
"quantity_amount": _jsonable(ing.get("quantity_amount")),
|
||||
"source_unit": ing.get("source_unit"),
|
||||
"sort_order": ing.get("sort_order") or 0,
|
||||
}
|
||||
for ing in rec.get("ingredients") or []
|
||||
|
||||
@@ -132,6 +132,16 @@ UNIT_ALIASES = {
|
||||
MASS_VOLUME_TO_G = {"g": 1.0, "kg": 1000.0, "ml": 1.0, "l": 1000.0}
|
||||
DEFAULT_UNIT_G = {"el": 15.0, "tl": 5.0, "prise": 0.3, "msp": 1.0}
|
||||
COUNT_UNITS = frozenset({"stück", "scheibe", "portion", "becher", "tasse"})
|
||||
UNIT_LABELS = {
|
||||
"g": "g", "kg": "kg", "ml": "ml", "l": "l",
|
||||
"el": "EL", "tl": "TL", "prise": "Prise", "msp": "Msp.",
|
||||
"stück": "Stück", "scheibe": "Scheibe", "portion": "Portion",
|
||||
"becher": "Becher", "tasse": "Tasse",
|
||||
}
|
||||
UNIT_ORDER = (
|
||||
"g", "ml", "el", "tl", "prise", "msp",
|
||||
"stück", "scheibe", "portion", "becher", "tasse", "kg", "l",
|
||||
)
|
||||
QTY_PARSE_RE = re.compile(
|
||||
r"^\s*(\d+(?:[.,]\d+)?)\s*([a-zA-ZäöüÄÖÜß.]+)?\s*$",
|
||||
re.IGNORECASE,
|
||||
@@ -186,6 +196,74 @@ def detect_quantity_unit(*texts: str | None) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def format_quantity_raw(value: float | None, unit: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
label = UNIT_LABELS.get(unit or "g", unit or "g")
|
||||
num = int(value) if float(value) == int(value) else value
|
||||
return f"{num} {label}".replace(".", ",")
|
||||
|
||||
|
||||
def list_quantity_units() -> list[dict[str, Any]]:
|
||||
out = []
|
||||
for uid in UNIT_ORDER:
|
||||
default_g = MASS_VOLUME_TO_G.get(uid)
|
||||
if default_g is None:
|
||||
default_g = DEFAULT_UNIT_G.get(uid)
|
||||
out.append({
|
||||
"id": uid,
|
||||
"label": UNIT_LABELS[uid],
|
||||
"default_g": default_g,
|
||||
"needs_unit_map": uid in COUNT_UNITS,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def resolve_quantity(
|
||||
*,
|
||||
quantity_raw: str | None = None,
|
||||
quantity_amount: float | None = None,
|
||||
source_unit: str | None = None,
|
||||
quantity_g: float | None = None,
|
||||
grams_per_unit: float | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Amount + unit → quantity_g. Standard unit is grams; conversion uses mapping or defaults."""
|
||||
amount = None
|
||||
if quantity_amount not in (None, ""):
|
||||
try:
|
||||
amount = float(quantity_amount)
|
||||
except (TypeError, ValueError):
|
||||
amount = None
|
||||
explicit_g = None
|
||||
if quantity_g not in (None, ""):
|
||||
try:
|
||||
explicit_g = float(quantity_g)
|
||||
except (TypeError, ValueError):
|
||||
explicit_g = None
|
||||
if amount is not None:
|
||||
unit = _canon_unit(source_unit) or "g"
|
||||
raw = format_quantity_raw(amount, unit)
|
||||
parsed = parse_quantity(raw.replace(",", "."), grams_per_unit)
|
||||
elif quantity_raw:
|
||||
parsed = parse_quantity(quantity_raw, grams_per_unit)
|
||||
elif explicit_g is not None:
|
||||
parsed = {"value": explicit_g, "unit": "g", "quantity_g": explicit_g, "needs_unit_map": False}
|
||||
else:
|
||||
parsed = {"value": None, "unit": _canon_unit(source_unit), "quantity_g": None, "needs_unit_map": False}
|
||||
qty_g = parsed.get("quantity_g")
|
||||
if qty_g is None and explicit_g is not None:
|
||||
qty_g = explicit_g
|
||||
unit = parsed.get("unit")
|
||||
value = parsed.get("value")
|
||||
return {
|
||||
"quantity_amount": value,
|
||||
"source_unit": unit,
|
||||
"quantity_raw": format_quantity_raw(value, unit) or (str(quantity_raw).strip() if quantity_raw else None),
|
||||
"quantity_g": qty_g,
|
||||
"needs_unit_map": bool(parsed.get("needs_unit_map")),
|
||||
}
|
||||
|
||||
|
||||
def get_food_mapping_with_cursor(
|
||||
cur,
|
||||
source_name: str,
|
||||
|
||||
@@ -4,10 +4,32 @@ from __future__ import annotations
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from data_layer.food_mapping import get_food_mapping_with_cursor, normalize_food_name
|
||||
from data_layer.food_mapping import (
|
||||
get_food_mapping_with_cursor,
|
||||
normalize_food_name,
|
||||
resolve_quantity,
|
||||
)
|
||||
from data_layer.nutrition_items import catalog_macros_for_item, _f
|
||||
|
||||
|
||||
def _resolved_ingredient_qty(cur, profile_id: str, source_name_raw: str, ing: dict[str, Any]) -> dict[str, Any]:
|
||||
mapping = get_food_mapping_with_cursor(cur, source_name_raw, profile_id)
|
||||
gpu = ing.get("grams_per_unit")
|
||||
if gpu in (None, ""):
|
||||
gpu = mapping.get("grams_per_unit") if mapping else None
|
||||
try:
|
||||
gpu = float(gpu) if gpu not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
gpu = None
|
||||
return resolve_quantity(
|
||||
quantity_raw=ing.get("quantity_raw"),
|
||||
quantity_amount=ing.get("quantity_amount"),
|
||||
source_unit=ing.get("source_unit"),
|
||||
quantity_g=ing.get("quantity_g"),
|
||||
grams_per_unit=gpu,
|
||||
)
|
||||
|
||||
|
||||
def upsert_recipes(cur, profile_id: str, recipes: list[dict[str, Any]]) -> dict[str, int]:
|
||||
inserted = updated = ingredients = 0
|
||||
for rec in recipes:
|
||||
@@ -46,16 +68,19 @@ def upsert_recipes(cur, profile_id: str, recipes: list[dict[str, Any]]) -> dict[
|
||||
inorm = ing.get("source_name_normalized") or normalize_food_name(ing.get("source_name_raw"))
|
||||
if not inorm:
|
||||
continue
|
||||
raw_name = ing.get("source_name_raw") or inorm
|
||||
qty = _resolved_ingredient_qty(cur, profile_id, raw_name, ing)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_recipe_ingredients
|
||||
(id, recipe_id, source_name_raw, source_name_normalized,
|
||||
quantity_raw, quantity_g, sort_order)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
||||
quantity_raw, quantity_g, quantity_amount, source_unit, sort_order)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
""",
|
||||
(
|
||||
str(uuid.uuid4()), rid, ing["source_name_raw"], inorm,
|
||||
ing.get("quantity_raw"), ing.get("quantity_g"), ing.get("sort_order") or 0,
|
||||
str(uuid.uuid4()), rid, raw_name, inorm,
|
||||
qty["quantity_raw"], qty["quantity_g"], qty["quantity_amount"], qty["source_unit"],
|
||||
ing.get("sort_order") or 0,
|
||||
),
|
||||
)
|
||||
ingredients += 1
|
||||
@@ -111,7 +136,8 @@ def list_recipes(cur, profile_id: str) -> list[dict[str, Any]]:
|
||||
ids = [str(r["id"]) for r in recipes]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT recipe_id, source_name_raw, source_name_normalized, quantity_raw, quantity_g, sort_order
|
||||
SELECT recipe_id, source_name_raw, source_name_normalized,
|
||||
quantity_raw, quantity_g, quantity_amount, source_unit, sort_order
|
||||
FROM food_recipe_ingredients
|
||||
WHERE recipe_id = ANY(%s::uuid[])
|
||||
ORDER BY sort_order, source_name_raw
|
||||
@@ -195,19 +221,18 @@ def save_recipe(cur, profile_id: str, rec: dict[str, Any], recipe_id: str | None
|
||||
inorm = ing.get("source_name_normalized") or normalize_food_name(raw)
|
||||
if not inorm:
|
||||
continue
|
||||
qty = ing.get("quantity_g")
|
||||
try:
|
||||
qty = float(qty) if qty not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
qty = None
|
||||
qty = _resolved_ingredient_qty(cur, profile_id, raw or inorm, ing)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_recipe_ingredients
|
||||
(id, recipe_id, source_name_raw, source_name_normalized,
|
||||
quantity_raw, quantity_g, sort_order)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
||||
quantity_raw, quantity_g, quantity_amount, source_unit, sort_order)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
""",
|
||||
(str(uuid.uuid4()), rid, raw or inorm, inorm, ing.get("quantity_raw"), qty, i),
|
||||
(
|
||||
str(uuid.uuid4()), rid, raw or inorm, inorm,
|
||||
qty["quantity_raw"], qty["quantity_g"], qty["quantity_amount"], qty["source_unit"], i,
|
||||
),
|
||||
)
|
||||
link_recipes_to_items(cur, profile_id)
|
||||
saved = get_recipe(cur, profile_id, rid)
|
||||
@@ -249,7 +274,7 @@ def mapped_ingredient_quantities(
|
||||
return None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT source_name_raw, quantity_g
|
||||
SELECT source_name_raw, quantity_g, quantity_raw, quantity_amount, source_unit
|
||||
FROM food_recipe_ingredients
|
||||
WHERE recipe_id = %s
|
||||
ORDER BY sort_order
|
||||
@@ -259,22 +284,29 @@ def mapped_ingredient_quantities(
|
||||
ings = cur.fetchall()
|
||||
if not ings:
|
||||
return None
|
||||
total_g = sum(_f(i.get("quantity_g")) for i in ings)
|
||||
resolved_ings = []
|
||||
for ing in ings:
|
||||
mapping = get_food_mapping_with_cursor(cur, ing["source_name_raw"], profile_id)
|
||||
if not mapping:
|
||||
return None
|
||||
qty = resolve_quantity(
|
||||
quantity_raw=ing.get("quantity_raw"),
|
||||
quantity_amount=ing.get("quantity_amount"),
|
||||
source_unit=ing.get("source_unit"),
|
||||
quantity_g=ing.get("quantity_g"),
|
||||
grams_per_unit=mapping.get("grams_per_unit"),
|
||||
)
|
||||
grams = _f(qty.get("quantity_g"))
|
||||
if grams <= 0:
|
||||
return None
|
||||
resolved_ings.append({"food_id": mapping["food_id"], "quantity_g": grams})
|
||||
total_g = sum(i["quantity_g"] for i in resolved_ings)
|
||||
if eaten_qty_g and eaten_qty_g > 0 and total_g > 0:
|
||||
scale = float(eaten_qty_g) / total_g
|
||||
else:
|
||||
portions = float(rec.get("portions") or 1) or 1.0
|
||||
scale = 1.0 / portions
|
||||
out = []
|
||||
for ing in ings:
|
||||
mapping = get_food_mapping_with_cursor(cur, ing["source_name_raw"], profile_id)
|
||||
if not mapping:
|
||||
return None
|
||||
out.append({
|
||||
"food_id": mapping["food_id"],
|
||||
"quantity_g": _f(ing.get("quantity_g")) * scale,
|
||||
})
|
||||
return out
|
||||
return [{**i, "quantity_g": i["quantity_g"] * scale} for i in resolved_ings]
|
||||
|
||||
|
||||
def catalog_macros_for_recipe(cur, profile_id: str, recipe_id: str, eaten_qty_g: float | None) -> dict[str, float] | None:
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Menge + Einheit an Rezeptzutaten; quantity_g bleibt die Standardeinheit (Gramm).
|
||||
|
||||
ALTER TABLE food_recipe_ingredients
|
||||
ADD COLUMN IF NOT EXISTS quantity_amount NUMERIC(10,3),
|
||||
ADD COLUMN IF NOT EXISTS source_unit VARCHAR(20);
|
||||
|
||||
COMMENT ON COLUMN food_recipe_ingredients.quantity_amount IS 'Menge in source_unit (z. B. 2 TL)';
|
||||
COMMENT ON COLUMN food_recipe_ingredients.source_unit IS 'Kanonische Einheit: g, ml, el, tl, prise, stück, …';
|
||||
COMMENT ON COLUMN food_recipe_ingredients.quantity_g IS 'Umrechnung auf Gramm, wenn Faktor bekannt';
|
||||
|
||||
UPDATE food_recipe_ingredients
|
||||
SET quantity_amount = quantity_g, source_unit = 'g'
|
||||
WHERE quantity_g IS NOT NULL AND quantity_amount IS NULL AND source_unit IS NULL;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
RAISE NOTICE 'Migration 066: recipe ingredient amount + unit';
|
||||
END $$;
|
||||
@@ -13,6 +13,7 @@ from data_layer.food_mapping import (
|
||||
apply_mapping_to_items,
|
||||
apply_quantities_to_items,
|
||||
clear_mapping_from_items,
|
||||
list_quantity_units,
|
||||
normalize_food_name,
|
||||
upsert_food_mapping,
|
||||
)
|
||||
@@ -79,6 +80,11 @@ def _schedule_rebuild(profile_id: str, dates: list[str], context: str) -> None:
|
||||
).start()
|
||||
|
||||
|
||||
@router.get("/units")
|
||||
def list_food_units(session: dict = Depends(require_auth)):
|
||||
return list_quantity_units()
|
||||
|
||||
|
||||
@router.get("/foods")
|
||||
def search_foods(
|
||||
q: str = "",
|
||||
|
||||
@@ -28,6 +28,9 @@ class RecipeIngredientIn(BaseModel):
|
||||
source_name_raw: str
|
||||
quantity_raw: Optional[str] = None
|
||||
quantity_g: Optional[float] = None
|
||||
quantity_amount: Optional[float] = None
|
||||
source_unit: Optional[str] = None
|
||||
grams_per_unit: Optional[float] = None
|
||||
|
||||
|
||||
class RecipeIn(BaseModel):
|
||||
|
||||
@@ -3,11 +3,13 @@ from datetime import date
|
||||
from csv_parser.executor import guess_nutrition_item_fields
|
||||
from data_layer.food_mapping import (
|
||||
filter_unmapped_since,
|
||||
list_quantity_units,
|
||||
merge_unmapped_rows,
|
||||
normalize_food_name,
|
||||
parse_quantity,
|
||||
parse_quantity_g,
|
||||
primary_search_query,
|
||||
resolve_quantity,
|
||||
)
|
||||
from data_layer.nutrition_items import macros_differ
|
||||
|
||||
@@ -46,6 +48,20 @@ def test_parse_quantity_g():
|
||||
assert parse_quantity("2 EL")["unit"] == "el"
|
||||
|
||||
|
||||
def test_resolve_quantity_household_units():
|
||||
two_tl = resolve_quantity(quantity_amount=2, source_unit="tl")
|
||||
assert two_tl["quantity_g"] == 10.0
|
||||
assert two_tl["quantity_raw"] == "2 TL"
|
||||
pinch = resolve_quantity(quantity_amount=1, source_unit="prise")
|
||||
assert pinch["quantity_g"] == 0.3
|
||||
slice_ = resolve_quantity(quantity_amount=1, source_unit="stück")
|
||||
assert slice_["quantity_g"] is None
|
||||
assert slice_["needs_unit_map"] is True
|
||||
assert resolve_quantity(quantity_amount=1, source_unit="stück", grams_per_unit=60)["quantity_g"] == 60.0
|
||||
ids = [u["id"] for u in list_quantity_units()]
|
||||
assert "tl" in ids and "prise" in ids
|
||||
|
||||
|
||||
def test_guess_fddb_bezeichnung_without_template_mapping():
|
||||
name, qty = guess_nutrition_item_fields({
|
||||
"bezeichnung": "50 g Hähnchen",
|
||||
|
||||
+6
-3
@@ -9,7 +9,7 @@ Semantic Versioning: MAJOR.MINOR.PATCH
|
||||
|
||||
APP_VERSION = "0.9v"
|
||||
BUILD_DATE = "2026-09-12"
|
||||
DB_SCHEMA_VERSION = "20260912b" # 065 omega attribute extensions
|
||||
DB_SCHEMA_VERSION = "20260912c" # 066 recipe ingredient units
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"auth": "1.2.0",
|
||||
@@ -20,8 +20,8 @@ MODULE_VERSIONS = {
|
||||
"circumference": "1.0.1",
|
||||
"caliper": "1.0.1",
|
||||
"activity": "1.2.1", # Legacy CSV import: activity_entries feature enforcement
|
||||
"nutrition": "1.2.9", # Zuordnen: Lebensmittel oder Rezept anlegen
|
||||
"bls": "1.0.4",
|
||||
"nutrition": "1.3.2", # UI: Liste/Kombination; Tandoor-Gerichte später
|
||||
"bls": "1.0.5", # GET /bls/units
|
||||
"photos": "1.0.0",
|
||||
"insights": "1.3.0",
|
||||
"prompts": "1.1.0",
|
||||
@@ -55,6 +55,9 @@ CHANGELOG = [
|
||||
"Katalogsuche: Fettgehalt (9,5 / 10 %) bleibt erhalten, Joghurt 10% vor >3,5%",
|
||||
"Eigenes Lebensmittel: beliebige Katalog-Stoffe (EPA/DHA/…) plus Portionsumrechnung auf 100 g",
|
||||
"Zuordnen: Mapping-Export robust; Rezepte anlegen/bearbeiten; Admin-Mapping direkt ändern",
|
||||
"Rezept-Dialog: Zutaten aus Zuordnungen und Katalog suchen; Tandoor später",
|
||||
"Rezeptzutaten: Menge + Einheit (EL/TL/Prise/Stück); Umrechnung auf Gramm",
|
||||
"Zuordnen: Mitai = Liste/Kombination; gekochte Rezepte Tandoor + Ausbeute später",
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user