Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/_resilient.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2213# Last Modified : 2026-08-2214#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# Groupe KA — connecteurs : chaîne de fetch anti-bot RÉSILIENTE (commune)89# Auteur : Simon-Pierre Boucher <contact@spboucher.ai>90# Fichier : connectors/_resilient.py91# -----------------------------------------------------------------------------92# But : rendre les connecteurs durables dans le temps. Quand un site jusque-là93# ouvert déploie un anti-bot (Cloudflare / Akamai / Incapsula / PerimeterX) ou94# renvoie 403/429/503, la requête directe N'ÉCHOUE PLUS silencieusement : elle95# ESCALADE automatiquement à travers une chaîne de secours :96#97# 1. Direct — la session du connecteur (curl_cffi impersonate si98# dispo, sinon requests) : rapide et gratuit.99# 2. Firecrawl — navigateur géré + proxy (FIRECRAWL_API_KEY) : premier100# recours dès qu'un site de gestionnaire bloque (2026-11-25).101# 3. Oxylabs (résid.) — proxy résidentiel Canada (-cc-CA) : IP propre.102# 4. Scrapfly (ASP) — bypass anti-bot géré + rendu JS optionnel.103# 5. Bright Data — Web Unlocker : déblocage premium, dernier recours.104#105# Le premier backend qui renvoie un 200 non vide gagne. Si TOUS échouent, on106# renvoie la dernière réponse (avec son code d'erreur) pour que le connecteur107# journalise l'échec comme avant — aucun changement de comportement en cas108# d'échec total, aucun blocage silencieux.109#110# Conception :111# - Aucun effet de bord à l'import ; toute brique non configurée est sautée.112# - Les clés sont lues de os.environ, avec repli sur le .env de l'app puis113# ~/.claude/.env, et acceptent les deux noms Scrapfly (SCRAPFLY_KEY /114# SCRAPFLY_API_KEY). => aucune modif de .env nécessaire.115# - `_ResilientResponse` imite requests.Response (.text/.content/.status_code/116# .url/.headers/.json()/.ok/.raise_for_status()) : les connecteurs existants117# continuent de fonctionner sans modification.118# - Coupe-circuit par hôte : après plusieurs escalades totalement infructueuses119# sur un même hôte, on saute l'escalade payante pendant un temps de repos120# (évite de brûler du quota Scrapfly/Bright Data sur une source morte).121# =============================================================================122from __future__ import annotations123124import json as _json125import os126import time127from pathlib import Path128from urllib.parse import quote, urlsplit129130import requests131132# -- curl_cffi est OPTIONNEL (meilleur fingerprint TLS s'il est présent) ------133try: # pragma: no cover134 from curl_cffi import requests as _cffi # type: ignore135 _HAS_CFFI = True136except Exception: # noqa: BLE001137 _cffi = None138 _HAS_CFFI = False139140# Codes HTTP typiques d'un blocage anti-bot (≠ 401/404/410/500 « métier » :141# 401 = auth manquante, 403/429 = bot bloqué, 5xx CF = challenge/edge).142BLOCK_STATUS = {403, 429, 503, 520, 521, 522, 523, 524, 526, 1020}143144# Marqueurs de page-challenge (Cloudflare/Akamai/Incapsula/PerimeterX/DataDome).145_CHALLENGE_MARKERS = (146 "just a moment", "cf-browser-verification", "cf-challenge",147 "attention required", "access denied", "request unsuccessful",148 "px-captcha", "perimeterx", "incapsula", "_incapsula_", "datadome",149 "captcha-delivery", "please enable javascript and cookies",150 "checking your browser", "ddos protection by",151)152153_UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "154 "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")155156# Coupe-circuit en mémoire : hôte -> (timestamp_jusquà, échecs_consécutifs)157_COOLDOWN: dict[str, tuple[float, int]] = {}158_COOLDOWN_HITS = 3 # nb d'échecs totaux avant repos159_COOLDOWN_SECONDS = 900.0 # 15 min de repos pour un hôte « mort »160161# -- chargement paresseux des secrets ----------------------------------------162_ENV_CACHE: dict[str, str] | None = None163164165def _load_env_files() -> dict[str, str]:166 """Parse les .env candidats une seule fois (repli si os.environ vide)."""167 global _ENV_CACHE168 if _ENV_CACHE is not None:169 return _ENV_CACHE170 out: dict[str, str] = {}171 candidates = []172 # .env de l'app (remonte quelques niveaux depuis ce module)173 here = Path(__file__).resolve()174 for up in range(2, 6):175 try:176 candidates.append(here.parents[up] / ".env")177 except IndexError:178 break179 candidates.append(Path.home() / ".claude" / ".env")180 for path in candidates:181 try:182 if not path.is_file():183 continue184 for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():185 line = line.strip()186 if not line or line.startswith("#") or "=" not in line:187 continue188 k, _, v = line.partition("=")189 k, v = k.strip(), v.strip().strip('"').strip("'")190 # ne pas écraser une valeur déjà trouvée (priorité app > global)191 if k and k not in out:192 out[k] = v193 except Exception: # noqa: BLE001194 continue195 _ENV_CACHE = out196 return out197198199def _secret(*names: str) -> str | None:200 """Cherche une clé dans os.environ puis dans les .env (par ordre de noms)."""201 for n in names:202 v = os.environ.get(n)203 if v:204 return v205 env = _load_env_files()206 for n in names:207 v = env.get(n)208 if v:209 return v210 return None211212213# -- réponse compatible requests.Response ------------------------------------214class _ResilientResponse:215 """Imite le minimum utile d'une requests.Response pour les connecteurs."""216217 def __init__(self, url: str, status_code: int, text: str,218 headers: dict | None = None, via: str = "direct") -> None:219 self.url = url220 self.status_code = int(status_code or 0)221 self._text = text or ""222 self.headers = headers or {}223 self.encoding = "utf-8"224 self.via = via # backend gagnant (diagnostic)225226 @property227 def text(self) -> str:228 return self._text229230 @property231 def content(self) -> bytes:232 return self._text.encode("utf-8", errors="ignore")233234 @property235 def ok(self) -> bool:236 return 200 <= self.status_code < 400237238 def json(self, **kw):239 return _json.loads(self._text)240241 def raise_for_status(self):242 if 400 <= self.status_code < 600:243 raise requests.HTTPError(244 f"{self.status_code} via {self.via} pour {self.url}",245 response=self) # type: ignore[arg-type]246 return None247248 def __repr__(self) -> str: # pragma: no cover249 return f"<_ResilientResponse [{self.status_code}] via {self.via}>"250251252# -- détection de blocage -----------------------------------------------------253def is_blocked(resp) -> bool:254 """True si la réponse ressemble à un blocage anti-bot (≠ erreur métier)."""255 if resp is None:256 return True257 code = getattr(resp, "status_code", 0) or 0258 if code in BLOCK_STATUS:259 return True260 # 200 mais page-challenge servie261 if code == 200:262 try:263 body = (resp.text or "")[:4000].lower()264 except Exception: # noqa: BLE001265 return False266 server = str(resp.headers.get("Server", "")).lower() if getattr(resp, "headers", None) else ""267 if any(m in body for m in _CHALLENGE_MARKERS):268 return True269 if "cloudflare" in server and ("captcha" in body or "challenge" in body):270 return True271 return False272273274def _host(url: str) -> str:275 try:276 return urlsplit(url).netloc.lower()277 except Exception: # noqa: BLE001278 return url279280281def _cooling(host: str) -> bool:282 until, _ = _COOLDOWN.get(host, (0.0, 0))283 return time.time() < until284285286def _note_failure(host: str) -> None:287 until, hits = _COOLDOWN.get(host, (0.0, 0))288 hits += 1289 if hits >= _COOLDOWN_HITS:290 _COOLDOWN[host] = (time.time() + _COOLDOWN_SECONDS, 0)291 else:292 _COOLDOWN[host] = (until, hits)293294295def _note_success(host: str) -> None:296 _COOLDOWN.pop(host, None)297298299# -- backends d'escalade ------------------------------------------------------300def _try_oxylabs(url: str, timeout: int, country: str,301 headers: dict | None) -> _ResilientResponse | None:302 endpoint = _secret("OXYLABS_PROXY") # pr.oxylabs.io:7777303 user = _secret("OXYLABS_PROXY_USER") # customer-... (sans -cc-XX)304 pwd = _secret("OXYLABS_PROXY_PASS")305 if not (endpoint and user and pwd):306 return None307 cc = (country or "ca").upper()308 puser = f"{user}-cc-{cc}"309 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"310 proxies = {"http": proxy, "https": proxy}311 hdrs = {"User-Agent": _UA}312 if headers:313 hdrs.update(headers)314 try:315 r = requests.get(url, proxies=proxies, headers=hdrs, timeout=timeout,316 verify=False) # noqa: S501 (proxy MITM du CA Oxylabs)317 return _ResilientResponse(url, r.status_code, r.text,318 dict(r.headers), via="oxylabs")319 except Exception: # noqa: BLE001320 return None321322323def _unwrap_pre(text: str) -> str:324 """Une réponse JSON/texte chargée dans un navigateur revient enrobée dans325 `<html>…<pre>…</pre></html>` : on restitue le corps d'origine."""326 import html as _html327 import re as _re328 m = _re.match(r"\s*<html[^>]*>\s*<head>.*?</head>\s*<body[^>]*>\s*<pre[^>]*>(.*)</pre>"329 r"\s*(?:<div[^>]*>\s*</div>\s*)*</body>\s*</html>\s*$",330 text, _re.S | _re.I)331 return _html.unescape(m.group(1)) if m else text332333334def _try_firecrawl(url: str, timeout: int, country: str, render_js: bool,335 headers: dict | None,336 wait_ms: int = 0) -> _ResilientResponse | None:337 """Firecrawl /v2/scrape : HTML brut (rawHtml) après chargement navigateur.338339 Premier recours payant quand un site de gestionnaire bloque la requête340 directe. `render_js` ajoute une attente pour les pages rendues côté client.341 Brique sautée si FIRECRAWL_API_KEY est absente.342 """343 key = _secret("FIRECRAWL_API_KEY")344 if not key:345 return None346 payload: dict = {"url": url, "formats": ["rawHtml"],347 "onlyMainContent": False,348 "location": {"country": (country or "ca").upper()},349 "timeout": int(max(timeout, 60) * 1000)}350 wait = wait_ms or (2500 if render_js else 0)351 if wait:352 payload["waitFor"] = int(wait)353 if headers:354 payload["headers"] = {str(k): str(v) for k, v in headers.items()}355 try:356 r = requests.post(357 "https://api.firecrawl.dev/v2/scrape",358 headers={"Authorization": f"Bearer {key}",359 "Content-Type": "application/json"},360 json=payload, timeout=max(timeout, 60) + 30)361 body = r.json() or {}362 if not body.get("success"):363 return None364 data = body.get("data") or {}365 meta = data.get("metadata") or {}366 return _ResilientResponse(367 meta.get("sourceURL") or url, meta.get("statusCode") or 0,368 _unwrap_pre(data.get("rawHtml") or ""), {}, via="firecrawl")369 except Exception: # noqa: BLE001370 return None371372373def _try_scrapfly(url: str, timeout: int, country: str, render_js: bool,374 headers: dict | None) -> _ResilientResponse | None:375 key = _secret("SCRAPFLY_KEY", "SCRAPFLY_API_KEY")376 if not key:377 return None378 params = {"key": key, "url": url, "country": country or "ca",379 "asp": "true", "proxy_pool": "public_residential_pool"}380 if render_js:381 params["render_js"] = "true"382 if headers:383 for k, v in headers.items():384 params[f"headers[{k}]"] = v385 try:386 r = requests.get("https://api.scrapfly.io/scrape", params=params,387 timeout=max(timeout, 180))388 result = (r.json() or {}).get("result") or {}389 return _ResilientResponse(390 url, result.get("status_code") or 0, result.get("content") or "",391 (result.get("response_headers") or {}), via="scrapfly")392 except Exception: # noqa: BLE001393 return None394395396def _try_brightdata(url: str, timeout: int,397 headers: dict | None) -> _ResilientResponse | None:398 key = _secret("BRIGHTDATA_API_KEY")399 zone = _secret("BRIGHTDATA_ZONE") or "web_unlocker1"400 if not key:401 return None402 try:403 r = requests.post(404 "https://api.brightdata.com/request",405 headers={"Authorization": f"Bearer {key}",406 "Content-Type": "application/json"},407 json={"zone": zone, "url": url, "format": "raw"},408 timeout=max(timeout, 120))409 return _ResilientResponse(url, r.status_code, r.text,410 dict(r.headers), via="brightdata")411 except Exception: # noqa: BLE001412 return None413414415# -- API publique -------------------------------------------------------------416def escalate(url: str, *, timeout: int = 30, country: str = "ca",417 render_js: bool = False, headers: dict | None = None,418 original=None):419 """Tente la chaîne de secours et renvoie la meilleure réponse.420421 Renvoie un `_ResilientResponse` 200 dès qu'un backend réussit ; sinon la422 dernière réponse tentée (ou `original`) pour préserver le comportement423 d'échec du connecteur. Respecte le coupe-circuit par hôte.424 """425 host = _host(url)426 if _cooling(host):427 return original # source au repos : on ne brûle pas de quota payant428429 last = original430 for backend in (431 lambda: _try_firecrawl(url, timeout, country, render_js, headers),432 lambda: _try_oxylabs(url, timeout, country, headers),433 lambda: _try_scrapfly(url, timeout, country, render_js, headers),434 lambda: _try_brightdata(url, timeout, headers),435 ):436 resp = backend()437 if resp is None:438 continue439 last = resp440 if resp.status_code == 200 and resp.text and not is_blocked(resp):441 _note_success(host)442 return resp443 time.sleep(0.4)444445 _note_failure(host)446 return last if last is not None else original447448449def escalate_if_blocked(resp, url: str, *, timeout: int = 30,450 country: str = "ca", render_js: bool = False,451 headers: dict | None = None):452 """Renvoie `resp` s'il est bon ; sinon lance l'escalade anti-bot."""453 if not is_blocked(resp):454 return resp455 better = escalate(url, timeout=timeout, country=country,456 render_js=render_js, headers=headers, original=resp)457 return better if better is not None else resp458