Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Fabri·Ka9# File : fabrika/connectors/votresite.py10# Module : fabrika11# Repository : https://git.spboucher.ai/fabri-ka12# Created : 2026-08-2313# Last Modified : 2026-08-2814#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# Fabri-Ka — Agrégateur de produits québécois89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/votresite.py : connecteur Votresite.ca (plateforme québécoise).91# Les sites Votresite.ca sont des Drupal 8 gérés (thème owebo-votresite) avec92# une boutique OpenCart montée dans un sous-répertoire (/boutique/ ou93# /produits/, parfois autre). Rendu 100 % serveur, aucune API JSON :94# - inventaire : <mount>/sitemap.xml (extension OpenCart, pas toujours95# activée) sinon crawl des catégories <mount>/fr + pagination96# ?limit=100&page=N ;97# - fiche : URL …/<slug>-p<ID>[c<ID>…]/ — prix courant dans <h2>…$</h2>,98# prix barré (spécial) dans <span style="text-decoration: line-through">,99# « Disponibilité: » / « Modèle: » en <li>, description div#tab-description,100# galerie <a class="thumbnail">. Les meta twitter:data1/2 servent de101# secours mais affichent le prix RÉGULIER même en solde.102# Dédup par ID produit (le même p<ID> apparaît sous plusieurs chemins de103# catégorie, ex. -p361c37c45c44).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import concurrent.futures as cf108import re109from html import unescape110111from ..schema import Product, parse_price112from .base import BaseConnector113114# …/slug-p361/ ou …/slug-p361c37c45/ (produit) ; …/slug-c116c139/ (catégorie)115PROD_URL_RE = re.compile(r"/([^/]+)-p(\d+)(?:c\d+)*/?(?:\?.*)?$")116CAT_URL_RE = re.compile(r"-c\d+(?:c\d+)*/?$")117LOC_RE = re.compile(r"<loc>\s*(?:<!\[CDATA\[)?\s*(.*?)\s*(?:\]\]>)?\s*</loc>",118 re.I | re.S)119HREF_RE = re.compile(r'href="([^"]+)"')120SKIP_RE = re.compile(r"(/account|/cart|/checkout|/wishlist|/compare|/login|"121 r"/register|route=|mailto:|tel:|javascript:)", re.I)122123# marqueurs OpenCart d'une boutique Votresite valide124_OC_MARKERS = ("image/cache", "route=product", 'class="thumbnails"',125 "list-unstyled")126127CANDIDATE_MOUNTS = ["/boutique", "/produits"]128129130def _clean(s: str | None) -> str:131 return unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", s or ""))).strip()132133134def _enc(url: str) -> str:135 """Les chemins d'images OpenCart contiennent espaces et accents bruts."""136 return url.replace(" ", "%20")137138139class VotresiteConnector(BaseConnector):140 platform = "votresite"141 request_delay = 0.2142 max_products = 2000143 max_listing_pages = 250 # garde-fou du crawl catégories144145 # ------------------------------------------------------------------ mount146 def _try_mount(self, mount: str) -> bool:147 try:148 r = self.get(f"{self.base}{mount}/fr")149 except Exception:150 return False151 html = r.text or ""152 return (r.status_code == 200153 and any(m in html for m in _OC_MARKERS)154 and (PROD_URL_RE.search(html) is not None155 or re.search(r'-[pc]\d+[c\d]*/"', html) is not None156 or "-c" in html))157158 def _discover_mount(self) -> str:159 ep = (self.store.get("catalog_endpoint") or "").strip().rstrip("/")160 candidates: list[str] = []161 if ep and ep != "__generic__":162 candidates.append(ep if ep.startswith("/") else f"/{ep}")163 # page d'accueil Drupal : le lien vers la boutique révèle le montage164 try:165 html = self.get(self.base + "/").text166 for m in re.finditer(167 r'href="https?://[^"/]+(/[a-z0-9_-]+)(?:/fr)?/?"', html, re.I):168 p = m.group(1)169 if re.search(r"boutique|produit|magasin|commander|achat", p, re.I):170 candidates.append(p)171 for m in re.finditer(172 r'href="https?://[^"/]+(/[a-z0-9_-]+)/fr/[^"]*-[pc]\d', html):173 candidates.append(m.group(1))174 except Exception:175 pass176 candidates += CANDIDATE_MOUNTS177 seen: set[str] = set()178 for c in candidates:179 c = c.rstrip("/")180 if not c or c in seen:181 continue182 seen.add(c)183 if self._try_mount(c):184 return c185 raise RuntimeError("boutique Votresite (OpenCart) introuvable "186 f"(montages essayés : {sorted(seen)})")187188 # -------------------------------------------------------------- inventaire189 def _sitemap_urls(self, mount: str) -> dict[str, str]:190 """{pid: url produit} depuis <mount>/sitemap.xml (souvent absent)."""191 out: dict[str, str] = {}192 try:193 r = self.get(f"{self.base}{mount}/sitemap.xml")194 except Exception:195 return out196 xml = r.text or ""197 if r.status_code != 200 or "<urlset" not in xml:198 return out199 for loc in LOC_RE.findall(xml):200 m = PROD_URL_RE.search(loc)201 if m:202 out.setdefault(m.group(2), loc)203 return out204205 def _crawl_urls(self, mount: str) -> dict[str, str]:206 """Crawl des pages catégories : {pid: url produit}."""207 root = f"{self.base}{mount}"208 prods: dict[str, str] = {}209 seen: set[str] = set()210 queue: list[str] = [f"{root}/fr"]211 fetched = 0212 while queue and fetched < self.max_listing_pages:213 url = queue.pop(0)214 key = url.rstrip("/")215 if key in seen:216 continue217 seen.add(key)218 try:219 html = self.get(url).text or ""220 except Exception:221 continue222 fetched += 1223 for href in HREF_RE.findall(html):224 href = unescape(href).split("#")[0]225 if not href.startswith(root) or SKIP_RE.search(href):226 continue227 pm = PROD_URL_RE.search(href.split("?")[0])228 if pm:229 prods.setdefault(pm.group(2), href.split("?")[0])230 continue231 path = href.split("?")[0]232 if CAT_URL_RE.search(path):233 # 100 produits par page de liste (défaut : 15)234 if path.rstrip("/") + "/?limit=100" not in seen:235 queue.append(path.rstrip("/") + "/?limit=100")236 elif "page=" in href and "limit=" in href:237 queue.append(href) # pagination déjà paramétrée238 if len(prods) >= self.max_products:239 break240 return prods241242 # ------------------------------------------------------------------ fiche243 def _parse_product(self, pid: str, url: str, html: str) -> Product | None:244 # le 1er <h1> est souvent le logo du site (un lien) ; le titre du245 # produit est le dernier <h1> SANS ancre (ex. lemieldabee.ca)246 title, h1_pos = None, -1247 h1s = list(re.finditer(r"<h1[^>]*>(.*?)</h1>", html, re.S))248 plain = [m for m in h1s if "<a " not in m.group(1)]249 chosen = (plain or h1s)[-1] if h1s else None250 if chosen and plain:251 title, h1_pos = _clean(chosen.group(1)), chosen.start()252 if not title:253 m = re.search(r'<meta[^>]+property="og:title"[^>]+content="([^"]+)"',254 html)255 title = _clean(m.group(1)) if m else None256 if chosen:257 h1_pos = chosen.start()258 if not title:259 return None260261 # zone d'info produit : entre le <h1> et le formulaire d'achat262 if h1_pos < 0:263 h1_pos = 0264 zone_end = html.find('<div id="product"', h1_pos)265 zone = html[h1_pos: zone_end if zone_end > h1_pos else h1_pos + 6000]266267 compare = None268 m = re.search(r"line-through[^>]*>\s*([^<]*\d[^<]*)</", zone)269 if m:270 compare = parse_price(m.group(1))271 price = None272 m = re.search(r"<h2[^>]*>\s*([^<]*\d[^<]*\$[^<]*)</h2>", zone)273 if m:274 price = parse_price(m.group(1))275 if price is None: # secours : meta twitter (prix régulier)276 m = re.search(r'twitter:data1"\s+content="([^"]+)"', html)277 if m:278 price = parse_price(m.group(1))279 if compare is not None and price is not None and compare <= price:280 compare = None281282 available = None283 m = (re.search(r"Disponibilité\s*:\s*</?[^>]*>?\s*([^<]+)<", zone)284 or re.search(r'twitter:data2"\s+content="([^"]+)"', html))285 dispo = _clean(m.group(1)) if m else ""286 if dispo:287 low = dispo.lower()288 if "rupture" in low or "épuis" in low or "epuis" in low:289 available = False290 elif "stock" in low or "commande" in low or "jour" in low:291 available = True292293 det: dict = {}294 m = re.search(r"Modèle\s*:\s*([^<]+)<", zone)295 if m and _clean(m.group(1)):296 det["model"] = _clean(m.group(1))297 if dispo:298 det["availability_text"] = dispo299300 # options (listes déroulantes OpenCart)301 opts = []302 for sel in re.finditer(303 r'<label[^>]*control-label[^>]*>(.*?)</label>\s*<select[^>]*'304 r'name="option\[\d+\]"[^>]*>(.*?)</select>', html, re.S):305 name = _clean(sel.group(1))306 values = [_clean(v) for v in307 re.findall(r"<option[^>]*>(.*?)</option>", sel.group(2), re.S)]308 values = [v for v in values if v and "choisir" not in v.lower()]309 if name and values:310 opts.append({"name": name, "values": values[:30]})311 if opts:312 det["options"] = opts313314 # description : div#tab-description jusqu'au prochain onglet/bloc315 desc = ""316 start = html.find('id="tab-description"')317 if start != -1:318 start = html.find(">", start) + 1319 cuts = [html.find(marker, start) for marker in320 ('id="tab-', 'class="related', "<footer", "Produits apparentés")]321 cuts = [c for c in cuts if c > start]322 desc = html[start: min(cuts) if cuts else start + 20000]323 if not _clean(desc):324 m = (re.search(r'<meta[^>]+property="og:description"[^>]+content="([^"]+)"', html)325 or re.search(r'<meta[^>]+name="description"[^>]+content="([^"]+)"', html))326 desc = m.group(1) if m else ""327328 images: list[str] = []329 for m in re.finditer(r'<a[^>]+class="thumbnail"[^>]+href="([^"]+)"', html):330 u = _enc(unescape(m.group(1)))331 if u.startswith("http") and u not in images:332 images.append(u)333 m = re.search(r'<meta[^>]+property="og:image"[^>]+content="([^"]+)"', html)334 if m:335 u = _enc(unescape(m.group(1)))336 if u.startswith("http") and u not in images:337 images.append(u)338339 # catégories du fil d'Ariane (sans l'accueil ni le produit lui-même)340 cats: list[str] = []341 m = re.search(r'<ul class="breadcrumb"[^>]*>(.*?)</ul>', html, re.S)342 if m:343 entries = re.findall(r"<a[^>]*>(.*?)</a>", m.group(1), re.S)344 cats = [_clean(e) for e in entries345 if _clean(e) and "fa-home" not in e and _clean(e) != title]346347 return Product(348 store_id=self.store_id,349 external_id=pid,350 url=url,351 title=title,352 description=desc,353 price=price,354 price_max=price,355 compare_at_price=compare,356 images=images,357 product_type=cats[-1] if cats else "",358 tags=cats,359 available=available,360 details=det,361 )362363 # ------------------------------------------------------------------ fetch364 def fetch(self) -> list[Product]:365 mount = self._discover_mount()366 urls = self._sitemap_urls(mount)367 if len(urls) < 3: # sitemap absent ou quasi vide -> crawl368 crawled = self._crawl_urls(mount)369 for pid, u in crawled.items():370 urls.setdefault(pid, u)371 items = list(urls.items())[: self.max_products]372 out: list[Product] = []373374 def work(item: tuple[str, str]) -> Product | None:375 pid, u = item376 try:377 html = self.get(u).text or ""378 except Exception:379 return None380 if len(html) < 500:381 return None382 return self._parse_product(pid, u, html)383384 with cf.ThreadPoolExecutor(6) as ex:385 for rec in ex.map(work, items):386 if rec:387 out.append(rec)388 return out389