SPB Git

Repository Public

base.py 10.7 KB 259 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Fabri·Ka9# File             : fabrika/connectors/base.py10# Module           : fabrika11# Repository       : https://git.spboucher.ai/fabri-ka12# Created          : 2026-08-1213# 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/base.py : connecteur générique par plateforme ecommerce.91#   Fabri-Ka utilise 1 connecteur / PLATEFORME : le même code Shopify sert des centaines92#   de boutiques, piloté par le registre data/stores.json.93# -----------------------------------------------------------------------------94from __future__ import annotations9596import os97import time9899import requests100101from ..schema import Product102103USER_AGENT = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "104              "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36 "105              "FabriKaBot/1.0 (+https://www.fabri-ka.com/bot; contact@spboucher.ai)")106107FIRECRAWL_API = "https://api.firecrawl.dev/v2/scrape"108109110class BaseConnector:111    """Connecteur de plateforme : instancié avec la fiche registre d'une boutique."""112113    platform: str = ""114    request_delay: float = 0.5115    timeout: int = 30116    max_pages: int = 200          # garde-fou (200 pages x 250 = 50 000 produits)117118    def __init__(self, store: dict) -> None:119        self.store = store120        self.store_id = store["id"]121        self.base = (store.get("url") or f"https://{store['id']}").rstrip("/")122        # dépassement par boutique (clé "timeout" du registre) : sites lents,123        # ex. canadel.com dont la Store API met ~50 s par page de 100 produits124        try:125            if store.get("timeout"):126                self.timeout = int(store["timeout"])127        except (TypeError, ValueError):128            pass129        self.session = requests.Session()130        self.session.headers["User-Agent"] = USER_AGENT131        self.session.headers["Accept-Language"] = "fr-CA,fr;q=0.9,en;q=0.8"132        self._last = 0.0133134    def get(self, url: str, **kw) -> requests.Response:135        wait = self.request_delay - (time.time() - self._last)136        if wait > 0:137            time.sleep(wait)138        resp = self.session.get(url, timeout=self.timeout, **kw)139        self._last = time.time()140        resp.raise_for_status()141        return resp142143    def get_rendered(self, url: str, wait_ms: int = 0,144                     proxy: str | None = None) -> str:145        """HTML rendu (JavaScript exécuté) via Firecrawl v2 — sites SPA/anti-bot.146147        `proxy="stealth"` franchit les challenges anti-bot (jusqu'à 5 crédits).148        Lève une exception si Firecrawl échoue (clé absente, budget épuisé,149        quota, erreur d'API) : jamais de chaîne vide silencieuse, sinon la150        boutique tomberait à zéro sans échec consigné."""151        from . import _resilient152        key = _resilient._secret("FIRECRAWL_API_KEY")153        if not key:154            raise RuntimeError("FIRECRAWL_API_KEY manquant (voir .env)")155        host = _resilient._host(url)156        if not _resilient._fc_budget_ok(host):157            raise RuntimeError(_resilient.LAST_FIRECRAWL_ERROR.get(158                host, "budget Firecrawl épuisé") + f" — {url}")159        payload: dict = {"url": url, "formats": ["html", "rawHtml"],160                         "onlyMainContent": False,161                         "location": {"country": "CA"}, "timeout": 90000}162        if wait_ms:163            payload["waitFor"] = wait_ms164        if proxy:165            payload["proxy"] = proxy166        resp = requests.post(167            FIRECRAWL_API,168            json=payload,169            headers={"Authorization": f"Bearer {key}"},170            timeout=150,171        )172        try:173            body = resp.json() or {}174        except ValueError:175            body = {}176        if not body.get("success"):177            raise RuntimeError(_resilient.redact(178                f"Firecrawl : HTTP {resp.status_code} — "179                f"{str(body.get('error') or resp.text)[:200]} — {url}"))180        data = body.get("data") or {}181        meta = data.get("metadata") or {}182        try:183            credits = max(1, int(meta.get("creditsUsed") or 1))184        except (TypeError, ValueError):185            credits = 1186        _resilient._fc_spend(host, credits)187        return data.get("html") or _resilient._unwrap_pre(data.get("rawHtml") or "")188189    def fetch(self) -> list[Product]:   # pragma: no cover - interface190        raise NotImplementedError191192193# =============================================================================194# Résilience anti-bot — auto-escalade de get() sans toucher au corps.195# Enrobe BaseConnector.get pour qu'un blocage196# anti-bot (403/429/503/challenge) ou une coupure réseau déclenche la chaîne197# de secours (Firecrawl -> Oxylabs résidentiel -> Scrapfly ASP -> Bright Data). Voir198# connectors/_resilient.py. Idempotent (marqueur _RESILIENT_WRAPPED).199# =============================================================================200if not getattr(BaseConnector, "_RESILIENT_WRAPPED", False):201    import requests as _res_requests  # noqa: E402202    from . import _resilient as _res  # noqa: E402203204    _res_orig_get = BaseConnector.get205206    def _res_full_url(url, kw):207        try:208            return _res_requests.Request("GET", url,209                                        params=kw.get("params")).prepare().url210        except Exception:  # noqa: BLE001211            return url212213    def _res_resilient_get(self, url, **kw):214        timeout = getattr(self, "timeout", 30)215        headers = kw.get("headers")216        try:217            return _res_orig_get(self, url, **kw)218        except _res_requests.HTTPError as exc:219            r = getattr(exc, "response", None)220            if r is not None and _res.is_blocked(r):221                target = getattr(r, "url", None) or _res_full_url(url, kw)222                better = _res.escalate_if_blocked(223                    r, target, timeout=timeout, headers=headers)224                if better is not None and getattr(better, "status_code", 0) == 200:225                    return better226            raise227        except (_res_requests.ConnectionError, _res_requests.Timeout):228            better = _res.escalate(_res_full_url(url, kw),229                                   timeout=timeout, headers=headers)230            if better is not None and getattr(better, "status_code", 0) == 200:231                return better232            raise233234    def _res_get_resilient(self, url, *, render_js=False, country="ca", **kw):235        """Fetch anti-bot explicite : force la chaîne de secours au besoin.236237        Comme get() mais tente d'abord le direct puis escalade même sur 200-238        challenge, avec rendu JS optionnel. Renvoie une réponse compatible239        requests (.text/.content/.status_code/.json()...).240        """241        timeout = getattr(self, "timeout", 30)242        headers = kw.get("headers")243        try:244            resp = _res_orig_get(self, url, **kw)245        except _res_requests.HTTPError as exc:246            resp = getattr(exc, "response", None)247        except (_res_requests.ConnectionError, _res_requests.Timeout):248            resp = None249        target = _res_full_url(url, kw)250        if resp is not None and getattr(resp, "url", None):251            target = resp.url252        return _res.escalate_if_blocked(resp, target, timeout=timeout,253                                        country=country, render_js=render_js,254                                        headers=headers)255256    BaseConnector.get = _res_resilient_get257    BaseConnector.get_resilient = _res_get_resilient258    BaseConnector._RESILIENT_WRAPPED = True259
Files main
Menu

Theme