IMBA v2: 3-ступенчатый fetch, 7 адаптеров, sqlite+FTS5, simhash-дедуп, self-growth discover
This commit is contained in:
+159
@@ -0,0 +1,159 @@
|
||||
"""Fetch-лестница: httpx -> curl_cffi(TLS-фингер) -> прокси -> firecrawl.
|
||||
|
||||
Возвращает FetchResult с полем mode, чтобы в базе было видно, какая ступень сработала.
|
||||
Каждый хост получает свой троттлинг: без него борды отдают 429 и всё выглядит мёртвым.
|
||||
"""
|
||||
import json, os, random, threading, time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
try:
|
||||
from curl_cffi import requests as crequests
|
||||
except Exception: # pragma: no cover
|
||||
crequests = None
|
||||
|
||||
from . import config
|
||||
|
||||
CF_MARK = ("just a moment", "cf-browser-verification", "attention required", "ddos-guard", "checking your browser")
|
||||
|
||||
|
||||
@dataclass
|
||||
class FetchResult:
|
||||
url: str
|
||||
status: int = 0
|
||||
text: str = ""
|
||||
mode: str = "http"
|
||||
elapsed: float = 0.0
|
||||
error: str = ""
|
||||
headers: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return self.status == 200 and len(self.text) > 200
|
||||
|
||||
@property
|
||||
def blocked(self) -> bool:
|
||||
low = self.text[:4000].lower()
|
||||
return self.status in (403, 429, 503) or any(m in low for m in CF_MARK)
|
||||
|
||||
|
||||
class _HostGate:
|
||||
"""Троттлинг по хосту: последний заход + минимальный интервал."""
|
||||
|
||||
def __init__(self, delay: float):
|
||||
self.delay = delay
|
||||
self._lock = threading.Lock()
|
||||
self._last: dict[str, float] = {}
|
||||
|
||||
def wait(self, host: str):
|
||||
with self._lock:
|
||||
prev = self._last.get(host, 0.0)
|
||||
now = time.monotonic()
|
||||
gap = self.delay - (now - prev)
|
||||
if gap > 0:
|
||||
time.sleep(gap + random.uniform(0, 0.15))
|
||||
self._last[host] = time.monotonic()
|
||||
|
||||
|
||||
_GATE: Optional[_HostGate] = None
|
||||
_PROXY_I = 0
|
||||
_PROXY_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _gate(delay: float) -> _HostGate:
|
||||
global _GATE
|
||||
if _GATE is None or _GATE.delay != delay:
|
||||
_GATE = _HostGate(delay)
|
||||
return _GATE
|
||||
|
||||
|
||||
def _pick_proxy(s) -> Optional[str]:
|
||||
global _PROXY_I
|
||||
pool = list(s.get("proxies") or [])
|
||||
if s.get("proxy_mode") == "env":
|
||||
env = os.environ.get("IMBA_PROXIES", "")
|
||||
pool = [p.strip() for p in env.split(",") if p.strip()]
|
||||
if not pool:
|
||||
return None
|
||||
with _PROXY_LOCK:
|
||||
p = pool[_PROXY_I % len(pool)]
|
||||
_PROXY_I += 1
|
||||
return p
|
||||
|
||||
|
||||
def _via_httpx(url, s, proxy=None) -> FetchResult:
|
||||
t0 = time.monotonic()
|
||||
kw = {"timeout": s["timeout"], "follow_redirects": True}
|
||||
if proxy:
|
||||
kw["proxy"] = proxy
|
||||
try:
|
||||
with httpx.Client(**kw, headers={"User-Agent": s["ua"], "Accept-Language": "en-US,en;q=0.9,ru;q=0.8"}) as c:
|
||||
r = c.get(url)
|
||||
body = r.text[: s["max_bytes"]]
|
||||
return FetchResult(url, r.status_code, body, "http" + ("+proxy" if proxy else ""),
|
||||
time.monotonic() - t0, headers=dict(r.headers))
|
||||
except Exception as e:
|
||||
return FetchResult(url, 0, "", "http", time.monotonic() - t0, error=f"{type(e).__name__}: {e}"[:200])
|
||||
|
||||
|
||||
def _via_cffi(url, s, proxy=None) -> FetchResult:
|
||||
if crequests is None:
|
||||
return FetchResult(url, 0, "", "cffi", 0.0, error="curl_cffi нет")
|
||||
t0 = time.monotonic()
|
||||
kw = {"timeout": s["timeout"], "impersonate": "chrome", "allow_redirects": True,
|
||||
"headers": {"Accept-Language": "en-US,en;q=0.9"}}
|
||||
if proxy:
|
||||
kw["proxies"] = {"http": proxy, "https": proxy}
|
||||
try:
|
||||
r = crequests.get(url, **kw)
|
||||
return FetchResult(url, r.status_code, (r.text or "")[: s["max_bytes"]], "cffi" + ("+proxy" if proxy else ""),
|
||||
time.monotonic() - t0, headers=dict(r.headers))
|
||||
except Exception as e:
|
||||
return FetchResult(url, 0, "", "cffi", time.monotonic() - t0, error=f"{type(e).__name__}: {e}"[:200])
|
||||
|
||||
|
||||
def _via_firecrawl(url, s) -> FetchResult:
|
||||
key = os.environ.get("FIRECRAWL_API_KEY", "")
|
||||
if not key:
|
||||
return FetchResult(url, 0, "", "firecrawl", 0.0, error="нет FIRECRAWL_API_KEY")
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
r = httpx.post("https://api.firecrawl.dev/v2/scrape",
|
||||
json={"url": url, "formats": ["markdown"], "onlyMainContent": False},
|
||||
headers={"Authorization": f"Bearer {key}"}, timeout=90)
|
||||
d = r.json()
|
||||
body = ((d.get("data") or {}).get("markdown") or "")[: s["max_bytes"]]
|
||||
return FetchResult(url, 200 if body else r.status_code, body, "firecrawl", time.monotonic() - t0)
|
||||
except Exception as e:
|
||||
return FetchResult(url, 0, "", "firecrawl", time.monotonic() - t0, error=f"{type(e).__name__}: {e}"[:200])
|
||||
|
||||
|
||||
def fetch(url: str, s=None, ladder=True) -> FetchResult:
|
||||
"""Основная точка входа. ladder=True включает эскалацию."""
|
||||
s = s or config.settings()
|
||||
host = urlparse(url).netloc
|
||||
_gate(float(s["per_host_delay"])).wait(host)
|
||||
|
||||
res = _via_httpx(url, s)
|
||||
if res.ok:
|
||||
return res
|
||||
if not ladder:
|
||||
return res
|
||||
|
||||
proxied = _pick_proxy(s)
|
||||
res2 = _via_cffi(url, s, proxy=proxied)
|
||||
if res2.ok:
|
||||
return res2
|
||||
if proxied is None:
|
||||
res3 = _via_cffi(url, s, proxy=_pick_proxy(s))
|
||||
if res3.ok:
|
||||
return res3
|
||||
if s.get("firecrawl"):
|
||||
res4 = _via_firecrawl(url, s)
|
||||
if res4.ok:
|
||||
return res4
|
||||
# возвращаем лучшую из попыток (по объёму тела)
|
||||
return max([res, res2], key=lambda r: (r.status == 200, len(r.text)))
|
||||
Reference in New Issue
Block a user