Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/iga.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 IGA (Sobeys Québec — plateforme Voilà, voila.ca)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# iga.net délègue l'épicerie en ligne à voila.ca. Deux voies :91# 1. (principale) API REST publique des promotions — JSON complet avec prix,92# prix promo, format et catégorie, pagination par curseur, sans anti-bot.93# 2. (complément, optionnelle) recherche de la SPA rendue via Scrapfly94# (render_js) pour les produits hors promotion.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import re99100from bs4 import BeautifulSoup101102from ..schema import Product, normalize_category, parse_price103from .base import BaseConnector104105PLP_URL = "https://voila.ca/api/product-listing-pages/v1/pages/promotions"106# regionId public observé (région de livraison Québec) — requis par l'API107REGION_ID = "dd7143ad-a16a-4c1d-8dee-e3c7e48dc511"108109# (terme de recherche, catégorie canonique) — voie complémentaire (rendu JS)110SEARCHES = [111 ("fruits", "Fruits et légumes"),112 ("viande", "Viandes et volailles"),113 ("fromage", "Charcuteries et fromages"),114 ("pain", "Boulangerie"),115 ("surgele", "Surgelés"),116]117118_ID_RE = re.compile(r"/([0-9]+[A-Z]{2})/?$")119_SIZE_IN_TITLE = re.compile(120 r"(\d+(?:[.,]\d+)?\s*(?:kg|g|ml|l|lb|oz|un))\b", re.IGNORECASE)121122123class IgaConnector(BaseConnector):124 source_id = "iga"125 request_delay = 1.0126 max_api_pages = 12 # 50 produits/page (promotions en cours)127 use_search = False # recherches Scrapfly complémentaires (coûteux)128129 # -- voie 1 : API REST des promotions --------------------------------------130 def _fetch_promotions(self) -> list[Product]:131 products: list[Product] = []132 token: str | None = None133 for _ in range(self.max_api_pages):134 params = {"regionId": REGION_ID, "maxPageSize": 50,135 "maxProductsToDecorate": 50}136 if token:137 params["pageToken"] = token138 data = self.get(PLP_URL, params=params,139 headers={"Accept": "application/json",140 "Accept-Language": "fr-CA,fr;q=0.9"}).json()141 decorated = list(data.get("decoratedProducts") or [])142 for group in data.get("productGroups") or []:143 decorated.extend(group.get("decoratedProducts") or [])144 for p in decorated:145 rid = p.get("retailerProductId")146 name = p.get("name") or ""147 if not rid or not name:148 continue149 price = (p.get("price") or {}).get("amount")150 promo = (p.get("promoPrice") or {}).get("amount")151 current, regular = (promo, price) if promo else (price, None)152 image = p.get("image") or {}153 srcset = image.get("bopSrcset") or ""154 img_url = srcset.split(" ")[0] if srcset else ""155 cat_path = p.get("categoryPath") or []156 unit = ((p.get("unitPrice") or {}).get("price") or {}).get("amount")157 products.append(Product(158 source=self.source_id,159 external_id=str(rid),160 url=f"https://voila.ca/products/{rid}",161 name=name,162 brand=p.get("brand") or "",163 category=normalize_category(cat_path[0] if cat_path else ""),164 category_raw=" / ".join(cat_path),165 size_label=p.get("packSizeDescription") or "",166 price=float(current) if current else None,167 regular_price=float(regular) if regular else None,168 on_sale=promo is not None,169 in_stock=p.get("available"),170 keywords=[a.get("label") for a in p.get("iconAttributes") or []171 if isinstance(a, dict) and a.get("label")],172 images=[img_url] if img_url.startswith("http") else [],173 ))174 token = (data.get("metadata") or {}).get("nextPageToken")175 if not token or not decorated:176 break177 return products178179 # -- voie 2 : recherche SPA rendue (complément) -----------------------------180 def _parse_search(self, html: str, category: str, term: str) -> list[Product]:181 soup = BeautifulSoup(html, "html.parser")182 products: list[Product] = []183 for link in soup.select('[data-test="fop-product-link"][href]'):184 href = link["href"]185 m = _ID_RE.search(href)186 if not m:187 continue188 tile = link189 for _ in range(6):190 if tile.parent is None:191 break192 tile = tile.parent193 if tile.select_one('[data-test="fop-price"]'):194 break195 title_el = tile.select_one('[data-test="fop-title"]') or link196 price_el = tile.select_one('[data-test="fop-price"]')197 orig_el = tile.select_one('[data-test="fop-original-price"]')198 unit_el = tile.select_one('[data-test="fop-price-per-unit"]')199 img = tile.select_one("img[src]")200 name = title_el.get_text(" ", strip=True)201 if not name:202 continue203 size_m = _SIZE_IN_TITLE.search(name)204 regular = parse_price(orig_el.get_text(" ", strip=True)) if orig_el else None205 products.append(Product(206 source=self.source_id,207 external_id=m.group(1),208 url=f"https://voila.ca{href}" if href.startswith("/") else href,209 name=name,210 category=category,211 category_raw=term,212 size_label=size_m.group(1) if size_m else "",213 price=parse_price(price_el.get_text(" ", strip=True)) if price_el else None,214 regular_price=regular,215 on_sale=regular is not None,216 unit_price_label=(unit_el.get_text(" ", strip=True).strip("()")217 if unit_el else ""),218 images=([img["src"]] if img is not None219 and str(img.get("src", "")).startswith("http") else []),220 ))221 return products222223 def fetch(self) -> list[Product]:224 products = self._fetch_promotions()225 seen = {p.uid for p in products}226 if self.use_search:227 for term, category in SEARCHES:228 url = f"https://voila.ca/products?q={term.replace(' ', '+')}"229 try:230 html = self.get_scrapfly(231 url, render_js=True,232 headers={"Accept-Language": "fr-CA,fr;q=0.9"},233 wait_for_selector='[data-test="fop-product-link"]',234 must_contain="fop-product-link",235 accept=lambda h, c=category, t=term: bool(self._parse_search(h, c, t)))236 except Exception:237 continue238 for prod in self._parse_search(html, category, term):239 if prod.uid not in seen:240 seen.add(prod.uid)241 products.append(prod)242 return products243