Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/nutrition.py10# Module : foodka11# Repository : https://git.spboucher.ai/food-ka12# Created : 2026-08-1813# Last Modified : 2026-08-1814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Food-Ka — Agrégateur de produits d'épicerie (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# nutrition.py : enrichissement nutritionnel via Open Food Facts (OFF)91# Les bannières n'exposent pas leurs fiches nutritionnelles sans anti-bot92# (voila.ca : pages PDP derrière Incapsula ; Shopify : pas de code-barres93# dans /products.json public). On croise donc avec la base ouverte OFF :94# https://search.openfoodfacts.org/search (« search-a-licious » : plein95# texte + filtre brands_tags, JSON) — nutriscore, groupe NOVA, nutriments96# /100 g ; les INGRÉDIENTS viennent d'un second appel /api/v2/product/97# {code} (l'index de recherche ne les porte pas). NB : l'ancien98# cgi/search.pl répond 503 (déprécié) — ne pas y revenir.99# Croisement CONSERVATEUR (mieux vaut rater que fusionner faux) :100# - marque non vide obligatoire, et retrouvée dans le champ brands d'OFF ;101# - similarité élevée des noms nettoyés (0,80 si le format concorde102# aussi, 0,90 sinon) ;103# - si les deux formats sont connus, ils doivent concorder (±2 %).104# Budget par cycle (défaut 100 requêtes) + throttle 6 s (limite OFF :105# 10 recherches/min) + cache BD off_cache (une marque+nom+format n'est106# cherchée qu'une seule fois, trouvée ou non — vider off_cache pour107# re-tenter). Résultat stocké dans details.off, ré-appliqué à chaque cycle108# (les mises à jour de produit écrasent details ; le cache est la vérité).109# -----------------------------------------------------------------------------110from __future__ import annotations111112import hashlib113import json114import re115import sqlite3116import time117118import requests119120from .matching import brand_key, name_key, name_similarity, size_key121from .normalize import parse_size, strip_accents122123SEARCH_URL = "https://search.openfoodfacts.org/search"124PRODUCT_URL = ("https://world.openfoodfacts.org/api/v2/product/{code}"125 "?fields=ingredients_text_fr,ingredients_text")126USER_AGENT = "FoodKaBot/1.0 (+https://www.food-ka.com/bot; contact@spboucher.ai)"127128_SLUG_RE = re.compile(r"[^a-z0-9]+")129130REQUEST_DELAY = 6.0 # limite OFF : 10 recherches/minute131SIM_WITH_SIZE = 0.80 # marque + format concordants -> le nom confirme132SIM_NO_SIZE = 0.90 # format inconnu -> quasi-identité exigée133134# nutriments retenus (valeurs /100 g ou /100 ml, + énergie)135_NUTRIMENT_KEYS = (136 "energy-kcal_100g", "fat_100g", "saturated-fat_100g", "trans-fat_100g",137 "carbohydrates_100g", "sugars_100g", "fiber_100g", "proteins_100g",138 "salt_100g", "sodium_100g", "calcium_100g", "iron_100g",139)140141142def match_key(brand: str, name: str, size_label: str) -> str:143 raw = f"{brand_key(brand)}|{name_key(name, brand)}|{size_key(size_label)}"144 return hashlib.md5(raw.encode("utf-8")).hexdigest()145146147def _sizes_agree(ours: str, theirs: str | None) -> bool | None:148 """True/False si les deux formats sont connus, None si l'un manque."""149 a, b = parse_size(ours), parse_size(theirs)150 if not a or not b:151 return None152 (qa, ua), (qb, ub) = a, b153 return ua == ub and abs(qa - qb) <= 0.02 * max(qa, qb)154155156def _pick(hits: list[dict], brand: str, name: str, size_label: str) -> tuple[dict | None, float]:157 """Meilleur candidat OFF respectant marque + nom + format — ou None."""158 ours_nk = name_key(name, brand)159 ours_bk = brand_key(brand)160 best, best_sim = None, 0.0161 for hit in hits:162 # marque : notre marque doit se retrouver dans le champ brands d'OFF163 # (liste chez search-a-licious, chaîne « A, B » sur l'API produit)164 raw = hit.get("brands")165 brand_list = raw if isinstance(raw, list) else str(raw or "").split(",")166 their_brands = [brand_key(str(b)) for b in brand_list]167 if ours_bk not in [b for b in their_brands if b]:168 continue169 hit_name = hit.get("product_name_fr") or hit.get("product_name") or ""170 sim = name_similarity(ours_nk, name_key(hit_name, brand))171 agree = _sizes_agree(size_label, hit.get("quantity"))172 if agree is False:173 continue # formats connus et différents -> rejet174 threshold = SIM_WITH_SIZE if agree else SIM_NO_SIZE175 if sim >= threshold and sim > best_sim:176 best, best_sim = hit, sim177 return best, best_sim178179180def _grade(value) -> str | None:181 """Grade OFF nettoyé — « unknown »/« not-applicable » -> None."""182 v = str(value or "").strip().lower()183 return v if v and v not in ("unknown", "not-applicable") else None184185186def _payload(hit: dict, sim: float, ingredients: str = "") -> dict:187 nutr = hit.get("nutriments") or {}188 brands = hit.get("brands")189 if isinstance(brands, list):190 brands = ", ".join(str(b) for b in brands)191 out = {k: v for k, v in {192 "code": hit.get("code"),193 "product_name": hit.get("product_name_fr") or hit.get("product_name"),194 "brands": brands,195 "quantity": hit.get("quantity"),196 "nutriscore": _grade(hit.get("nutriscore_grade")),197 "nova": hit.get("nova_group"),198 "ecoscore": _grade(hit.get("ecoscore_grade")),199 "ingredients": ingredients[:800] or None,200 "allergens": [str(a).split(":")[-1] for a in hit.get("allergens_tags") or []] or None,201 "nutriments": {k: nutr[k] for k in _NUTRIMENT_KEYS if nutr.get(k) is not None} or None,202 "url": (f"https://world.openfoodfacts.org/product/{hit.get('code')}"203 if hit.get("code") else None),204 "match_similarity": round(sim, 3),205 }.items() if v not in (None, "", {}, [])}206 return out207208209def _search(session: requests.Session, brand: str, name: str) -> list[dict]:210 slug = _SLUG_RE.sub("-", strip_accents(brand).lower()).strip("-")211 params = {212 "q": f'{name[:120]} brands_tags:"{slug}"',213 "page_size": "10", "langs": "fr",214 }215 resp = session.get(SEARCH_URL, params=params, timeout=25)216 resp.raise_for_status()217 return (resp.json().get("hits") or [])218219220def _ingredients(session: requests.Session, code) -> str:221 """Texte des ingrédients (FR de préférence) — jamais bloquant."""222 if not code:223 return ""224 try:225 resp = session.get(PRODUCT_URL.format(code=code), timeout=25)226 resp.raise_for_status()227 prod = resp.json().get("product") or {}228 return str(prod.get("ingredients_text_fr")229 or prod.get("ingredients_text") or "")230 except Exception:231 return ""232233234# ---------------------------------------------------------------------------235# Cycle d'enrichissement (appelé après chaque ingestion)236# ---------------------------------------------------------------------------237238def enrich(con: sqlite3.Connection, budget: int = 100) -> dict:239 """Recherche OFF pour au plus `budget` nouveaux produits (jamais cherchés),240 puis (ré)applique details.off à tous les produits actifs appariés."""241 rows = con.execute(242 """SELECT p.uid, p.brand, p.name, p.size_label,243 (l.uid IS NOT NULL) AS linked244 FROM products p LEFT JOIN product_links l ON l.uid = p.uid245 WHERE p.active=1 AND p.brand<>'' AND p.name<>''246 ORDER BY linked DESC, p.last_seen DESC""").fetchall()247248 cached: dict[str, sqlite3.Row] = {249 r["match_key"]: r for r in250 con.execute("SELECT match_key, found, payload FROM off_cache")}251252 session = requests.Session()253 session.headers["User-Agent"] = USER_AGENT254 searched = matched = errors = 0255 now = time.time()256 for r in rows:257 if searched >= budget or errors >= 3: # OFF injoignable -> on n'insiste pas258 break259 key = match_key(r["brand"], r["name"], r["size_label"])260 if key in cached:261 continue262 searched += 1263 try:264 hits = _search(session, r["brand"], r["name"])265 best, sim = _pick(hits, r["brand"], r["name"], r["size_label"])266 errors = 0267 except Exception:268 errors += 1269 searched -= 1270 time.sleep(REQUEST_DELAY)271 continue272 if best:273 time.sleep(1.0) # politesse entre recherche et fiche produit274 payload = _payload(best, sim, _ingredients(session, best.get("code")))275 else:276 payload = {}277 found = 1 if best else 0278 matched += found279 con.execute(280 "INSERT INTO off_cache (match_key, code, found, payload, fetched_at)"281 " VALUES (?,?,?,?,?) ON CONFLICT(match_key) DO UPDATE SET"282 " code=excluded.code, found=excluded.found,"283 " payload=excluded.payload, fetched_at=excluded.fetched_at",284 (key, payload.get("code"), found,285 json.dumps(payload, ensure_ascii=False), now))286 con.commit()287 cached[key] = {"match_key": key, "found": found, # type: ignore[assignment]288 "payload": json.dumps(payload, ensure_ascii=False)}289 time.sleep(REQUEST_DELAY)290291 # (ré)application : le cache est la source de vérité de details.off292 applied = 0293 for r in con.execute(294 """SELECT uid, brand, name, size_label, details FROM products295 WHERE active=1 AND brand<>'' AND name<>''""").fetchall():296 hit = cached.get(match_key(r["brand"], r["name"], r["size_label"]))297 if hit is None or not hit["found"]:298 continue299 try:300 payload = json.loads(hit["payload"] or "{}")301 details = json.loads(r["details"] or "{}")302 except ValueError:303 continue304 if not payload or details.get("off") == payload:305 continue306 details["off"] = payload307 con.execute("UPDATE products SET details=? WHERE uid=?",308 (json.dumps(details, ensure_ascii=False), r["uid"]))309 applied += 1310 con.commit()311 with_off = con.execute(312 "SELECT COUNT(*) c FROM products WHERE active=1"313 " AND details LIKE '%\"off\"%'").fetchone()["c"]314 return {"searched": searched, "matched": matched, "applied": applied,315 "products_with_off": with_off}316