Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/tau.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 Marché Tau (marchestau.com — supermarchés santé)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# k-eCommerce : les grilles de catégories sont chargées en AJAX (aucun prix91# dans le HTML), mais les FICHES produit sont rendues côté serveur92# (« 16,99$ CAD », fil d'Ariane, marque, image). Stratégie : sitemap93# kSitemap-1.xml (~14 000 URLs), filtrage des slugs produit (suffixe de94# format « -227gr »), échantillon réparti sur tout le catalogue, puis une95# requête par fiche (throttling de BaseConnector).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from bs4 import BeautifulSoup102103from ..schema import Product, normalize_category, parse_price104from .base import BaseConnector105106BASE = "https://marchestau.com"107SITEMAP = f"{BASE}/kSitemap-1.xml"108109_LOC_RE = re.compile(r"<loc>([^<]+)</loc>")110# slug produit : se termine par un format, ex. « -227gr », « -1.36l », « -60un »111_SLUG_SIZE_RE = re.compile(112 r"-(\d+(?:[.,]\d+)?)\s*(gr|g|kg|ml|l|lb|oz|un)$", re.IGNORECASE)113_CODE_RE = re.compile(r"(\d{6,})")114115116class TauConnector(BaseConnector):117 source_id = "tau"118119 max_products: int = 180 # une requête par fiche : rester raisonnable120121 def _product_urls(self) -> list[str]:122 """URLs de fiches produit, échantillonnées uniformément (tout l'alphabet)."""123 xml = self.get(SITEMAP).text124 urls = [u for u in _LOC_RE.findall(xml)125 if _SLUG_SIZE_RE.search(u.rsplit("/", 1)[-1])]126 if len(urls) <= self.max_products:127 return urls128 step = len(urls) / self.max_products129 return [urls[int(i * step)] for i in range(self.max_products)]130131 def _parse_product(self, html: str, url: str) -> Product | None:132 soup = BeautifulSoup(html, "html.parser")133 h1 = soup.select_one(".product-detail h1") or soup.select_one("h1")134 if h1 is None:135 return None136 name = h1.get_text(" ", strip=True)137 if not name:138 return None139140 code_el = soup.select_one(".product-details-code")141 code = ""142 if code_el is not None:143 m = _CODE_RE.search(code_el.get_text())144 code = m.group(1) if m else ""145 slug = url.rstrip("/").rsplit("/", 1)[-1]146 external_id = code or slug147148 # prix courant + prix régulier barré (solde)149 price_el = soup.select_one(".price-current")150 regular_el = soup.select_one(151 ".price-regular, .price-before, .single-price-display del, "152 ".single-price-display s")153 unit_el = soup.select_one(".price-per-unit small")154155 # fil d'Ariane : Accueil > Catalogue > <cat> > <sous-cat> > <produit>156 crumbs = [li.get_text(" ", strip=True)157 for li in soup.select("ul.breadcrumb li a")]158 crumbs = [c for c in crumbs159 if c and c not in ("Page d'accueil", "Catalogue")]160 category_raw = " / ".join(crumbs)161162 brand_el = soup.select_one(".product-brand a")163 img = soup.select_one("#product-detail-gallery-main-img[src]")164 image = str(img["src"]) if img else ""165166 # format depuis le slug : « mures-noires-227gr » -> « 227 g »167 size_label = ""168 m = _SLUG_SIZE_RE.search(slug)169 if m:170 unit = m.group(2).lower()171 size_label = f"{m.group(1)} {'g' if unit == 'gr' else unit}"172173 desc_el = soup.select_one(".product-details-desc")174 return Product(175 source=self.source_id,176 external_id=external_id,177 url=url,178 name=name,179 brand=brand_el.get_text(" ", strip=True) if brand_el else "",180 category=normalize_category(category_raw),181 category_raw=category_raw,182 size_label=size_label,183 price_label=price_el.get_text(" ", strip=True) if price_el else "",184 regular_price=(parse_price(regular_el.get_text(" ", strip=True))185 if regular_el else None),186 on_sale=regular_el is not None,187 unit_price_label=unit_el.get_text(" ", strip=True) if unit_el else "",188 description=desc_el.get_text(" ", strip=True) if desc_el else "",189 images=[image] if image.startswith("http") else [],190 )191192 def fetch(self) -> list[Product]:193 products: list[Product] = []194 seen: set[str] = set()195 for url in self._product_urls():196 try:197 html = self.get(url).text198 except Exception: # une fiche qui casse ne bloque pas le reste199 continue200 prod = self._parse_product(html, url)201 if prod is not None and prod.uid not in seen:202 seen.add(prod.uid)203 products.append(prod)204 return products205