SPB Git

Repository Public

_flipp.py 17.5 KB 370 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/_flipp.py10# Module           : foodka11# Repository       : https://git.spboucher.ai/food-ka12# Created          : 2026-08-1613# 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# connectors/_flipp.py : socle commun des bannières « circulaire seulement »91#   Beaucoup d'épiceries de proximité (affiliés Metro et Sobeys) n'ont aucun92#   catalogue en ligne : leur seule donnée de prix est la circulaire hebdo,93#   hébergée sur Flipp. Le backend Flipp (backflipp.wishabi.com) est une API94#   JSON publique sans clé ni anti-bot :95#     1. /flipp/flyers?locale=fr-ca&postal_code=…  -> circulaires de la zone96#        (filtrer côté client sur merchant_id — le paramètre d'URL ne filtre pas)97#     2. /flipp/flyers/{flyer_id}?locale=fr-ca     -> items avec prix98#   Une seule circulaire provinciale par bannière par semaine (vérifié sur99#   4 codes postaux) : un poste montréalais suffit. Le flyer_id change chaque100#   semaine — toujours résolu dynamiquement via l'étape 1.101#   Les items n'ont ni SKU ni catégorie ni unité (« /lb ») : external_id =102#   slug stable marque+nom+format (continuité du price_log d'une semaine à103#   l'autre), catégorie déduite du nom du produit.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import re108109from ..schema import Product, clean_text, strip_accents110from .base import BaseConnector111112LIST_URL = ("https://backflipp.wishabi.com/flipp/flyers"113            "?locale=fr-ca&postal_code={postal}")114FLYER_URL = "https://backflipp.wishabi.com/flipp/flyers/{flyer_id}?locale=fr-ca"115ITEM_URL = "https://backflipp.wishabi.com/flipp/items/{item_id}?locale=fr-ca"116117# format dans le nom : « (550 à 675 g) », « 2 L », « 9,1 ou 12,7 kg »…118_SIZE_IN_NAME = re.compile(119    r"((?:\d+\s*[x×]\s*)?\d+(?:[.,]\d+)?\s*(?:kg|g|ml|l|lb|oz|un))\b",120    re.IGNORECASE)121_SLUG_RE = re.compile(r"[^a-z0-9]+")122123# Catégorisation par mots du nom (les items Flipp n'ont pas de taxonomie).124# Motifs à frontière de mot sur le nom FRANÇAIS sans accents ; l'ordre compte125# (les motifs composés/désambiguïsants d'abord). Faute de correspondance :126# default_category du flyer, sinon « Autres ».127_NAME_RULES: list[tuple[re.Pattern, str]] = [(re.compile(rf"\b(?:{pat})\b"), cat) for pat, cat in [128    # désambiguïsations prioritaires129    (r"eaux? de (?:parfum|toilette|cologne)|parfums?|cremes? adhesives?|"130     r"cremes? (?:pour )?(?:le )?(?:corps|mains?|visage)", "Santé et beauté"),131    (r"eaux? de javel|javel", "Maison et entretien"),132    (r"beurres? d.arachides?|tartinades?|vinaigre\w*", "Garde-manger"),133    (r"cremes? glacees?|sorbets?|surgele\w*|congele\w*|pizzas?", "Surgelés"),134    (r"chocolat\w*|croustilles?|chips|biscuits?|bonbons?|craquelins?|"135     r"barres? tendres|popcorn|mais souffle|arachides?|noix|gommes?|"136     r"friandises?|collations?", "Collations et confiseries"),137    (r"jus|eaux?|boissons?|cafes?|thes?|tisanes?|sodas?|cola|bieres?|vins?|"138     r"cidres?|limonades?|smoothies?|kombucha", "Boissons"),139    (r"fromages?|cheddar|mozzarella|feta|brie|parmesan|jambons?|salami|"140     r"pepperoni|prosciutto|charcuteries?", "Charcuteries et fromages"),141    (r"lait|laits|yogourts?|oeufs?|margarines?|beurres?|cremes?",142     "Produits laitiers et œufs"),143    (r"saumons?|truites?|tilapia|morue|aiglefin|sole|thons?|crevettes?|"144     r"homards?|petoncles?|poissons?|fruits de mer|calmars?",145     "Poissons et fruits de mer"),146    (r"boeuf|poulets?|porc|veau|agneau|dindes?|poitrines?|cuisses?|"147     r"biftecks?|steaks?|cotelettes?|saucisses?|tournedos|rotis?|hache\w*|"148     r"bacon|viandes?", "Viandes et volailles"),149    (r"pains?|baguettes?|bagels?|muffins?|tortillas?|croissants?|brioches?|"150     r"gateau\w*|tarte\w*|patisseries?", "Boulangerie"),151    (r"peches?|pommes?|bananes?|fraises?|framboises?|bleuets?|raisins?|"152     r"melons?|ananas|celeris?|laitues?|salades?|carottes?|brocolis?|"153     r"chou\w*|poivrons?|tomates?|concombres?|oignons?|patates?|mais|"154     r"avocats?|citrons?|limes?|cerises?|prunes?|poires?|mangues?|kiwis?|"155     r"champignons?|epinards?|asperges?|courge\w*|legumes?|fruits?",156     "Fruits et légumes"),157    (r"cereales?|pates?|riz|sauces?|conserves?|soupes?|bouillons?|huiles?|"158     r"vinaigre\w*|farines?|sucres?|ketchup|mayonnaise|moutarde|confitures?|"159     r"miel|gruau|granola|tofu|legumineuses?|epices?", "Garde-manger"),160    (r"repas|sushis?|sandwich\w*|pret[- ]a[- ]manger", "Prêt-à-manger"),161    (r"vitamines?|supplements?|proteines?|probiotiques?|collagene|curcuma|"162     r"chlorophylle|omega", "Bio et santé"),163    (r"couches?|bebes?", "Bébé"),164    (r"chats?|chiens?|litieres?|animaux", "Animaux"),165    (r"papiers?|essuie[- ]tout|lessives?|detergents?|savons?|nettoyants?|"166     r"javel|assouplissants?", "Maison et entretien"),167    (r"shampoing\w*|shampooing\w*|dentifrices?|deodorants?|hygiene",168     "Santé et beauté"),169]]170171172def _categorize(name_fr: str, default: str) -> str:173    key = strip_accents(name_fr).lower()174    for rx, cat in _NAME_RULES:175        if rx.search(key):176            return cat177    return default or "Autres"178179180# Rayons « épicerie » de la taxonomie canonique — pour les bannières dont la181# circulaire mêle alimentaire et non-alimentaire (pharmacies : cosmétiques,182# médicaments…), keep_categories = GROCERY_CATEGORIES ne retient que le183# alimentaire. Conservateur : un item non catégorisé (« Autres ») est écarté.184GROCERY_CATEGORIES = frozenset({185    "Fruits et légumes", "Viandes et volailles", "Poissons et fruits de mer",186    "Charcuteries et fromages", "Produits laitiers et œufs", "Boulangerie",187    "Surgelés", "Garde-manger", "Boissons", "Collations et confiseries",188    "Prêt-à-manger",189})190191192class FlippConnector(BaseConnector):193    """Base des circulaires Flipp — sous-classes : source_id, merchant_id,194    flyer_page (URL humaine de la circulaire, pour le lien produit).195196    `default_categories` associe un nom de flyer à une catégorie par défaut197    (ex. Rachelle-Béry « Espace Santé » -> « Bio et santé »)."""198199    merchant_id: int = 0200    postal_code: str = "H2X1Y4"                 # Montréal — capte les flyers provinciaux201    flyer_page: str = ""202    default_categories: dict[str, str] = {}203    # Certaines bannières publient PLUSIEURS circulaires sous le même204    # merchant_id (ex. Supermarché PA : « Weekly Flyer » + « Nature Flyer »).205    # Si non vide, seuls les flyers dont le nom contient ce texte (insensible206    # à la casse) sont retenus. Un tuple accepte plusieurs libellés : Flipp207    # renomme ses cahiers sans préavis (« Circulaire hebdomadaire » ->208    # « Weekly Ad », « Circulaire » -> « Costco Grocery »), ce qui vidait la209    # source sans erreur.210    flyer_name_filter: str | tuple[str, ...] = ""211    # Si non vide : ne garder que les items dont la catégorie déduite est dans212    # cet ensemble (ex. GROCERY_CATEGORIES pour les circulaires de pharmacie).213    keep_categories: frozenset[str] = frozenset()214215    # -- récupération -----------------------------------------------------------216    def _flyers(self) -> list[dict]:217        """Circulaires courantes de la bannière (résolution hebdo du flyer_id)."""218        data = self.get(LIST_URL.format(postal=self.postal_code),219                        headers={"Accept": "application/json"}).json()220        flyers = [f for f in (data.get("flyers") or [])221                  if f.get("merchant_id") == self.merchant_id]222        if self.flyer_name_filter:223            needles = ((self.flyer_name_filter,)224                       if isinstance(self.flyer_name_filter, str)225                       else tuple(self.flyer_name_filter))226            needles = tuple(n.lower() for n in needles)227            flyers = [f for f in flyers228                      if any(n in str(f.get("name") or "").lower()229                             for n in needles)]230        # Grandes bannières : Flipp publie souvent la semaine COURANTE et la231        # semaine À VENIR. On trie par valid_from croissant : en cas de slug232        # dupliqué entre les deux semaines, le prix de la semaine courante233        # gagne (le pipeline garde la première occurrence d'un uid).234        flyers.sort(key=lambda f: str(f.get("valid_from") or ""))235        return flyers236237    def fetch(self) -> list[Product]:238        products: list[Product] = []239        for flyer in self._flyers():240            data = self.get(FLYER_URL.format(flyer_id=flyer["id"]),241                            headers={"Accept": "application/json"}).json()242            for item in data.get("items") or []:243                prod = self._item_to_product(item, flyer)244                if prod is not None:245                    products.append(prod)246        return products247248    # -- extraction d'un item ----------------------------------------------------249    def _item_to_product(self, item: dict, flyer: dict) -> Product | None:250        price = self._price(item.get("price"))251        if price is None:      # vignette non-produit (« Scene offre ») ou multi-format252            return None253254        # nom bilingue « PÊCHES ONTARIO | ONTARIO PEACHES » -> FR + EN en mot-clé255        parts = [clean_text(p) for p in str(item.get("name") or "").split("|")]256        parts = [p for p in parts if p]257        if not parts:258            return None259        name_fr, keywords = parts[0], parts[1:]260261        brand = clean_text(item.get("brand") or "").replace(" | ", " / ")262        if brand and brand == brand.lower():     # Flipp met parfois tout en minuscules263            brand = brand.title()264265        size_m = _SIZE_IN_NAME.search(name_fr)266        flyer_name = clean_text(flyer.get("name") or "")267        default_cat = self.default_categories.get(flyer_name, "")268        external_id = self._slug(brand, name_fr, size_m.group(1) if size_m else "")269270        category = _categorize(name_fr, default_cat)271        # Filtre par rayon AVANT l'appel fiche item : les items écartés272        # (non alimentaires) ne coûtent aucune requête détail.273        if self.keep_categories and category not in self.keep_categories:274            return None275276        # fiche item Flipp (petit texte de la vignette, prix régulier, % de277        # rabais) — mise en cache par id d'item Flipp : l'id change quand la278        # circulaire change, donc un seul appel par item et par semaine.279        detail: dict = {}280        try:281            detail = self.detail(external_id, str(item.get("id") or ""),282                                 lambda: self._item_detail(item.get("id")))283        except Exception:      # la fiche est un bonus, jamais bloquante284            detail = {}285286        regular = self._price(detail.get("original_price"))287        if regular is not None and regular <= price:288            regular = None289290        return Product(291            source=self.source_id,292            external_id=external_id,293            url=self.flyer_page,294            name=name_fr,295            brand=brand,296            category=category,297            category_raw=flyer_name,298            size_label=size_m.group(1) if size_m else "",299            price=price,300            regular_price=regular,301            price_label=f"{item.get('price')} $",302            on_sale=True,                        # une circulaire = les spéciaux de la semaine303            keywords=keywords,304            details={k: v for k, v in {305                "flyer_id": flyer.get("id"),306                "flyer_name": flyer_name,307                "valid_from": item.get("valid_from") or flyer.get("valid_from"),308                "valid_to": item.get("valid_to") or flyer.get("valid_to"),309                "discount_pct": item.get("discount") or detail.get("percent_off"),310                "dollars_off": detail.get("dollars_off"),311                "fine_print": self._fine_print(item, detail) or None,312            }.items() if v is not None},313            images=[u.replace("http://", "https://")314                    for u in [item.get("cutout_image_url")] if u],315        )316317    def _item_detail(self, item_id) -> dict:318        """Fiche item Flipp (/flipp/items/{id}) réduite aux champs utiles.319320        C'est là que vivent le petit texte de la vignette (description,321        « +tx », limites/disclaimer) et le prix régulier (original_price).322        """323        if not item_id:324            return {}325        data = self.get(ITEM_URL.format(item_id=item_id),326                        headers={"Accept": "application/json"}).json()327        it = data.get("item") or data or {}328        keep = ("description", "price_text", "disclaimer_text", "sale_story",329                "original_price", "percent_off", "dollars_off")330        return {k: it.get(k) for k in keep if it.get(k) not in (None, "", [])}331332    @staticmethod333    def _fine_print(item: dict, detail: dict | None = None) -> str:334        """Petit texte de la vignette (limites, « +tx », « Sans carte… ») :335        text_areas de l'item + champs texte de la fiche /flipp/items/{id},336        dédupliqués, en une seule chaîne lisible."""337        bits: list[str] = []338        for ta in item.get("text_areas") or []:339            if isinstance(ta, str):340                bits.append(ta)341            elif isinstance(ta, dict):342                txt = ta.get("text") or ta.get("value") or ""343                if txt:344                    bits.append(str(txt))345        for src in (item, detail or {}):346            for key in ("description", "price_text", "disclaimer_text",347                        "sale_story", "pre_price_text", "post_price_text"):348                val = src.get(key)349                if val:350                    bits.append(str(val))351        cleaned = [clean_text(b) for b in bits]352        uniq = list(dict.fromkeys(b for b in cleaned if b))353        return " · ".join(uniq)[:300]354355    @staticmethod356    def _price(raw) -> float | None:357        """« 5.99 », « 0.3 », 5.99 -> float ; vide/0 -> None (jamais inventé)."""358        try:359            value = float(str(raw).strip().replace(",", "."))360        except (TypeError, ValueError):361            return None362        return value if 0 < value <= 2000 else None363364    @staticmethod365    def _slug(brand: str, name_fr: str, size: str) -> str:366        """Identifiant stable d'une semaine à l'autre (l'id d'item Flipp change) :367        le même produit garde le même uid et son historique price_log."""368        raw = strip_accents(f"{brand} {name_fr} {size}").lower()369        return _SLUG_RE.sub("-", raw).strip("-")[:80]370
Files main
Menu

Theme