#!/usr/bin/env python3 """Builds Horai/Resources/off-foods.json from the Open Food Facts CSV export. Usage: tools/build-off.py [path-to-en.openfoodfacts.org.products.csv.gz] Keeps the most scanned products sold in a handful of countries, per 100 g, with the allergens and ingredients as the label lists them. Open Food Facts is published under the ODbL, and this output is a derived database, so it must be shared under the ODbL too: publish the generated file next to the attribution in the app's About page. Data: https://world.openfoodfacts.org, (c) Open Food Facts contributors, ODbL 1.0. """ import csv, gzip, json, os, re, sys, urllib.request URL = "https://openfoodfacts-ds.s3.eu-west-3.amazonaws.com/en.openfoodfacts.org.products.csv.gz" COLUMNS = ["kcal", "protein", "carbs", "fat", "fiber", "sugar", "sodium", "calcium", "iron", "potassium", "magnesium", "caffeine"] # Products kept per country, most scanned first. A product sold in several countries counts once. QUOTA = {"en:greece": 6000, "en:cyprus": 1500, "en:france": 6000, "en:germany": 5000, "en:italy": 4000, "en:spain": 4000, "en:united-kingdom": 5000, "en:ireland": 1500, "en:united-states": 6000, "en:switzerland": 1500, "en:austria": 1500, "en:belgium": 1500, "en:netherlands": 1500} SMALL = {"en:greece", "en:cyprus"} ALLERGENS = {"milk": "milk", "gluten": "gluten", "eggs": "egg", "peanuts": "peanut", "nuts": "nuts", "sesame-seeds": "sesame", "fish": "fish", "crustaceans": "crustacean", "molluscs": "mollusc", "soybeans": "soy", "celery": "celery", "mustard": "mustard", "lupin": "lupin", "sulphur-dioxide-and-sulphites": "sulphites"} def num(text): try: return float(text) except (TypeError, ValueError): return None def product(row): name = re.sub(r"\s+", " ", row["product_name"]).strip() if len(name) < 2 or len(name) > 90: return None kcal = num(row["energy-kcal_100g"]) if kcal is None and num(row["energy_100g"]) is not None: kcal = num(row["energy_100g"]) / 4.184 if kcal is None or not 0 <= kcal <= 900: return None protein, carbs, fat = (num(row[k]) for k in ("proteins_100g", "carbohydrates_100g", "fat_100g")) if all(v is None for v in (protein, carbs, fat)): return None # a calories-only record is too thin to trust if sum(v or 0 for v in (protein, carbs, fat)) > 105: return None # impossible per 100 g sodium = num(row["sodium_100g"]) sodium = sodium * 1000 if sodium is not None else (num(row["salt_100g"]) / 2.5 * 1000 if num(row["salt_100g"]) is not None else None) def mg(key): v = num(row[key]) return None if v is None else v * 1000 def keep(v, digits): return None if v is None else round(v, digits) values = [round(kcal), keep(protein, 1), keep(carbs, 1), keep(fat, 1), keep(num(row["fiber_100g"]), 1), keep(num(row["sugars_100g"]), 1), keep(sodium, 0), keep(mg("calcium_100g"), 0), keep(mg("iron_100g"), 1), keep(mg("potassium_100g"), 0), keep(mg("magnesium_100g"), 0), keep(mg("caffeine_100g"), 0)] serving = (row["serving_size"] or "").strip() grams = num(row["serving_quantity"]) or 0 if grams <= 0 or grams > 2000 or len(serving) > 40: serving, grams = "", 0 liquid = bool(re.search(r"\d\s*(ml|cl|l)\b", (serving + " " + (row["quantity"] or "")).lower())) brand = (row["brands"] or "").split(",")[0].strip()[:40] allergens = ",".join(sorted({ALLERGENS[t.split(":")[-1]] for t in (row["allergens"] or "").split(",") if t.split(":")[-1] in ALLERGENS})) ingredients = re.sub(r"\s+", " ", row["ingredients_text"] or "").strip()[:200] return [name, brand, row["code"], values, serving, round(grams, 1), 1 if liquid else 0, allergens, ingredients] def build(path): csv.field_size_limit(10**9) pools = {c: [] for c in QUOTA} with gzip.open(path, "rt", encoding="utf-8", newline="") as f: for row in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): countries = [c for c in (row["countries_tags"] or "").split(",") if c in QUOTA] if not countries or not row["product_name"] or not row["code"].isdigit(): continue scans = int(num(row["unique_scans_n"]) or 0) for c in countries: # The small markets have few scanned products, so they keep every complete one. if scans >= 1 or c in SMALL: pools[c].append((scans, row["code"], row)) foods, seen_codes, seen_names = [], set(), set() for country, pool in pools.items(): pool.sort(key=lambda p: -p[0]) taken = 0 for scans, code, row in pool: if taken >= QUOTA[country]: break if code in seen_codes: continue item = product(row) if item is None: continue key = (item[0].lower(), item[1].lower()) if key in seen_names: continue seen_codes.add(code) seen_names.add(key) foods.append(item) taken += 1 print(country, taken) return foods if __name__ == "__main__": path = sys.argv[1] if len(sys.argv) > 1 else "/tmp/off/off.csv.gz" if not os.path.exists(path): os.makedirs(os.path.dirname(path), exist_ok=True) print("downloading", URL) urllib.request.urlretrieve(URL, path) foods = build(path) out = os.path.join(os.path.dirname(__file__), "..", "Horai", "Resources", "off-foods.json") with open(out, "w", encoding="utf-8") as f: json.dump({"version": 1, "columns": COLUMNS, "foods": foods}, f, separators=(",", ":"), ensure_ascii=False) print(len(foods), "products,", round(os.path.getsize(out) / 1e6, 2), "MB ->", os.path.normpath(out))