Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Fabri·Ka9# File : fabrika/connectors/scrapfly.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/scrapfly.py : transport de secours quand l'accès direct échoue91# (403/429/HTML au lieu de JSON). Depuis le 2026-11-26, l'escalade est92# Direct → Firecrawl → Scrapfly : `scrapfly_get` / `scrapfly_json` tentent93# d'abord Firecrawl (/v2/scrape, rawHtml, pays CA) quand — et seulement94# quand — l'hôte BLOQUE réellement la requête directe (voir95# `_resilient.host_blocks`), sous budget de crédits et coupe-circuit par96# hôte ; sinon, ou si Firecrawl ne rend rien d'exploitable, Scrapfly prend97# le relais comme avant. Chaque appel consomme des crédits : dernier recours.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import json102import os103import re104import threading105import time106107import requests108109API = "https://api.scrapfly.io/scrape"110_LOCK = threading.Lock()111_MIN_INTERVAL = 0.5112_last = [0.0]113114115def available() -> bool:116 """Un relais est-il configuré (Scrapfly ou Firecrawl) ?"""117 return bool(os.environ.get("SCRAPFLY_API_KEY")118 or os.environ.get("FIRECRAWL_API_KEY"))119120121def _firecrawl(url: str, *, render_js: bool = False, must_contain: str | None = None,122 accept=None) -> str | None:123 """Firecrawl en premier recours — uniquement si l'hôte bloque le direct.124125 Renvoie le corps exploitable, ou None (hôte non bloquant, budget épuisé,126 coupe-circuit ouvert, page vide ou refusée par `accept`)."""127 from . import _resilient128 if not _resilient._secret("FIRECRAWL_API_KEY"):129 return None130 if not _resilient.host_blocks(url):131 return None132 fc = _resilient.firecrawl_first(url, timeout=60, country="ca",133 render_js=render_js,134 must_contain=must_contain, accept=accept)135 return fc.text if fc is not None else None136137138def _scrape(url: str, *, method: str = "GET", data: str | None = None,139 headers: dict | None = None, render_js: bool = False,140 timeout: int = 150) -> tuple[int, str]:141 from . import _resilient142 key = os.environ.get("SCRAPFLY_API_KEY")143 if not key:144 why = _resilient.LAST_FIRECRAWL_ERROR.get(_resilient._host(url), "")145 raise RuntimeError("SCRAPFLY_API_KEY manquant (voir .env)"146 + (f" ; Firecrawl : {why}" if why else ""))147 _resilient.RELAY_STATS["scrapfly"] += 1148 with _LOCK:149 wait = _MIN_INTERVAL - (time.time() - _last[0])150 if wait > 0:151 time.sleep(wait)152 _last[0] = time.time()153 params = {"key": key, "url": url, "asp": "true", "country": "ca"}154 if render_js:155 params["render_js"] = "true"156 for k, v in (headers or {}).items():157 params[f"headers[{k.lower()}]"] = v158 try:159 r = requests.request(method, API, params=params, data=data, timeout=timeout)160 except requests.RequestException as exc:161 # l'exception cite l'URL complète, clé comprise : on la masque162 raise type(exc)(_resilient.redact(str(exc))) from None163 if r.status_code == 422:164 # certaines cibles restreignent les pays de proxy Scrapfly (ex.165 # boutiquesoha.com → us seulement) : l'erreur 422166 # ERR::SCRAPE::COUNTRY_NOT_AVAILABLE_FOR_TARGET liste les pays permis,167 # on réessaie avec le premier au lieu d'échouer.168 try:169 err = r.json().get("result", {}).get("error") or {}170 except ValueError:171 err = {}172 if err.get("code") == "ERR::SCRAPE::COUNTRY_NOT_AVAILABLE_FOR_TARGET":173 m = re.search(r"restricted to following countries:\s*([a-zA-Z, ]+)",174 err.get("message", ""))175 if m:176 params["country"] = m.group(1).split(",")[0].strip().lower()177 r = requests.request(method, API, params=params, data=data,178 timeout=timeout)179 if r.status_code >= 400:180 # jamais r.raise_for_status() : son message cite l'URL avec la clé181 raise requests.HTTPError(182 f"Scrapfly : HTTP {r.status_code} pour {url}", response=r)183 res = r.json().get("result", {})184 content = res.get("content") or ""185 # réponse volumineuse : Scrapfly renvoie un lien "large_object" à suivre186 if content.startswith("https://api.scrapfly.io/scrape/large_object/"):187 lo = requests.get(content, params={"key": key}, timeout=timeout)188 if lo.status_code >= 400:189 raise requests.HTTPError(190 f"Scrapfly (large_object) : HTTP {lo.status_code} pour {url}",191 response=lo)192 content = lo.text193 return int(res.get("status_code") or 0), content194195196def scrapfly_get(url: str, render_js: bool = False, timeout: int = 150) -> tuple[int, str]:197 """GET par relais : Firecrawl d'abord si l'hôte bloque, sinon Scrapfly.198 Retourne (status_code_amont, contenu)."""199 body = _firecrawl(url, render_js=render_js)200 if body is not None:201 return 200, body202 return _scrape(url, render_js=render_js, timeout=timeout)203204205def scrapfly_post(url: str, body: dict, headers: dict | None = None,206 timeout: int = 150) -> tuple[int, str]:207 """POST JSON via Scrapfly. Retourne (status_code_amont, contenu)."""208 hdrs = {"content-type": "application/json"}209 hdrs.update(headers or {})210 return _scrape(url, method="POST", data=json.dumps(body), headers=hdrs,211 timeout=timeout)212213214def _is_json(text: str) -> bool:215 try:216 json.loads(text)217 return True218 except ValueError:219 return False220221222def scrapfly_json(url: str, render_js: bool = False) -> dict | list:223 # contrôle contre les pages vides : le corps rendu doit être du JSON224 body = _firecrawl(url, render_js=render_js, accept=_is_json)225 if body is not None:226 return json.loads(body)227 status, content = _scrape(url, render_js=render_js)228 if status != 200:229 raise RuntimeError(f"scrapfly upstream {status} pour {url}")230 return json.loads(content)231