SPB Git

Repository Public

generic.py 19.5 KB 440 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Fabri·Ka9# File             : fabrika/connectors/generic.py10# Module           : fabrika11# Repository       : https://git.spboucher.ai/fabri-ka12# Created          : 2026-08-1213# Last Modified    : 2026-11-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# Fabri-Ka — Agrégateur de produits québécois89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/generic.py : connecteur universel par sitemap + extraction du91#   balisage produit rendu côté serveur (JSON-LD schema.org Product, microdata,92#   Open Graph product, blobs PrestaShop/Magento). Couvre PrestaShop, Magento,93#   BigCommerce, WordPress non-Woo et sites ecommerce sur mesure. Scrapfly en94#   secours pour l'anti-bot. Rendu client-only (Ecwid) non couvert ; Square95#   Online est couvert par connectors/square.py (vague 2).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import concurrent.futures as cf100import json101import re102from html import unescape103from urllib.parse import urlparse104105from ..schema import Product, parse_price106from .base import BaseConnector107108PRODUCT_URL_RE = re.compile(109    r"(/produits?/|/product/|/products/|/boutique/|/shop/|/store/|/p/|/item/"110    r"|/\d+-[a-z0-9]|/achat/|/produit-|-p\d+\.html|\.html$)", re.I)111NON_PRODUCT_RE = re.compile(112    r"(/blog|/blogue|/category|/categorie|/tag/|/page/|/compte|/account|/cart|"113    r"/panier|/checkout|/contact|/a-propos|/about|/cms|/content/|/faq|/policies|"114    r"/politique|sitemap|\.(?:jpg|png|pdf|css|js)$)", re.I)115LOC_RE = re.compile(r"<loc>\s*(?:<!\[CDATA\[)?\s*(.*?)\s*(?:\]\]>)?\s*</loc>", re.I | re.S)116IP_HOST_RE = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}(?::\d+)?$")117118119def _clean(s):120    return unescape(re.sub(r"<[^>]+>", " ", re.sub(r"\s+", " ", s or ""))).strip()121122123def _walk_jsonld(node, out):124    if isinstance(node, list):125        for x in node:126            _walk_jsonld(x, out)127    elif isinstance(node, dict):128        t = node.get("@type")129        types = t if isinstance(t, list) else [t]130        if any(str(x).endswith("Product") for x in types if x):131            out.append(node)132        for v in node.values():133            if isinstance(v, (list, dict)):134                _walk_jsonld(v, out)135136137def _jsonld_images(img) -> list[str]:138    """Normalise le champ image JSON-LD (str | dict | liste mixte) en URLs."""139    out: list[str] = []140    items = img if isinstance(img, list) else [img]141    for x in items:142        if isinstance(x, dict):143            x = x.get("url") or x.get("contentUrl")144        if isinstance(x, str) and x.startswith("http") and x not in out:145            out.append(x)146    return out[:10]147148149def extract_product(url, html, visible_price=False, price_optional=False):150    """Retourne un dict {title, price, price_max, image, images, description,151    currency, available, brand, sku, gtin, rating, review_count} ou None."""152    title = price = price_max = image = desc = None153    brand = sku = gtin = rating = review_count = None154    images: list[str] = []155    currency = "CAD"156    available = None157158    # 1) JSON-LD Product159    for block in re.findall(r'<script[^>]*type="application/ld\+json"[^>]*>(.*?)</script>',160                            html, re.S | re.I):161        try:162            data = json.loads(block.strip())163        except Exception:164            continue165        prods = []166        _walk_jsonld(data, prods)167        for p in prods:168            if not isinstance(p, dict):169                continue170            offers = p.get("offers") or {}171            if isinstance(offers, list):172                offers = next((o for o in offers if isinstance(o, dict)), {})173            if not isinstance(offers, dict):174                offers = {}175            spec = offers.get("priceSpecification") or {}176            if isinstance(spec, list):177                spec = next((s for s in spec if isinstance(s, dict)), {})178            if not isinstance(spec, dict):179                spec = {}180            pr = parse_price(offers.get("price") or offers.get("lowPrice")181                             or spec.get("price"))182            if pr:183                title = title or _clean(p.get("name"))184                price = price or pr185                price_max = price_max or parse_price(offers.get("highPrice"))186                currency = offers.get("priceCurrency") or currency187                if not images:188                    images = _jsonld_images(p.get("image"))189                image = image or (images[0] if images else None)190                desc = desc or _clean(p.get("description"))191                av = str(offers.get("availability") or "")192                available = ("InStock" in av) if av else available193                b = p.get("brand")194                if isinstance(b, dict):195                    b = b.get("name")196                if isinstance(b, str) and b.strip():197                    brand = brand or _clean(b)198                if p.get("sku"):199                    sku = sku or str(p["sku"])[:80]200                for gk in ("gtin13", "gtin", "gtin12", "gtin8", "mpn"):201                    if p.get(gk):202                        gtin = gtin or str(p[gk])[:40]203                        break204                ar = p.get("aggregateRating") or {}205                if isinstance(ar, dict) and ar.get("ratingValue"):206                    try:207                        rating = rating or float(ar["ratingValue"])208                        rc = ar.get("reviewCount") or ar.get("ratingCount")209                        if rc:210                            review_count = review_count or int(float(rc))211                    except (TypeError, ValueError):212                        pass213214    # 2) Open Graph product / meta215    if not price:216        m = re.search(r'<meta[^>]+(?:og:price:amount|product:price:amount)"[^>]*content="([^"]+)"', html, re.I) \217            or re.search(r'<meta[^>]+content="([^"]+)"[^>]*(?:og:price:amount|product:price:amount)"', html, re.I)218        if m:219            price = parse_price(m.group(1))220    # 3) microdata itemprop=price221    if not price:222        m = re.search(r'itemprop="price"[^>]*content="([^"]+)"', html, re.I) \223            or re.search(r'content="([^"]+)"[^>]*itemprop="price"', html, re.I)224        if m:225            price = parse_price(m.group(1))226    # 4) prix visible du thème — OPT-IN par fiche registre (visible_price_fallback),227    # jamais global : ex. bbqquebec.com (export statique Shopify→Vercel 2026-10-23,228    # JSON-LD Product présent mais offers:null, aucun OG/microdata price; le prix229    # ne survit que dans le markup du thème: class="price__current" / data-prix).230    if not price and visible_price:231        m = re.search(r'class="price__current"[^>]*>\s*([^<]{1,40})<', html, re.I) \232            or re.search(r'data-prix="([^"]{1,40})"', html, re.I)233        if m:234            price = parse_price(m.group(1))235    if not title:236        m = re.search(r'<meta[^>]+property="og:title"[^>]*content="([^"]+)"', html, re.I)237        title = _clean(m.group(1)) if m else None238        if not title:239            m = re.search(r"<title[^>]*>(.*?)</title>", html, re.S | re.I)240            title = _clean(m.group(1)) if m else None241    if not image:242        m = re.search(r'<meta[^>]+property="og:image"[^>]*content="([^"]+)"', html, re.I) \243            or re.search(r'<meta[^>]+content="([^"]+)"[^>]*property="og:image"', html, re.I)244        image = m.group(1) if m else None245        if image and image not in images:246            images.insert(0, image)247    if not desc:248        m = re.search(r'<meta[^>]+(?:name|property)="(?:description|og:description)"[^>]*content="([^"]+)"', html, re.I)249        desc = _clean(m.group(1)) if m else None250    if not brand:251        m = re.search(r'<meta[^>]+property="(?:og:brand|product:brand)"[^>]*content="([^"]+)"', html, re.I)252        brand = _clean(m.group(1)) if m else None253254    # prix facultatif — OPT-IN par fiche registre (price_optional), jamais255    # global : ex. verbois.com (fabricant qui vend via détaillants, catalogue256    # Woo historique de ~500 fiches TOUTES sans prix → price_on_request=1 au257    # finalize; la Store API, masquée par un plugin type WP Hide en 2026-11,258    # livrait déjà ces fiches sans prix). Sans l'opt-in, exiger un prix reste259    # le garde-fou qui évite d'ingérer des pages non marchandes.260    if not title or (not price and not price_optional):261        return None262    return {"title": title, "price": price, "price_max": price_max,263            "image": image, "images": images or ([image] if image else []),264            "description": desc, "currency": currency, "available": available,265            "brand": brand, "sku": sku, "gtin": gtin,266            "rating": rating, "review_count": review_count}267268269class GenericConnector(BaseConnector):270    platform = "generic"271    request_delay = 0.2272    max_products = 800273    use_scrapfly = True      # False pendant la détection (vitesse)274275    def _rehost(self, u):276        # certains CMS mal configurés (ex. boreale.com, Craft CMS, 2026-09-08)277        # émettent des <loc> sur l'IP brute du serveur → cert TLS invalide.278        # On ramène ces URLs sur le domaine de la boutique, qui sert les279        # mêmes chemins (sitemaps enfants et pages produit vérifiés 200).280        # Variante 2026-09-22 (boreale.com encore) : <loc> émis sur un domaine281        # parasite (sitemaps.instead.beer) — « sitemap » dans l'hôte faisait en282        # plus exclure chaque URL produit via NON_PRODUCT_RE. Réécriture OPT-IN283        # par fiche registre (rehost_hosts), jamais globale : d'autres boutiques284        # génériques pointent légitimement vers un domaine tiers (CDN, miroir).285        p = urlparse(u)286        bad_hosts = {h.lower() for h in (self.store.get("rehost_hosts") or [])}287        if IP_HOST_RE.match(p.netloc) or p.netloc.lower() in bad_hosts:288            return f"{self.base}{p.path}" + (f"?{p.query}" if p.query else "")289        return u290291    def _sitemap_products(self):292        from . import scrapfly293        seen, out = set(), []294        roots = [f"{self.base}/sitemap.xml", f"{self.base}/sitemap_index.xml",295                 f"{self.base}/wp-sitemap.xml", f"{self.base}/1_fr_0_sitemap.xml",296                 f"{self.base}/sitemap/sitemap-index.xml", f"{self.base}/media/sitemap.xml",297                 f"{self.base}/pub/media/sitemap.xml", f"{self.base}/sitemap1.xml",298                 f"{self.base}/en/sitemap.xml", f"{self.base}/fr/sitemap.xml"]299        # sitemaps produit hors des emplacements standards (ex. jcperreault.com,300        # 2026-10-16 : produits retirés de /sitemap.xml, désormais uniquement301        # dans /media/feeds/sitemap_products_fr.xml déclaré via robots.txt).302        # Clé fiche OPT-IN sitemap_roots (URL absolue ou chemin), prioritaire —303        # jamais de lecture globale de robots.txt pour ne pas perturber les304        # autres boutiques génériques.305        extra = [u if u.startswith("http") else f"{self.base}{u}"306                 for u in (self.store.get("sitemap_roots") or [])]307        roots = extra + roots308        # URLs produit sous des préfixes propres au site, invisibles pour309        # PRODUCT_URL_RE (ex. donjjewellery.com, refonte Woo → Medusa headless310        # 2026-10 : produits sous /engagement-rings/…, /womens/…, /mens/…).311        # Inclusion OPT-IN par fiche registre (product_url_prefixes), jamais312        # globale — miroir de skip_url_prefixes.313        incl = tuple(self.store.get("product_url_prefixes") or [])314        queue, depth_left = list(roots), 3315        fetched_roots = 0316        while queue and fetched_roots < 60:317            u = queue.pop(0)318            if u in seen:319                continue320            seen.add(u)321            try:322                r = self.session.get(u, timeout=self.timeout)323                xml = r.text if r.status_code == 200 else ""324            except Exception:325                xml = ""326            if not xml and self.use_scrapfly and scrapfly.available() and u == roots[0]:327                try:328                    _, xml = scrapfly.scrapfly_get(u)329                except Exception:330                    xml = ""331            if not xml:332                continue333            fetched_roots += 1334            locs = [self._rehost(l.strip()) for l in LOC_RE.findall(xml)]335            child_maps = [l for l in locs if l.endswith(".xml") or "sitemap" in l.lower()]336            if child_maps and depth_left > 0:337                queue = child_maps + queue338                depth_left -= 0339            for l in locs:340                if l.endswith(".xml"):341                    continue342                if (PRODUCT_URL_RE.search(l)343                        or (incl and urlparse(l).path.startswith(incl))) \344                        and not NON_PRODUCT_RE.search(l):345                    out.append(l)346            if len(out) >= self.max_products * 2:347                break348        # sites bilingues (ex. maisondherbes.com, refonte Next.js fr/en) : le349        # sitemap liste chaque produit en double sous un préfixe de langue350        # (/en/…). Exclusion OPT-IN par fiche registre (skip_url_prefixes),351        # jamais globale : d'autres boutiques génériques ont leur catalogue352        # légitimement sous /en/ (ex. pierresdailleurs.ca, 771 produits).353        skip = tuple(self.store.get("skip_url_prefixes") or [])354        if skip:355            out = [u for u in out if not urlparse(u).path.startswith(skip)]356        # dédup en gardant l'ordre357        return list(dict.fromkeys(out))[: self.max_products]358359    def _fetch_html(self, url):360        from . import scrapfly361        try:362            r = self.session.get(url, timeout=self.timeout)363            if r.status_code == 200:364                # sans charset dans Content-Type, requests décode en latin-1365                # (mojibake sur les pages UTF-8, ex. rudimenterre.com Hydrogen)366                if "charset" not in (r.headers.get("content-type") or "").lower():367                    r.encoding = r.apparent_encoding or "utf-8"368                if len(r.text) > 500:369                    return r.text370        except Exception:371            pass372        if self.use_scrapfly and scrapfly.available():373            try:374                st, content = scrapfly.scrapfly_get(url)375                if st == 200:376                    return content377            except Exception:378                pass379        return ""380381    def fetch(self) -> list[Product]:382        urls = self._sitemap_products()383        if not urls:384            return []385        out: list[Product] = []386        base_host = urlparse(self.base).netloc.lower().replace("www.", "")387        visible_price = bool(self.store.get("visible_price_fallback"))388        price_optional = bool(self.store.get("price_optional"))389390        def work(u):391            html = self._fetch_html(u)392            if not html:393                return None394            info = extract_product(u, html, visible_price=visible_price,395                                   price_optional=price_optional)396            if not info:397                return None398            det: dict = {}399            if info.get("sku"):400                det["sku"] = info["sku"]401            if info.get("gtin"):402                det["gtin"] = info["gtin"]403            if info.get("rating"):404                det["average_rating"] = info["rating"]405            if info.get("review_count"):406                det["review_count"] = info["review_count"]407            return Product(408                store_id=self.store_id,409                external_id=u.rstrip("/").split("/")[-1][:80] or u,410                url=u, title=info["title"], description=info.get("description") or "",411                price=info["price"],412                price_max=info.get("price_max") or info["price"],413                currency=info.get("currency") or "CAD",414                images=info.get("images") or ([info["image"]] if info.get("image") else []),415                vendor=info.get("brand") or "",416                available=info.get("available"),417                details=det)418419        with cf.ThreadPoolExecutor(6) as ex:420            for rec in ex.map(work, urls):421                if rec:422                    out.append(rec)423        return out424425426def probe_generic(domain, session, sample=6):427    """Teste si une boutique est récoltable en générique. Retourne (ok, n_urls, n_hits)."""428    store = {"id": domain, "url": f"https://{domain}"}429    conn = GenericConnector(store)430    conn.session = session431    urls = conn._sitemap_products()432    if not urls:433        return False, 0, 0434    hits = 0435    for u in urls[:sample]:436        html = conn._fetch_html(u)437        if html and extract_product(u, html):438            hits += 1439    return (hits >= max(2, sample // 2)), len(urls), hits440
Files main
Menu

Theme