Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/matching.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# matching.py : rapprochement inter-bannières — « le même produit ailleurs »91# Après chaque cycle d'ingestion, reconstruit la table product_links92# (group_id, uid) : groupes de produits ACTIFS identiques vendus par des93# bannières DIFFÉRENTES, rapprochés par clé normalisée94# marque + nom nettoyé + format.95# Matching CONSERVATEUR (mieux vaut rater un rapprochement qu'en inventer) :96# - marque non vide obligatoire (égalité stricte après normalisation) ;97# - format identique (quantité + unité de base via parse_size) ;98# - similarité élevée entre noms nettoyés (accents/casse/mots vides/99# format retirés, jetons triés) — seuil 0,86, ou 0,95 si aucun format100# n'est connu de part et d'autre.101# Une source « *_flyer » est la même bannière que sa source catalogue102# (metro / metro_flyer) : un groupe doit couvrir >= 2 bannières distinctes.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import hashlib107import re108import sqlite3109from difflib import SequenceMatcher110111from .normalize import parse_size, strip_accents112113# seuils de similarité (SequenceMatcher sur jetons triés)114SIM_WITH_SIZE = 0.86 # marque + format identiques -> le nom confirme115SIM_NO_SIZE = 0.95 # aucun format connu -> quasi-identité exigée116# Sources hors matching épicerie : la SAQ est une bannière unique à prix117# provinciaux uniformes — aucun « même produit ailleurs » pertinent, et ses118# vins/bières ne doivent pas se rapprocher des rayons boissons des épiceries.119EXCLUDED_SOURCES = frozenset({"saq"})120MAX_BLOCK = 3000 # garde-fou : bloc (marque, format) anormalement gros121 # (comparaisons en fenêtre triée de 30 -> coût linéaire ;122 # les marques maison dépassent 400 depuis les circulaires)123124_ALNUM_RE = re.compile(r"[^a-z0-9]+")125# jetons de format dans le nom (« 2 x 450 g », « 1,5 l »…) — retirés du nom126_SIZE_TOKEN_RE = re.compile(127 r"\b\d+(?:[.,]\d+)?\s*(?:x|×)?\s*\d*(?:[.,]\d+)?\s*"128 r"(?:kg|g|mg|lb|lbs|oz|ml|cl|l|un|unites?|ea|each|pk)\b")129_STOPWORDS = {130 "de", "du", "des", "la", "le", "les", "l", "d", "et", "a", "au", "aux",131 "en", "pour", "the", "of", "and", "with", "un", "une",132}133134135def banner(source: str) -> str:136 """Bannière d'une source — « metro_flyer » et « metro » = même bannière."""137 return source[:-6] if source.endswith("_flyer") else source138139140def brand_key(brand: str) -> str:141 """Marque normalisée (accents/casse/ponctuation) — '' si inutilisable."""142 key = _ALNUM_RE.sub("", strip_accents(brand or "").lower())143 return key if len(key) >= 2 else ""144145146def name_key(name: str, brand: str = "") -> str:147 """Nom nettoyé : accents/casse, marque, format et mots vides retirés,148 jetons triés (robuste à l'ordre FR/EN des mots). Les jetons NUMÉRIQUES149 restants sont conservés : ils sont discriminants (« lait 2 % » vs150 « lait 3,25 % ») — name_similarity exige leur égalité stricte."""151 s = strip_accents(name or "").lower()152 s = _SIZE_TOKEN_RE.sub(" ", s)153 s = _ALNUM_RE.sub(" ", s)154 drop = set(_STOPWORDS)155 if brand:156 drop |= set(_ALNUM_RE.sub(" ", strip_accents(brand).lower()).split())157 tokens = [t for t in s.split() if t and t not in drop]158 return " ".join(sorted(tokens))159160161def size_key(size_label: str) -> str:162 """Format canonique « 450|g », « 2000|ml »… — '' si non extractible."""163 parsed = parse_size(size_label)164 if not parsed:165 return ""166 qty, base = parsed167 return f"{qty:g}|{base}"168169170_NUM_RE = re.compile(r"\d+")171172173def name_similarity(a: str, b: str) -> float:174 """Similarité de deux noms nettoyés (name_key). Garde-fou : les jetons175 numériques doivent être IDENTIQUES (« lait 2 » ≠ « lait 3 25 ») — un176 chiffre différent = produit différent (teneur en gras, compte, calibre)."""177 if not a or not b:178 return 0.0179 if a == b:180 return 1.0181 if set(_NUM_RE.findall(a)) != set(_NUM_RE.findall(b)):182 return 0.0183 return SequenceMatcher(None, a, b).ratio()184185186# ---------------------------------------------------------------------------187# Reconstruction de la table product_links188# ---------------------------------------------------------------------------189190def rebuild(con: sqlite3.Connection) -> dict:191 """Reconstruit product_links à partir des produits actifs. Retourne des192 compteurs : groupes multi-bannières, produits reliés, bannières couvertes."""193 rows = con.execute(194 """SELECT uid, source, brand, name, size_label FROM products195 WHERE active=1 AND brand<>'' AND name<>''""").fetchall()196197 # blocs de candidats : même marque + même format (clé exacte)198 blocks: dict[tuple[str, str], list[tuple[str, str, str]]] = {}199 for r in rows:200 if r["source"] in EXCLUDED_SOURCES:201 continue202 bk = brand_key(r["brand"])203 if not bk:204 continue205 nk = name_key(r["name"], r["brand"])206 if not nk:207 continue208 blocks.setdefault((bk, size_key(r["size_label"])),209 []).append((r["uid"], r["source"], nk))210211 groups: list[list[str]] = []212 for (bk, sk), members in blocks.items():213 if len(members) < 2 or len(members) > MAX_BLOCK:214 continue215 threshold = SIM_WITH_SIZE if sk else SIM_NO_SIZE216 # union-find sur la similarité des noms nettoyés217 parent = list(range(len(members)))218219 def find(i: int) -> int:220 while parent[i] != i:221 parent[i] = parent[parent[i]]222 i = parent[i]223 return i224225 # tri par nom nettoyé : les paires proches sont voisines — on ne226 # compare chaque membre qu'à une fenêtre bornée (blocs petits en227 # pratique, la fenêtre évite le pire cas quadratique)228 order = sorted(range(len(members)), key=lambda i: members[i][2])229 for a in range(len(order)):230 for b in range(a + 1, min(a + 30, len(order))):231 i, j = order[a], order[b]232 if name_similarity(members[i][2], members[j][2]) >= threshold:233 parent[find(i)] = find(j)234 clusters: dict[int, list[int]] = {}235 for i in range(len(members)):236 clusters.setdefault(find(i), []).append(i)237 for idx in clusters.values():238 uids = [members[i][0] for i in idx]239 banners = {banner(members[i][1]) for i in idx}240 if len(banners) >= 2: # inter-bannières seulement241 groups.append(sorted(set(uids)))242243 con.execute("DELETE FROM product_links")244 linked = 0245 for uids in groups:246 gid = hashlib.md5("|".join(uids).encode("utf-8")).hexdigest()[:16]247 for uid in uids:248 # un produit ne peut appartenir qu'à un groupe (uid = clé primaire)249 con.execute(250 "INSERT OR IGNORE INTO product_links (group_id, uid) VALUES (?,?)",251 (gid, uid))252 linked += 1253 con.commit()254 real_groups = con.execute(255 "SELECT COUNT(DISTINCT group_id) c FROM product_links").fetchone()["c"]256 real_linked = con.execute(257 "SELECT COUNT(*) c FROM product_links").fetchone()["c"]258 return {"groups": real_groups, "linked_products": real_linked}259