"""Turning one row of the Open Food Facts bulk CSV into one clean product row (pure code). A value that is missing, not a number, negative or absurd becomes None, never 0. Text is cleaned of control characters. Nothing here touches the network, the file system or the database. """ import re from dataclasses import dataclass from decimal import Decimal, InvalidOperation from typing import Any from engine.nutrition import normalise_barcode KEEP_TAGS = ("en:canada", "en:united-states") # volunteers tag where they saw a product KJ_PER_KCAL = Decimal("4.184") MAX_KCAL = Decimal( 902 ) # the limits of the table (migration 013): a value over them is emptied MAX_G = Decimal(100) # here, so one odd row can never make the whole import fail MAX_AMOUNT = Decimal(1000) @dataclass(frozen=True) class Row: code: str # 13 digits, as the receipt look-up uses it name: str | None brand: str | None quantity_text: str | None pack_g: Decimal | None kcal: Decimal | None protein_g: Decimal | None carbs_g: Decimal | None fat_g: Decimal | None fibre_g: Decimal | None serving_g: Decimal | None per_text: str | None # "100g" or "100ml": what the numbers are per countries: str # the matching tags, kept so a later narrowing needs no re-download def wanted_countries(tags: str | None) -> list[str]: parts = [t.strip().lower() for t in (tags or "").split(",")] return [t for t in KEEP_TAGS if t in parts] def clean_text(x: Any, limit: int = 300) -> str | None: if not isinstance(x, str): return None out = "".join(c for c in x if c.isprintable()).strip()[:limit] return out or None def number(x: Any, high: Decimal = MAX_AMOUNT) -> Decimal | None: if x is None or isinstance(x, bool): return None try: d = Decimal(str(x).strip()) except (InvalidOperation, ValueError): return None return d if d.is_finite() and 0 <= d <= high else None def fit( d: Decimal | None, places: int, high: Decimal, positive: bool = False ) -> Decimal | None: """The value as the table stores it (rounded to its decimal places), or None when it would break the table's rule after rounding. The table has numeric(_, places) columns: a tiny 0.0001 rounds to 0, which fails a 'greater than 0' rule, so the rounding is done here before the table sees it.""" if d is None: return None d = d.quantize(Decimal(1).scaleb(-places)) if d < 0 or d > high or (positive and d <= 0): return None return d _PACK = re.compile( r"^\s*(?:(\d{1,3})\s*[x×]\s*)?(\d+(?:[.,]\d+)?)\s*(kg|g)\s*$", re.IGNORECASE ) def pack_grams(quantity: str | None) -> Decimal | None: """Grams only when unambiguous ('500 g', '1 kg', '2 x 100 g'); litres and ounces stay text.""" if not quantity: return None m = _PACK.match(quantity) if m is None: return None each = Decimal(m.group(2).replace(",", ".")) if m.group(3).lower() == "kg": each *= 1000 total = each * Decimal(m.group(1) or 1) return fit(total, 3, Decimal(1_000_000), positive=True) def parse_row(r: dict[str, str]) -> Row | None: """None when the row is not wanted: wrong country, no usable barcode, or nothing to keep.""" tags = wanted_countries(r.get("countries_tags")) if not tags: return None code = normalise_barcode((r.get("code") or "").strip()) if code is None: return None kcal = number(r.get("energy-kcal_100g"), MAX_KCAL) if kcal is None: # kilojoules only: converted here, in code kj = number(r.get("energy-kj_100g"), Decimal(4000)) kcal = None if kj is None else (kj / KJ_PER_KCAL).quantize(Decimal("0.01")) if ( kcal is not None and kcal > MAX_KCAL ): # the table refuses these, so empty it here kcal = None kcal = fit(kcal, 4, MAX_KCAL) protein, carbs = ( fit(number(r.get("proteins_100g"), MAX_G), 4, MAX_G), fit(number(r.get("carbohydrates_100g"), MAX_G), 4, MAX_G), ) fat = fit(number(r.get("fat_100g"), MAX_G), 4, MAX_G) fibre = fit(number(r.get("fiber_100g"), MAX_G), 4, MAX_G) name = clean_text(r.get("product_name")) if name is None and all(v is None for v in (kcal, protein, carbs, fat, fibre)): return None quantity = clean_text(r.get("quantity"), 100) serving = fit( number(r.get("serving_quantity"), Decimal(5000)), 3, Decimal(5000), positive=True, ) per = clean_text(r.get("nutrition_data_per"), 20) return Row( code=code, name=name, brand=clean_text(r.get("brands")), quantity_text=quantity, pack_g=pack_grams(quantity), kcal=kcal, protein_g=protein, carbs_g=carbs, fat_g=fat, fibre_g=fibre, serving_g=serving, per_text=per.lower().replace(" ", "") if per else None, countries=",".join(tags), )