SPB Git

Repository Public

normalize.py 12.1 KB 297 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/normalize.py10# Module           : foodka11# Repository       : https://git.spboucher.ai/food-ka12# Created          : 2026-08-1213# 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# normalize.py : normalisation des champs bruts des connecteurs91#   prix, formats (450 g, 2 L, 12 un), prix unitaire ($/100 g),92#   catégories canoniques, marques.93# -----------------------------------------------------------------------------94from __future__ import annotations9596import re97import unicodedata9899__all__ = [100    "strip_accents", "parse_price", "parse_size", "unit_price",101    "format_unit_price", "normalize_category", "clean_text",102]103104105def strip_accents(text: str) -> str:106    return "".join(c for c in unicodedata.normalize("NFD", text or "")107                   if unicodedata.category(c) != "Mn")108109110def clean_text(text: str | None) -> str:111    """Espaces normalisés, entités résiduelles retirées."""112    if not text:113        return ""114    return re.sub(r"\s+", " ", text).strip()115116117# ---------------------------------------------------------------------------118# Prix — "3,49 $", "$3.49", "2 / 5,00 $", "349¢"119# ---------------------------------------------------------------------------120121_PRICE_RE = re.compile(r"(\d{1,4}(?:[  ]\d{3})*(?:[.,]\d{1,2})?)\s*\$|\$\s*(\d{1,4}(?:[.,]\d{1,2})?)")122_MULTI_RE = re.compile(r"(\d+)\s*(?:/|pour|for)\s*(\d{1,4}(?:[.,]\d{1,2})?)\s*\$")123_CENTS_RE = re.compile(r"(\d{1,3})\s*¢")124125126def parse_price(label: str | float | int | None) -> float | None:127    """Extrait un prix unitaire ($ CAD) d'un libellé source.128129    Gère "2 / 5,00 $" (prix multi-achat → prix à l'unité), "3,49 $",130    "$3.49" et "99 ¢". Retourne None si aucun prix affiché — jamais131    de prix inventé.132    """133    if label is None:134        return None135    if isinstance(label, (int, float)):136        return float(label) if label > 0 else None137    text = str(label)138    m = _MULTI_RE.search(text)139    if m:140        n, total = int(m.group(1)), float(m.group(2).replace(",", "."))141        if n > 0:142            return round(total / n, 2)143    m = _PRICE_RE.search(text)144    if m:145        raw = (m.group(1) or m.group(2)).replace(" ", "").replace(" ", "")146        return float(raw.replace(",", "."))147    m = _CENTS_RE.search(text)148    if m:149        return round(int(m.group(1)) / 100, 2)150    return None151152153# ---------------------------------------------------------------------------154# Formats — "450 g", "1,5 L", "12 x 355 ml", "6 un", "environ 200 g"155# ---------------------------------------------------------------------------156157# unité canonique -> (facteur vers unité de base, unité de base)158_UNITS = {159    "kg": (1000.0, "g"), "g": (1.0, "g"), "mg": (0.001, "g"),160    "lb": (453.592, "g"), "lbs": (453.592, "g"), "oz": (28.3495, "g"),161    "l": (1000.0, "ml"), "ml": (1.0, "ml"), "cl": (10.0, "ml"),162    "un": (1.0, "un"), "unite": (1.0, "un"), "unites": (1.0, "un"),163    "ea": (1.0, "un"), "each": (1.0, "un"), "pk": (1.0, "un"),164}165166_SIZE_RE = re.compile(167    r"(?:(\d+)\s*[x×]\s*)?(\d+(?:[.,]\d+)?)\s*(kg|g|mg|lb|lbs|oz|ml|cl|l|un|unites?|ea|each|pk)\b",168    re.IGNORECASE)169170171def parse_size(label: str | None) -> tuple[float, str] | None:172    """Extrait (quantité, unité de base) d'un format.173174    "450 g" -> (450, "g") ; "2 L" -> (2000, "ml") ;175    "12 x 355 ml" -> (4260, "ml") ; "6 un" -> (6, "un").176    """177    if not label:178        return None179    m = _SIZE_RE.search(strip_accents(label))180    if not m:181        return None182    mult = int(m.group(1)) if m.group(1) else 1183    qty = float(m.group(2).replace(",", "."))184    factor, base = _UNITS[m.group(3).lower()]185    total = mult * qty * factor186    return (total, base) if total > 0 else None187188189def unit_price(price: float | None, size_label: str | None) -> tuple[float, str] | None:190    """Prix par unité comparable : $/100 g, $/100 ml ou $/un."""191    if price is None:192        return None193    size = parse_size(size_label)194    if not size:195        return None196    qty, base = size197    if base == "un":198        return (round(price / qty, 2), "un")199    return (round(price / qty * 100, 3), f"100 {base}")200201202def format_unit_price(up: tuple[float, str] | None) -> str:203    if not up:204        return ""205    value, base = up206    return f"{value:.2f} $ / {base}".replace(".", ",")207208209# ---------------------------------------------------------------------------210# Catégories canoniques — chaque bannière a sa propre taxonomie ; on la211# rabat sur un ensemble commun pour permettre les filtres inter-épiceries.212# ---------------------------------------------------------------------------213214CATEGORIES = [215    "Fruits et légumes",216    "Viandes et volailles",217    "Poissons et fruits de mer",218    "Charcuteries et fromages",219    "Produits laitiers et œufs",220    "Boulangerie",221    "Surgelés",222    "Garde-manger",223    "Boissons",224    "Collations et confiseries",225    "Prêt-à-manger",226    "Bio et santé",227    "Bébé",228    "Animaux",229    "Maison et entretien",230    "Santé et beauté",231    "Alcool",232    "Autres",233]234235# mots-clés (sans accents, minuscules) -> catégorie canonique ; l'ordre compte,236# le premier motif trouvé gagne.237_CATEGORY_RULES: list[tuple[str, str]] = [238    ("fruit", "Fruits et légumes"), ("legume", "Fruits et légumes"),239    ("produce", "Fruits et légumes"), ("vegetable", "Fruits et légumes"),240    ("charcuterie", "Charcuteries et fromages"), ("deli", "Charcuteries et fromages"),241    ("fromage", "Charcuteries et fromages"), ("cheese", "Charcuteries et fromages"),242    ("viande", "Viandes et volailles"), ("volaille", "Viandes et volailles"),243    ("boeuf", "Viandes et volailles"), ("porc", "Viandes et volailles"),244    ("poulet", "Viandes et volailles"), ("meat", "Viandes et volailles"),245    ("poisson", "Poissons et fruits de mer"), ("fruits de mer", "Poissons et fruits de mer"),246    ("seafood", "Poissons et fruits de mer"), ("poissonnerie", "Poissons et fruits de mer"),247    ("laitier", "Produits laitiers et œufs"), ("lait", "Produits laitiers et œufs"),248    ("oeuf", "Produits laitiers et œufs"), ("dairy", "Produits laitiers et œufs"),249    ("yogourt", "Produits laitiers et œufs"), ("egg", "Produits laitiers et œufs"),250    ("boulangerie", "Boulangerie"), ("pain", "Boulangerie"),251    ("patisserie", "Boulangerie"), ("bakery", "Boulangerie"),252    ("surgele", "Surgelés"), ("congele", "Surgelés"), ("frozen", "Surgelés"),253    ("boisson", "Boissons"), ("jus", "Boissons"), ("eau", "Boissons"),254    ("cafe", "Boissons"), ("the ", "Boissons"), ("biere", "Boissons"),255    ("vin", "Boissons"), ("beverage", "Boissons"), ("drink", "Boissons"),256    ("collation", "Collations et confiseries"), ("croustille", "Collations et confiseries"),257    ("bonbon", "Collations et confiseries"), ("chocolat", "Collations et confiseries"),258    ("confiserie", "Collations et confiseries"), ("snack", "Collations et confiseries"),259    ("candy", "Collations et confiseries"), ("biscuit", "Collations et confiseries"),260    ("pret-a-manger", "Prêt-à-manger"), ("prets-a-manger", "Prêt-à-manger"),261    ("repas prepare", "Prêt-à-manger"), ("mets prepare", "Prêt-à-manger"),262    ("prepared", "Prêt-à-manger"), ("ready", "Prêt-à-manger"),263    ("biologique", "Bio et santé"), ("organic", "Bio et santé"),264    ("naturel", "Bio et santé"), ("sante et mieux", "Bio et santé"),265    ("vrac", "Bio et santé"), ("supplement", "Bio et santé"),266    ("bebe", "Bébé"), ("baby", "Bébé"), ("couche", "Bébé"),267    ("animaux", "Animaux"), ("animal", "Animaux"), ("pet", "Animaux"),268    ("nettoyage", "Maison et entretien"), ("entretien", "Maison et entretien"),269    ("menager", "Maison et entretien"), ("maison", "Maison et entretien"),270    ("cleaning", "Maison et entretien"), ("household", "Maison et entretien"),271    ("papier", "Maison et entretien"), ("lessive", "Maison et entretien"),272    ("beaute", "Santé et beauté"), ("pharmacie", "Santé et beauté"),273    ("hygiene", "Santé et beauté"), ("soin", "Santé et beauté"),274    ("health", "Santé et beauté"), ("beauty", "Santé et beauté"),275    ("cosmetique", "Santé et beauté"),276    ("epicerie", "Garde-manger"), ("garde-manger", "Garde-manger"),277    ("pantry", "Garde-manger"), ("grocery", "Garde-manger"),278    ("conserve", "Garde-manger"), ("pates", "Garde-manger"),279    ("cereale", "Garde-manger"), ("condiment", "Garde-manger"),280    ("sauce", "Garde-manger"), ("dejeuner", "Garde-manger"),281    ("cuisine du monde", "Garde-manger"), ("international", "Garde-manger"),282]283284285def normalize_category(raw: str | None) -> str:286    """Rabat une catégorie source (fr/en, n'importe quelle bannière) sur la287    taxonomie canonique Food-Ka. Retourne "Autres" si rien ne correspond."""288    if not raw:289        return "Autres"290    if raw in CATEGORIES:291        return raw292    key = strip_accents(raw).lower()293    for pattern, cat in _CATEGORY_RULES:294        if pattern in key:295            return cat296    return "Autres"297
Files main
Menu

Theme