Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/euro_marche.py10# Module : foodka11# Repository : https://git.spboucher.ai/food-ka12# Created : 2026-08-1613# Last Modified : 2026-09-1714#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 Euro Marché (épiceries européennes/méditerranéennes, Montréal)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Historique : circulaire hebdo sur Flipp (merchant 3300) jusqu'au 2026-09-16.91# Depuis, la bannière auto-héberge sa circulaire en scans PNG sur euromarche.ca92# (flyer_fr.php, images/1..N.png) — plus aucune circulaire sur backflipp (vérifié93# aux 4 codes postaux des magasins ; le merchant 3300 existe encore au registre94# Flipp, d'où la stratégie hybride : Flipp d'abord, scans en repli).95# Repli scans : extraction vision (API Anthropic, clé résolue comme _resilient),96# 1 appel par page et par semaine grâce au cache détail (clé = hash de l'image).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import base64101import hashlib102import json103import re104105from ..schema import Product, clean_text106from ._flipp import FlippConnector, _categorize107from ._resilient import _secret108109_FLYER_FR = "https://euromarche.ca/flyer_fr.php"110_PAGE_RE = re.compile(r'src="(images/\d+\.png)"')111_ANTHROPIC_API = "https://api.anthropic.com/v1/messages"112_VISION_MODEL = "claude-sonnet-4-6"113114_VISION_PROMPT = (115 "Voici une page de la circulaire hebdomadaire d'une épicerie québécoise. "116 "Extrais CHAQUE produit qui a un prix visible. Réponds UNIQUEMENT avec un "117 "tableau JSON, sans texte autour. Un objet par produit :\n"118 '{"name_fr": "nom en français", "name_en": "nom anglais ou \'\'", '119 '"brand": "marque si imprimée sinon \'\'", '120 '"size": "format imprimé (ex. 1 KG, 3 L, 800 GR) ou \'\'", '121 '"price": prix unitaire effectif en dollars (nombre ; 79¢ -> 0.79 ; '122 '"2/5.00$" -> 2.5), '123 "\"price_text\": \"texte du prix tel qu'imprimé (ex. 12.99 CH/EA, 99¢/lb)\", "124 '"unit": "ch|lb|kg|\'\'"}\n'125 "N'invente rien : si un prix est illisible, omets le produit."126)127128129class EuroMarcheConnector(FlippConnector):130 source_id = "euro_marche"131 merchant_id = 3300132 flyer_page = _FLYER_FR133134 def fetch(self) -> list[Product]:135 # 1. Flipp (source structurée historique) — si la bannière y revient,136 # le connecteur reprend seul le chemin préféré.137 products = super().fetch()138 if products:139 return products140 # 2. Repli : scans PNG auto-hébergés de la circulaire courante.141 return self._fetch_site_scans()142143 # -- repli : scans de la circulaire sur euromarche.ca -------------------------144 def _fetch_site_scans(self) -> list[Product]:145 html = self.get(_FLYER_FR).text146 pages = sorted(set(_PAGE_RE.findall(html)),147 key=lambda p: int(re.sub(r"\D", "", p)))148 products: list[Product] = []149 for idx, page in enumerate(pages, start=1):150 img = self.get(f"https://euromarche.ca/{page}").content151 page_key = hashlib.sha256(img).hexdigest()[:16]152 # cache hebdo : l'appel vision ne part que si le scan a changé153 payload = self.detail(f"__scan_p{idx}", page_key,154 lambda img=img: {"items": self._vision_extract(img)})155 for item in payload.get("items") or []:156 prod = self._scan_item_to_product(item, idx)157 if prod is not None:158 products.append(prod)159 return products160161 def _scan_item_to_product(self, item: dict, page: int) -> Product | None:162 price = self._price(item.get("price"))163 name_fr = clean_text(str(item.get("name_fr") or ""))164 if price is None or not name_fr:165 return None166 brand = clean_text(str(item.get("brand") or ""))167 if brand and brand == brand.lower():168 brand = brand.title()169 size = clean_text(str(item.get("size") or ""))170 name_en = clean_text(str(item.get("name_en") or ""))171 unit = clean_text(str(item.get("unit") or ""))172 price_label = clean_text(str(item.get("price_text") or "")) or f"{price} $"173 return Product(174 source=self.source_id,175 external_id=self._slug(brand, name_fr, size),176 url=self.flyer_page,177 name=name_fr,178 brand=brand,179 category=_categorize(name_fr, ""),180 category_raw="Circulaire (scan)",181 size_label=size,182 price=price,183 price_label=price_label,184 on_sale=True, # une circulaire = les spéciaux de la semaine185 keywords=[name_en] if name_en else [],186 details={k: v for k, v in {187 "scan_page": page,188 "price_unit": unit or None,189 }.items() if v is not None},190 )191192 # -- extraction vision d'une page de scan -------------------------------------193 def _vision_extract(self, img: bytes) -> list[dict]:194 key = _secret("ANTHROPIC_API_KEY")195 if not key:196 raise RuntimeError("ANTHROPIC_API_KEY manquant (os.environ, .env, ~/.claude/.env)")197 resp = self.session.post(198 _ANTHROPIC_API,199 headers={"x-api-key": key, "anthropic-version": "2023-06-01",200 "content-type": "application/json"},201 json={202 "model": _VISION_MODEL,203 "max_tokens": 8000,204 "temperature": 0,205 "messages": [{"role": "user", "content": [206 {"type": "image",207 "source": {"type": "base64", "media_type": "image/png",208 "data": base64.b64encode(img).decode()}},209 {"type": "text", "text": _VISION_PROMPT},210 ]}],211 },212 timeout=300,213 )214 resp.raise_for_status()215 text = "".join(b.get("text") or "" for b in resp.json().get("content") or [])216 text = re.sub(r"^```(?:json)?|```$", "", text.strip(), flags=re.M).strip()217 try:218 items = json.loads(text)219 except json.JSONDecodeError:220 start, end = text.find("["), text.rfind("]")221 if start < 0 or end <= start:222 raise223 items = json.loads(text[start:end + 1])224 return [it for it in items if isinstance(it, dict)]225