Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/schema.py10# Description : Schéma standard d'un produit d'épicerie (Product) et11# normalisation.12# Module : foodka13# Repository : https://git.spboucher.ai/food-ka14# Created : 2026-08-1215# Last Modified : 2026-08-1216#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author : Simon-Pierre Boucher22# Position : Professor of Finance23# Institution : Université du Québec en Outaouais (UQO)24# Department : Département des sciences administratives25# Organization : SP Boucher26#27# Website : https://spboucher.ai28# Git : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General : info@spboucher.ai35# Professional : contact@spboucher.ai36# Direct : simon@spboucher.ai37# Research : research@spboucher.ai38# Development : dev@spboucher.ai39# Support : support@spboucher.ai40# Security/Admin : admin@spboucher.ai41# Notifications : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification : Public68# Distribution : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License : None specified (no license file in this repository)82# Maintainer : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889# -----------------------------------------------------------------------------90# Food-Ka — Agrégateur de produits d'épicerie (province de Québec)91# Auteur : Simon-Pierre Boucher — contact@spboucher.ai92# schema.py : modèle de données standardisé (Product) + enrichissement central93# -----------------------------------------------------------------------------94"""Schéma standard d'un produit d'épicerie (Product) et normalisation.9596Chaque connecteur, peu importe la bannière (Metro, IGA, Maxi…), doit97produire des objets `Product` conformes à ce schéma. La méthode98`finalize()` applique ensuite la couche de normalisation commune99(foodka/normalize.py) : prix, prix unitaire $/100 g, catégorie100canonique… — les connecteurs restent simples et remplissent les101champs bruts.102"""103from __future__ import annotations104105import hashlib106import json107from dataclasses import dataclass, field, asdict108109from .normalize import ( # ré-exportés pour les connecteurs110 clean_text,111 format_unit_price,112 normalize_category,113 parse_price,114 parse_size,115 strip_accents,116 unit_price,117)118119__all__ = [120 "Product", "normalize_category", "parse_price", "parse_size",121 "clean_text", "strip_accents",122]123124125@dataclass126class Product:127 """Produit d'épicerie standardisé Food-Ka."""128129 source: str # id de la bannière (voir data/sources.json)130 external_id: str # identifiant/SKU chez la source131 url: str # fiche produit chez la source132 name: str = "" # ex. "Beurre d'arachide croquant"133 brand: str = "" # ex. "Kraft"134 category: str = "" # catégorie canonique Food-Ka135 category_raw: str = "" # taxonomie originale de la bannière136 size_label: str = "" # format affiché, ex. "500 g", "2 L"137 price: float | None = None # prix courant ($ CAD), rabais inclus138 regular_price: float | None = None # prix régulier si le produit est en solde139 price_label: str = "" # texte original (ex. "2 / 5,00 $")140 on_sale: bool = False # produit en promotion141 unit_price: float | None = None # prix par unité comparable142 unit_price_label: str = "" # ex. "0,70 $ / 100 g"143 in_stock: bool | None = None # None = inconnu144 description: str = ""145 keywords: list[str] = field(default_factory=list) # tags source (bio, sans gluten…)146 details: dict = field(default_factory=dict) # champs structurés (JSON)147 images: list[str] = field(default_factory=list) # URLs absolues148149 @property150 def uid(self) -> str:151 return f"{self.source}:{self.external_id}"152153 def content_hash(self) -> str:154 """Hash du contenu pour la détection de changements (pseudo-webhook)."""155 payload = asdict(self)156 blob = json.dumps(payload, sort_keys=True, ensure_ascii=False)157 return hashlib.sha256(blob.encode("utf-8")).hexdigest()158159 def finalize(self) -> "Product":160 """Applique la normalisation commune. Appelé par le pipeline d'ingestion.161162 Idempotent ; ne remplace jamais une valeur explicite du connecteur.163 """164 self.name = clean_text(self.name)165 self.brand = clean_text(self.brand)166 self.size_label = clean_text(self.size_label)167 self.description = clean_text(self.description)168169 if not self.category:170 self.category = normalize_category(self.category_raw)171172 if self.price is None:173 self.price = parse_price(self.price_label)174175 # cohérence solde : un "prix régulier" égal ou inférieur au prix176 # courant n'apporte rien — on le laisse tomber.177 if self.regular_price is not None and self.price is not None:178 if self.regular_price <= self.price:179 self.regular_price = None180 else:181 self.on_sale = True182 if self.regular_price is None and not self.on_sale:183 self.on_sale = False184185 if self.unit_price is None:186 up = unit_price(self.price, self.size_label)187 if up:188 self.unit_price = up[0]189 if not self.unit_price_label:190 self.unit_price_label = format_unit_price(up)191192 # garde-fou : prix absurdes (0 $, > 2000 $) = donnée cassée, pas un prix193 if self.price is not None and not (0 < self.price <= 2000):194 self.price = None195 self.regular_price = None196 self.on_sale = False197198 return self199