SPB Git

Repository Public

aubut.py 7.8 KB 199 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/aubut.py10# Module           : foodka11# Repository       : https://git.spboucher.ai/food-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1214#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 — connecteur Aubut (aubut.ca — grossiste cash & carry, Montréal)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Site maison (Vue.js) : les grilles de catégories (/produits/<cat>?p=N,91# 32 tuiles/page) embarquent un composant <app-product-ecommerce> dont92# l'attribut :product contient TOUT le produit en JSON (prix, format, solde,93# inventaire, image) — parsing trivial et fiable.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import json9899from bs4 import BeautifulSoup100101from ..schema import Product102from .base import BaseConnector103104BASE = "https://www.aubut.ca"105106# (slug de catégorie, catégorie canonique)107CATEGORIES = [108    ("fruits-et-legumes-9", "Fruits et légumes"),109    ("viandes-poissons-frais-8", "Viandes et volailles"),110    ("charcuteries-7", "Charcuteries et fromages"),111    ("produits-laitiers-6", "Produits laitiers et œufs"),112    ("boulangerie-5", "Boulangerie"),113    ("surgele-4", "Surgelés"),114    ("epicerie-1", "Garde-manger"),115    ("boissons-2", "Boissons"),116]117118119def _price(value) -> float | None:120    """« 31.99 » (chaîne du JSON Aubut) -> float, None si vide/zéro."""121    try:122        price = float(value)123    except (TypeError, ValueError):124        return None125    return price if price > 0 else None126127128class AubutConnector(BaseConnector):129    source_id = "aubut"130131    max_categories: int | None = None    # borne pour les tests132    pages_per_category: int = 2          # 32 tuiles/page -> ~512 produits max133134    def _parse_tiles(self, html: str, category: str, slug: str) -> list[Product]:135        soup = BeautifulSoup(html, "html.parser")136        products: list[Product] = []137        for tag in soup.select("app-product-ecommerce[\\:product]"):138            try:139                data = json.loads(tag[":product"])140            except (ValueError, KeyError):141                continue142            name = (data.get("title") or "").strip()143            pid = str(data.get("product_id") or data.get("id") or "")144            if not name or not pid:145                continue146147            # prix « unité » ; *_special > 0 = prix en solde148            regular = _price(data.get("unite_price"))149            special = _price(data.get("unite_price_special"))150            price = special if special is not None else regular151            if special is None:152                regular = None      # pas de solde -> pas de prix régulier distinct153154            image = data.get("picture_thumb_path") or ""155            in_stock = None156            if str(data.get("has_inventaire") or "") in ("0", "1"):157                in_stock = data.get("has_inventaire") == "1"158159            products.append(Product(160                source=self.source_id,161                external_id=pid,162                url=data.get("detail") or f"{BASE}/produits/details/{data.get('slug', '')}-{pid}",163                name=name,164                brand=(data.get("brand_title") or "").strip(),165                category=category,166                category_raw=slug,167                size_label=(data.get("unite_format") or "").strip(),168                price=price,169                regular_price=regular,170                on_sale=special is not None,171                unit_price_label=(data.get("price_100") or "").strip(),172                in_stock=in_stock,173                images=[image] if image.startswith("http") else [],174            ))175        return products176177    def fetch(self) -> list[Product]:178        products: list[Product] = []179        seen: set[str] = set()180        categories = CATEGORIES[: self.max_categories]181        for slug, category in categories:182            for page in range(1, self.pages_per_category + 1):183                url = f"{BASE}/produits/{slug}"184                if page > 1:185                    url += f"?p={page}"186                try:187                    html = self.get(url).text188                except Exception:   # une page qui casse ne bloque pas le reste189                    break190                new = 0191                for prod in self._parse_tiles(html, category, slug):192                    if prod.uid not in seen:193                        seen.add(prod.uid)194                        products.append(prod)195                        new += 1196                if new == 0:        # page vide ou répétée : catégorie épuisée197                    break198        return products199
Files main
Menu

Theme