"""Nutrition arithmetic. Pure code: no database, no clock, no randomness, no network. All sums are made on exact decimals; rounding happens once, in `display`. A total is never shown as complete when any input had no data: `complete` covers calories, protein, carbs and fat, and `fibre_complete` covers fibre (a food with no fibre value is common and should not mark everything). """ from collections.abc import Iterable from dataclasses import dataclass from decimal import ROUND_HALF_UP, Decimal from typing import Any HUNDRED = Decimal(100) MAX_SERVING_G = Decimal(5000) MAX_KCAL_PER_100G = Decimal(902) # pure fat is 9 kcal per g @dataclass(frozen=True) class Per100: """Nutrition per 100 g. None means the source has no value (not zero).""" kcal: Decimal | None protein_g: Decimal | None carbs_g: Decimal | None fat_g: Decimal | None fibre_g: Decimal | None estimate: bool = False # a typical value, not a measured or labelled one @dataclass(frozen=True) class Draw: """Grams of one thing that went into a meal, with its per-100 g values (None = no data).""" label: str grams: Decimal per100: Per100 | None @dataclass(frozen=True) class Macros: kcal: Decimal protein_g: Decimal carbs_g: Decimal fat_g: Decimal fibre_g: Decimal complete: bool # calories, protein, carbs and fat are known for every input fibre_complete: bool missing: tuple[str, ...] # inputs left out of the numbers, in the order met estimated: tuple[str, ...] = () # inputs whose values are typical estimates ZERO = Macros( Decimal(0), Decimal(0), Decimal(0), Decimal(0), Decimal(0), True, True, () ) def _merge(a: Iterable[str], b: Iterable[str]) -> tuple[str, ...]: out: list[str] = [] for x in [*a, *b]: if x not in out: out.append(x) return tuple(out) def sum_draws(draws: Iterable[Draw]) -> Macros: k = p = c = f = fib = Decimal(0) complete = fibre_complete = True missing: list[str] = [] estimated: list[str] = [] for d in draws: scale = d.grams / HUNDRED v = d.per100 if v is None: complete = False fibre_complete = False if d.label not in missing: missing.append(d.label) continue if v.estimate and d.label not in estimated: estimated.append(d.label) main = (v.kcal, v.protein_g, v.carbs_g, v.fat_g) if any(x is None for x in main): complete = False if d.label not in missing: missing.append(d.label) k += scale * (v.kcal or 0) p += scale * (v.protein_g or 0) c += scale * (v.carbs_g or 0) f += scale * (v.fat_g or 0) if v.fibre_g is None: fibre_complete = False else: fib += scale * v.fibre_g return Macros( k, p, c, f, fib, complete, fibre_complete, tuple(missing), tuple(estimated) ) def add(items: Iterable[Macros]) -> Macros: total = ZERO for m in items: total = Macros( total.kcal + m.kcal, total.protein_g + m.protein_g, total.carbs_g + m.carbs_g, total.fat_g + m.fat_g, total.fibre_g + m.fibre_g, total.complete and m.complete, total.fibre_complete and m.fibre_complete, _merge(total.missing, m.missing), _merge(total.estimated, m.estimated), ) return total def times(m: Macros, factor: Decimal) -> Macros: return Macros( m.kcal * factor, m.protein_g * factor, m.carbs_g * factor, m.fat_g * factor, m.fibre_g * factor, m.complete, m.fibre_complete, m.missing, m.estimated, ) def per_portion(total: Macros, portions: Decimal) -> Macros: if portions <= 0: raise ValueError("portions must be positive") return Macros( total.kcal / portions, total.protein_g / portions, total.carbs_g / portions, total.fat_g / portions, total.fibre_g / portions, total.complete, total.fibre_complete, total.missing, total.estimated, ) def typed( kcal: Decimal, protein_g: Decimal, carbs_g: Decimal, fat_g: Decimal, fibre_g: Decimal | None, ) -> Macros: return Macros( kcal, protein_g, carbs_g, fat_g, fibre_g or Decimal(0), True, fibre_g is not None, (), ) def unknown(label: str) -> Macros: z = Decimal(0) return Macros(z, z, z, z, z, False, False, (label,)) def _round(x: Decimal, places: int) -> Decimal: return x.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP) def display(m: Macros) -> dict[str, Any]: """The numbers as shown: calories whole, the rest to one decimal.""" return { "kcal": int(_round(m.kcal, 0)), "protein_g": float(_round(m.protein_g, 1)), "carbs_g": float(_round(m.carbs_g, 1)), "fat_g": float(_round(m.fat_g, 1)), "fibre_g": float(_round(m.fibre_g, 1)), "complete": m.complete, "fibre_complete": m.fibre_complete, "missing": list(m.missing), "estimated": list(m.estimated), } def check_calories( kcal: Decimal, protein_g: Decimal, carbs_g: Decimal, fat_g: Decimal ) -> list[str]: """Calories should be near 4 per g of protein and carbs and 9 per g of fat (within 20% or 20 kcal).""" estimate = 4 * protein_g + 4 * carbs_g + 9 * fat_g slack = max(Decimal(20), estimate * Decimal("0.2")) if abs(kcal - estimate) > slack: what = "4 per g of protein and carbs and 9 per g of fat" return [ f"The calories ({kcal:g}) do not match the macros (about {estimate:g} from {what})." ] return [] def check_panel(p: Per100) -> list[str]: """Plain-language problems with a typed or looked-up panel; empty means it looks right.""" problems: list[str] = [] vals = { "calories": p.kcal, "protein": p.protein_g, "carbs": p.carbs_g, "fat": p.fat_g, "fibre": p.fibre_g, } if any(v is not None and v < 0 for v in vals.values()): problems.append("A value is negative.") if p.kcal is None: problems.append("The calories are missing.") if None in (p.protein_g, p.carbs_g, p.fat_g): problems.append( "Protein, carbs and fat all need a value (type 0 if the label says 0)." ) if problems: return problems assert p.kcal is not None and p.protein_g is not None assert p.carbs_g is not None and p.fat_g is not None if p.protein_g + p.carbs_g + p.fat_g > HUNDRED + Decimal("0.5"): problems.append("Protein, carbs and fat add up to more than 100 g in 100 g.") if p.kcal > MAX_KCAL_PER_100G: problems.append( f"The calories ({p.kcal:g}) do not match a real food: 100 g cannot have more than about 900." ) problems.extend(check_calories(p.kcal, p.protein_g, p.carbs_g, p.fat_g)) if p.fibre_g is not None and p.fibre_g > p.carbs_g + Decimal("0.5"): problems.append("The fibre is more than the carbs (carbs include fibre).") return problems def from_serving( kcal: Decimal | None, protein_g: Decimal | None, carbs_g: Decimal | None, fat_g: Decimal | None, fibre_g: Decimal | None, serving_g: Decimal, ) -> Per100: """Convert values printed per serving to per 100 g.""" if not Decimal(1) <= serving_g <= MAX_SERVING_G: raise ValueError("serving size must be between 1 and 5000 g") f = HUNDRED / serving_g def conv(x: Decimal | None) -> Decimal | None: return None if x is None else x * f return Per100( conv(kcal), conv(protein_g), conv(carbs_g), conv(fat_g), conv(fibre_g) ) def normalise_barcode(raw: str) -> str | None: """The 13-digit form used to look a product up, or None when the code cannot be right. Accepts UPC-12, EAN-13 and GTIN-14 with a leading 0 (what receipts hold). The GS1 check digit must match. Codes with a real packaging indicator (1 to 8) name a case, not one item: refused. """ if not raw.isascii() or not raw.isdigit() or len(raw) not in (12, 13, 14): return None padded = raw.zfill(14) if padded[0] != "0": return None total = sum(int(c) * (3 if i % 2 == 0 else 1) for i, c in enumerate(padded[:13])) if (10 - total % 10) % 10 != int(padded[13]): return None return padded[1:] def choose_panel( typed: Per100 | None, off: Per100 | None, generic: Per100 | None ) -> Per100 | None: """Typed label first (read from the real package), then Open Food Facts, then generic.""" for panel in (typed, off, generic): if panel is not None: return panel return None def plausible_for( ingredient_kcal: Decimal | None, product_kcal: Decimal | None ) -> bool: """Is a product's calories per 100 g close enough to its matched ingredient's to save it without a person looking? Within 50% of the ingredient; for ingredients under 20 kcal per 100 g, within 20 kcal. Missing numbers are never plausible.""" if ingredient_kcal is None or product_kcal is None: return False slack = Decimal(20) if ingredient_kcal < 20 else ingredient_kcal * Decimal("0.5") return abs(product_kcal - ingredient_kcal) <= slack