Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Fabri·Ka9# File : fabrika/schema.py10# Description : Chaque connecteur, peu importe la plateforme ecommerce de11# la boutique, produit des objets `Product` conformes à ce12# schéma.13# Module : fabrika14# Repository : https://git.spboucher.ai/fabri-ka15# Created : 2026-08-1216# Last Modified : 2026-08-2817#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author : Simon-Pierre Boucher23# Position : Professor of Finance24# Institution : Université du Québec en Outaouais (UQO)25# Department : Département des sciences administratives26# Organization : SP Boucher27#28# Website : https://spboucher.ai29# Git : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General : info@spboucher.ai36# Professional : contact@spboucher.ai37# Direct : simon@spboucher.ai38# Research : research@spboucher.ai39# Development : dev@spboucher.ai40# Support : support@spboucher.ai41# Security/Admin : admin@spboucher.ai42# Notifications : notifications@spboucher.ai43#44# Preferred Contact: contact@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification : Public69# Distribution : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License : None specified (no license file in this repository)83# Maintainer : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990# -----------------------------------------------------------------------------91# Fabri-Ka — Agrégateur de produits québécois (marketplace de découverte)92# Auteur : Simon-Pierre Boucher — contact@spboucher.ai93# schema.py : modèles standardisés Product / Store + normalisation94# -----------------------------------------------------------------------------95"""Chaque connecteur, peu importe la plateforme ecommerce de la boutique,96produit des objets `Product` conformes à ce schéma. Le pipeline (ingest.py)97fait le diff avec la base et le frontend consomme un format unique."""98from __future__ import annotations99100import hashlib101import json102import re103import unicodedata104from dataclasses import dataclass, field, asdict105106REGIONS = [107 "Bas-Saint-Laurent", "Saguenay–Lac-Saint-Jean", "Capitale-Nationale",108 "Mauricie", "Estrie", "Montréal", "Outaouais", "Abitibi-Témiscamingue",109 "Côte-Nord", "Nord-du-Québec", "Gaspésie–Îles-de-la-Madeleine",110 "Chaudière-Appalaches", "Laval", "Lanaudière", "Laurentides",111 "Montérégie", "Centre-du-Québec",112]113114# Taxonomie produit Fabri-Ka (clé canonique -> libellé FR + mots-clés de match)115CATEGORIES: dict[str, tuple[str, list[str]]] = {116 "erable": ("Érable & miel", ["erable", "maple", "sirop", "miel", "honey", "hydromel"]),117 "epicerie": ("Épicerie fine", ["confiture", "jam", "sauce", "epice", "spice", "condiment",118 "vinaigre", "huile", "moutarde", "ketchup", "marinade",119 "tartinade", "sel ", "sucre", "farine", "grain", "cereale",120 "granola", "collation", "snack", "chip", "craquelin",121 "sans gluten", "vrac", "conserve", "pesto", "bouillon"]),122 "cafe_the": ("Café & thé", ["cafe", "coffee", "the ", "tisane", "tea", "infusion", "espresso", "matcha"]),123 "chocolat": ("Chocolat & confiseries", ["chocolat", "chocolate", "bonbon", "candy", "caramel",124 "confiserie", "sucrerie", "guimauve", "fudge"]),125 "boulangerie": ("Boulangerie & pâtisserie", ["pain", "bread", "patisserie", "biscuit", "cookie",126 "gateau", "brioche", "viennoiserie", "tarte"]),127 "viande_poisson": ("Viandes & poissons", ["viande", "meat", "boucherie", "charcuterie", "saucisse",128 "jerky", "poisson", "fish", "fruits de mer", "seafood",129 "fume", "smoked", "canard", "porc", "boeuf", "bison", "cerf"]),130 "fromage_laitier": ("Fromages & produits laitiers", ["fromage", "cheese", "laitier", "dairy",131 "yogourt", "beurre", "creme glacee"]),132 "boissons": ("Boissons", ["kombucha", "jus", "juice", "limonade", "boisson", "drink", "cocktail",133 "sirop simple", "tonic", "soda", "eau petillante"]),134 "alcool": ("Bières, vins & spiritueux", ["biere", "beer", "vin ", "wine", "cidre", "cider", "gin",135 "vodka", "whisky", "spiritueux", "hydromel", "brasserie"]),136 "sante_beaute": ("Beauté & soins", ["savon", "soap", "cosmetique", "creme", "skincare", "shampoing",137 "supplement", "vitamine", "huile essentielle", "aromatherapie",138 "hydrolat", "herboristerie", "probiotique",139 "barbe", "beard", "baume", "lotion", "deodorant", "parfum",140 "bain", "bath", "chandelle de massage", "serum", "soin"]),141 "maison": ("Maison & déco", ["chandelle", "bougie", "candle", "deco", "coussin", "vaisselle",142 "ceramique", "poterie", "pottery", "verre", "planche", "ustensile",143 "tablier", "linge", "literie", "couverture", "lampe", "meuble",144 "furniture", "bois", "woodwork", "menuiserie"]),145 "mode": ("Mode & accessoires", ["vetement", "clothing", "t-shirt", "tshirt", "chandail", "hoodie",146 "soulier", "sandale", "chaussure", "botte", "espadrille",147 "valise", "bagage",148 "tuque", "casquette", "chapeau", "foulard", "mitaine", "bas ",149 "chaussette", "manteau", "robe", "jupe", "pantalon", "legging",150 "sac ", "handbag", "cuir", "leather", "portefeuille", "ceinture"]),151 "bijoux": ("Bijoux", ["bijou", "jewel", "collier", "necklace", "bracelet", "bague", "ring",152 "montre", "watch", "horloger",153 "boucle", "earring", "pendentif", "argent sterling",154 "plaque or", "vermeil", "swarovski", "pierre fine"]),155 "art": ("Art & artisanat", ["oeuvre", "art ", "print", "affiche", "poster", "illustration",156 "vitrail", "carte de voeux", "carte de vœux",157 "peinture", "sculpture", "photographie", "carte de souhait",158 "papeterie", "stationery", "carnet", "sticker", "autocollant", "macrame"]),159 "enfants": ("Enfants & bébés", ["bebe", "baby", "enfant", "kid", "jouet", "toy", "doudou",160 "suce ", "biberon", "poussette",161 "hochet", "couche", "puericulture", "peluche", "figurine",162 "casse-tete", "puzzle", "bricolage", "jeu de societe",163 "jeux de societe", "lego", "poupee"]),164 "animaux": ("Animaux", ["chien", "dog", "chat", "cat", "animaux", "pet ", "gaterie", "laisse",165 "collier pour", "litiere"]),166 "plein_air": ("Plein air & sport", ["plein air", "outdoor", "camping", "randonnee", "velo", "bike",167 "peche", "chasse", "kayak", "ski", "raquette", "sport"]),168 "jardin": ("Jardin & agriculture", ["jardin", "garden", "semence", "seed", "plante", "compost",169 "serre", "potager", "engrais"]),170 "industriel": ("Manufacturier & spécialisé", ["outil", "tool", "equipement", "industriel",171 "machine", "piece", "quincaillerie", "electronique",172 "remorque", "trailer", "essieu", "attache", "pneu",173 "frein", "garde-boue", "treuil", "moteur", "hitch",174 "auto", "camion", "vehicule", "soudure", "boulon"]),175 "autre": ("Autre", []),176}177178179def strip_accents(s: str) -> str:180 return "".join(c for c in unicodedata.normalize("NFD", s) if unicodedata.category(c) != "Mn")181182183def infer_category(*texts: str) -> str:184 """Devine la catégorie canonique à partir de textes bruts (type, tags, titre)."""185 blob = " " + strip_accents(" ".join(t for t in texts if t).lower()) + " "186 best, best_hits = "autre", 0187 for key, (_, kws) in CATEGORIES.items():188 hits = sum(1 for kw in kws if kw in blob)189 if hits > best_hits:190 best, best_hits = key, hits191 return best192193194def details_signal_text(details) -> str:195 """Signaux de catégorisation tirés du JSON `details` : noms + valeurs des196 options Shopify et des attributs WooCommerce (matériaux, formats…)."""197 if not isinstance(details, dict) or not details:198 return ""199 parts: list[str] = []200 for o in details.get("options") or []: # Shopify201 if isinstance(o, dict):202 parts.append(str(o.get("name") or ""))203 parts.extend(str(v) for v in (o.get("values") or [])[:12])204 for a in details.get("attributes") or []: # WooCommerce205 if isinstance(a, dict):206 parts.append(str(a.get("name") or ""))207 parts.extend(str(t) for t in (a.get("terms") or [])[:12])208 return " ".join(p for p in parts if p)209210211# --- Règles de pertinence & de qualité (Phase 2 — enrichissement 2026-08) ----212# Un agrégateur de FABRICANTS n'affiche ni cartes-cadeaux, ni ateliers/cours,213# ni abonnements, ni billets d'événements : ces items restent en base214# (marqués, comptés, réintégrables) mais ne sont pas publiés.215PRICE_SANE_MAX = 100_000.0 # au-delà : prix suspect -> quarantaine216217_GIFT_POS = re.compile(r"(carte|certificat)s?[ -]cadeaux?|gift ?card|gift certificate")218_GIFT_NEG = re.compile(r"porte[ -]cartes?|pochette|enveloppe|presentoir|support|boite|etui")219_WORK_T = re.compile(r"^ateliers?\b|\bateliers? (de|d.|creatif|culinaire|priv|decouverte)"220 r"|\bcours (de|d.|en ligne|priv)|^cours\b|^formation|\bformation (en|de|d.)"221 r"|\bworkshop\b|\bmasterclass\b|\bwebinaire\b|\bvisite guidee\b"222 r"|\bcamp de jour\b|\bdegustation (guidee|priv)")223_WORK_PT = re.compile(r"^(ateliers?|cours|formations?|workshops?|classes?|events?|evenements?)$")224_SUB_T = re.compile(r"^abonnements?\b|\babonnements? (a|au|aux|mensuel|annuel|d.un|de)"225 r"|\bsubscription box|^subscription")226_SUB_PT = re.compile(r"^abonnements?$|^subscriptions?$|^adhesions?$|^memberships?$")227_TICK_T = re.compile(r"^billets?\b|\bbillets? (de|d.|pour)|^tickets?\b|\bdroit d.acces"228 r"|\bdroits? d.entree|\blaissez-passer\b|^admission\b|^reservation s?\W*$")229_TICK_PT = re.compile(r"^(billets?|billetterie|tickets?|events?|evenements?|spectacles?)$")230_TEST_T = re.compile(r"^tests? ?(product|produit)?\W*$")231232233def classify_listing(title: str, product_type: str = "") -> str:234 """'published' ou 'excluded:<raison>' selon le titre/type normalisés.235236 Règles calibrées sur la base du 2026-08-19 (623 cartes-cadeaux,237 518 ateliers/cours, 88 abonnements, 23 billets — précision > rappel)."""238 t = strip_accents((title or "").lower())239 pt = strip_accents((product_type or "").lower()).strip()240 if _GIFT_POS.search(t) and not _GIFT_NEG.search(t):241 return "excluded:carte_cadeau"242 if _WORK_T.search(t) or _WORK_PT.match(pt):243 return "excluded:atelier_cours"244 if _SUB_T.search(t) or _SUB_PT.match(pt):245 return "excluded:abonnement"246 if _TICK_T.search(t) or _TICK_PT.match(pt):247 return "excluded:billet"248 if _TEST_T.match(t):249 return "excluded:test"250 return "published"251252253def is_placeholder_price(v: float | None) -> bool:254 """999 999 $, 99 999 $… : placeholders « sur devis » (ecksand & cie)."""255 if v is None or v < 99_999:256 return False257 digits = str(int(v))258 return set(digits) == {"9"}259260261def parse_price(raw) -> float | None:262 """'24,95 $' | '$24.95' | 24.95 -> 24.95 (CAD)."""263 if raw is None:264 return None265 if isinstance(raw, (int, float)):266 return float(raw) if raw > 0 else None267 s = re.sub(r"[^\d,.]", "", str(raw))268 if not s:269 return None270 if "," in s and "." not in s:271 s = s.replace(",", ".")272 else:273 s = s.replace(",", "")274 try:275 v = float(s)276 return v if v > 0 else None277 except ValueError:278 return None279280281@dataclass282class Product:283 """Produit standardisé Fabri-Ka."""284285 store_id: str # domaine canonique de la boutique286 external_id: str # identifiant chez la source287 url: str # page produit chez la boutique288 title: str = ""289 description: str = "" # texte court, sans HTML290 price: float | None = None # CAD, le plus bas des variantes291 price_max: float | None = None # CAD, le plus haut des variantes292 compare_at_price: float | None = None293 currency: str = "CAD"294 images: list[str] = field(default_factory=list)295 category: str = "" # clé canonique (CATEGORIES)296 product_type: str = "" # valeur brute de la source297 tags: list[str] = field(default_factory=list)298 vendor: str = "" # marque affichée par la boutique299 available: bool | None = None300 details: dict = field(default_factory=dict) # avis, dimensions, variantes… (JSON)301 listing_status: str = "published" # published | excluded:<raison> | quarantine:<raison>302 price_on_request: int = 0 # 1 = sur devis / prix non publié par la boutique303304 @property305 def uid(self) -> str:306 return hashlib.sha1(f"{self.store_id}::{self.external_id}".encode()).hexdigest()[:20]307308 def finalize(self) -> "Product":309 import html as _html310 self.title = _html.unescape(re.sub(r"\s+", " ", self.title or "")).strip()[:300]311 # cap 5 000 car. (l'ancien cap 600 tronquait 34 % des fiches — matériaux312 # et dimensions vivent souvent dans la description longue)313 self.description = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", " ", self.description or "")314 self.description = re.sub(r"<[^>]+>", " ", self.description)315 self.description = _html.unescape(re.sub(r"\s+", " ", self.description)).strip()[:5000]316 if not self.category:317 self.category = infer_category(self.product_type, " ".join(self.tags),318 self.title, self.description[:200],319 details_signal_text(self.details))320 self.images = [i for i in self.images if isinstance(i, str) and i.startswith("http")][:15]321 # prix : 0 $ n'est pas un prix (Woo renvoie parfois 0 pour « sur demande »)322 if self.price is not None and self.price <= 0:323 self.price = None324 if self.price_max is not None and self.price_max <= 0:325 self.price_max = None326 # placeholders « sur devis » neutralisés, jamais publiés comme nombres327 if is_placeholder_price(self.price) or is_placeholder_price(self.price_max):328 self.details = dict(self.details or {})329 self.details["price_placeholder"] = self.price330 self.price = self.price_max = self.compare_at_price = None331 if self.price is None:332 self.price_on_request = 1333 # pertinence + quarantaine (aberrations à l'ingestion)334 status = classify_listing(self.title, self.product_type)335 if status == "published":336 if not self.title:337 status = "quarantine:titre_vide"338 elif self.price is not None and self.price > PRICE_SANE_MAX:339 status = "quarantine:prix_hors_bornes"340 self.listing_status = status341 return self342343 def content_hash(self) -> str:344 # len(description)/len(images) : force la mise à jour quand les caps345 # changent (600→5000, 8→15) ou qu'une galerie s'enrichit (Square)346 basis = json.dumps([self.title, self.price, self.price_max, self.available,347 self.images[:1], len(self.images), self.description[:200],348 len(self.description), self.details or None],349 ensure_ascii=False, sort_keys=True)350 return hashlib.sha1(basis.encode()).hexdigest()[:16]351352 def to_row(self) -> dict:353 d = asdict(self)354 d["uid"] = self.uid355 return d356