Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/_metro.py10# Module : foodka11# Repository : https://git.spboucher.ai/food-ka12# Created : 2026-08-1213# 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/_metro.py : socle commun Metro / Super C (même plateforme)91# Tuiles produit rendues côté serveur (data-product-code) mais site derrière92# un anti-bot agressif -> Scrapfly (ASP). Pagination : « <allée>-page-N ».93# -----------------------------------------------------------------------------94from __future__ import annotations9596import re9798from bs4 import BeautifulSoup99100from ..schema import Product, parse_price101from .base import BaseConnector102103_PER_KG_RE = re.compile(r"(\d+(?:,\d+)?)\s*\$\s*/\s*kg")104105# (slug d'allée, catégorie canonique)106AISLES = [107 ("fruits-et-legumes", "Fruits et légumes"),108 ("viandes-et-volailles", "Viandes et volailles"),109 ("poissons-et-fruits-de-mer", "Poissons et fruits de mer"),110 ("produits-laitiers-et-oeufs", "Produits laitiers et œufs"),111 ("pains-et-patisseries", "Boulangerie"),112 ("produits-surgeles", "Surgelés"),113 ("garde-manger", "Garde-manger"),114 ("boissons", "Boissons"),115 ("collations", "Collations et confiseries"),116]117118119class MetroPlatformConnector(BaseConnector):120 """Base Metro/Super C — sous-classes : définir source_id et domain."""121122 domain: str = "" # ex. "www.metro.ca"123 aisle_prefix: str = "/epicerie-en-ligne/allees" # superc : "/allees"124 pages_per_aisle: int = 2 # ~45 produits/page125 # Approfondissement ciblé : {slug d'allée: nb de pages} — les allées126 # absentes gardent pages_per_aisle (coût Scrapfly mesuré : 40-80127 # crédits/page ASP sans render_js).128 pages_override: dict[str, int] = {}129130 def _parse_tiles(self, html: str, category: str) -> list[Product]:131 soup = BeautifulSoup(html, "html.parser")132 products: list[Product] = []133 for tile in soup.select("[data-product-code]"):134 code = tile.get("data-product-code")135 name = tile.get("data-product-name") or ""136 if not code or not name:137 continue138 link_el = tile.select_one("a.product-details-link[href]")139 link = link_el["href"] if link_el else ""140 img_el = tile.select_one(".pt__visual img[src]")141 image = (img_el["src"] if img_el else "") or ""142 brand_el = tile.select_one(".head__brand")143 size_el = tile.select_one(".head__unit-details")144 price_el = tile.select_one(".price-update")145 before_el = tile.select_one(".pricing__before-price")146 unit_el = tile.select_one(".pricing__secondary-price")147 price_label = price_el.get_text(" ", strip=True) if price_el else ""148 unit_label = unit_el.get_text(" ", strip=True) if unit_el else ""149 before_txt = before_el.get_text(" ", strip=True) if before_el else ""150 price = None151 regular = parse_price(before_txt) if before_txt else None152 # Produit au poids : le prix affiché est une estimation à l'unité153 # mais le « prix régulier » est au kg — on compare tout au kg.154 if "kg" in before_txt:155 m_cur = _PER_KG_RE.search(unit_label)156 m_reg = _PER_KG_RE.search(before_txt)157 if m_cur:158 price = float(m_cur.group(1).replace(",", "."))159 price_label = f"{m_cur.group(1)} $ / kg"160 regular = (float(m_reg.group(1).replace(",", "."))161 if m_reg else None)162 else: # pas de prix au kg comparable : ne rien inventer163 regular = None164 on_sale = bool(tile.select_one(".pi-price-promo, .promo-price")) or regular is not None165 products.append(Product(166 source=self.source_id,167 external_id=str(code),168 url=(f"https://{self.domain}{link}" if link.startswith("/") else link),169 name=name,170 brand=brand_el.get_text(strip=True) if brand_el else "",171 category=category,172 category_raw=tile.get("data-product-category") or "",173 size_label=size_el.get_text(" ", strip=True) if size_el else "",174 price=price,175 price_label=price_label,176 regular_price=regular,177 on_sale=on_sale,178 unit_price_label=unit_label,179 images=[image] if image.startswith("http") else [],180 ))181 return products182183 def fetch(self) -> list[Product]:184 products: list[Product] = []185 seen: set[str] = set()186 for slug, category in AISLES:187 pages = self.pages_override.get(slug, self.pages_per_aisle)188 for page in range(1, pages + 1):189 suffix = slug if page == 1 else f"{slug}-page-{page}"190 url = f"https://{self.domain}{self.aisle_prefix}/{suffix}"191 try:192 html = self.get_scrapfly(url, must_contain="data-product-code")193 except Exception: # une allée qui casse ne bloque pas le reste194 break195 batch = self._parse_tiles(html, category)196 new = 0197 for prod in batch:198 if prod.uid not in seen:199 seen.add(prod.uid)200 products.append(prod)201 new += 1202 if new == 0: # page vide ou répétée : allée épuisée203 break204 return products205