M2: extraction quality — fallback extractors, thin-content detection, result cache

- extractor: trafilatura (precision) -> trafilatura (recall) -> readability-lxml
  fallback chain; longest result wins; 'thin' flag below 200 chars
- orchestrator: Redis-backed scrape-result cache keyed by URL (cache hit skips
  render entirely); thin/empty results are never cached
- /health reports orchestrator Redis reachability

Verified: HN + synthetic thin/empty/boilerplate pages; cache hit path via fakeredis.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
User 2026-07-05 22:05:04 -07:00
parent e2b329b2bb
commit 56e7fa16dd
8 changed files with 156 additions and 32 deletions

View file

@ -1,37 +1,83 @@
"""Trafilatura-based extraction. M1: primary extractor only; M2 adds fallbacks."""
"""Mechanical extraction: Trafilatura primary, readability-lxml fallback.
No inference anywhere — deterministic library-based extraction only. A result
is "thin" when it's shorter than MIN_TEXT_CHARS; thin/empty primary output
triggers the fallback chain, and the longest result wins.
"""
import re
import trafilatura
from readability import Document
from lxml import html as lxml_html
MIN_TEXT_CHARS = 200
def _trafilatura_extract(html: str, url: str, favor_recall: bool) -> str:
return (
trafilatura.extract(
html,
url=url,
include_tables=True,
include_links=False,
include_comments=False,
favor_recall=favor_recall,
)
or ""
)
def _readability_extract(html: str) -> str:
try:
doc = Document(html)
tree = lxml_html.fromstring(doc.summary())
text = tree.text_content()
# Collapse the whitespace soup text_content() produces.
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n\s*\n\s*", "\n\n", text)
return text.strip()
except Exception:
return ""
def _metadata(html: str, url: str) -> tuple[str | None, dict]:
meta = trafilatura.extract_metadata(html, default_url=url)
if meta is None:
return None, {}
fields = {
k: v
for k, v in {
"author": meta.author,
"date": meta.date,
"sitename": meta.sitename,
"description": meta.description,
}.items()
if v
}
return meta.title, fields
def extract_content(html: str, url: str) -> dict:
text = trafilatura.extract(
html,
url=url,
include_tables=True,
include_links=False,
include_comments=False,
favor_recall=False,
)
meta = trafilatura.extract_metadata(html, default_url=url)
candidates = [
("trafilatura", lambda: _trafilatura_extract(html, url, favor_recall=False)),
("trafilatura_recall", lambda: _trafilatura_extract(html, url, favor_recall=True)),
("readability", lambda: _readability_extract(html)),
]
metadata = {}
title = None
if meta is not None:
title = meta.title
metadata = {
k: v
for k, v in {
"author": meta.author,
"date": meta.date,
"sitename": meta.sitename,
"description": meta.description,
}.items()
if v
}
best_name, best_text = "none", ""
for name, fn in candidates:
text = fn()
if len(text) > len(best_text):
best_name, best_text = name, text
if len(best_text) >= MIN_TEXT_CHARS and name == "trafilatura":
break # primary extractor produced substantial content; done
title, metadata = _metadata(html, url)
return {
"title": title,
"text": text or "",
"text": best_text,
"metadata": metadata,
"extractor_used": "trafilatura" if text else "none",
"extractor_used": best_name if best_text else "none",
"thin": len(best_text) < MIN_TEXT_CHARS,
}

View file

@ -1,3 +1,5 @@
fastapi>=0.115
uvicorn[standard]>=0.32
trafilatura>=1.12
readability-lxml>=0.8
lxml>=5.0

View file

@ -0,0 +1,46 @@
"""Redis-backed result cache; degrades to no-op when Redis is unavailable."""
import json
import logging
import redis.asyncio as aioredis
log = logging.getLogger("orchestrator")
class Cache:
def __init__(self, redis_url: str | None):
self._redis = None
if redis_url:
self._redis = aioredis.from_url(redis_url, socket_timeout=2, socket_connect_timeout=2)
else:
log.warning("no REDIS_URL configured; orchestrator result cache disabled")
async def get_json(self, key: str) -> dict | None:
if not self._redis:
return None
try:
raw = await self._redis.get(key)
return json.loads(raw) if raw else None
except Exception:
return None
async def set_json(self, key: str, value: dict, ttl: int) -> None:
if not self._redis:
return
try:
await self._redis.set(key, json.dumps(value), ex=ttl)
except Exception:
pass
async def is_ready(self) -> bool:
if not self._redis:
return False
try:
return await self._redis.ping()
except Exception:
return False
async def close(self) -> None:
if self._redis:
await self._redis.aclose()

View file

@ -5,3 +5,6 @@ EXTRACTOR_URL = os.environ.get("EXTRACTOR_URL", "http://localhost:8003")
SEARCHER_URL = os.environ.get("SEARCHER_URL", "http://localhost:8001")
STAGE_TIMEOUT_S = float(os.environ.get("STAGE_TIMEOUT_S", "60"))
REDIS_URL = os.environ.get("REDIS_URL", "")
EXTRACT_CACHE_TTL = int(os.environ.get("EXTRACT_CACHE_TTL", "3600"))

View file

@ -7,6 +7,7 @@ from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from . import config, pipeline
from .cache import Cache
from .logging_setup import setup
log = setup()
@ -15,7 +16,9 @@ log = setup()
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.client = httpx.AsyncClient()
app.state.cache = Cache(config.REDIS_URL)
yield
await app.state.cache.close()
await app.state.client.aclose()
@ -38,7 +41,12 @@ async def health() -> dict:
except httpx.HTTPError:
services[name] = {"status": "unreachable"}
overall = "ok" if all(s.get("status") == "ok" for s in services.values()) else "degraded"
return {"status": overall, "service": "orchestrator", "services": services}
return {
"status": overall,
"service": "orchestrator",
"redis": await app.state.cache.is_ready(),
"services": services,
}
@app.post("/scrape")
@ -46,7 +54,7 @@ async def scrape(req: ScrapeRequest) -> dict:
if not req.url.startswith(("http://", "https://")):
raise HTTPException(status_code=400, detail="url must be http(s)")
try:
result = await pipeline.scrape_url(app.state.client, req.url)
result = await pipeline.scrape_url(app.state.client, req.url, app.state.cache)
except pipeline.StageError as exc:
log.error("scrape failed at %s: %s", exc.stage, exc.detail)
raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc

View file

@ -6,6 +6,7 @@ from typing import Any
import httpx
from . import config
from .cache import Cache
class Trace:
@ -68,12 +69,23 @@ async def extract(client: httpx.AsyncClient, html: str, url: str, trace: Trace)
return result
async def scrape_url(client: httpx.AsyncClient, url: str) -> dict:
"""render -> extract for one URL. Raises StageError on hard failure."""
async def scrape_url(client: httpx.AsyncClient, url: str, cache: Cache | None = None) -> dict:
"""render -> extract for one URL. Raises StageError on hard failure.
The extracted result is cached by URL; a hit skips render entirely.
"""
trace = Trace()
cache_key = f"scrape:{url}"
if cache:
start = time.monotonic()
cached = await cache.get_json(cache_key)
if cached:
trace.record("scrape_cache", (time.monotonic() - start) * 1000, cache="hit")
return {**cached, "trace": trace.as_dict()}
rendered = await render(client, url, trace)
extracted = await extract(client, rendered["html"], rendered.get("final_url") or url, trace)
return {
result = {
"url": url,
"final_url": rendered.get("final_url"),
"status": rendered.get("status"),
@ -81,5 +93,8 @@ async def scrape_url(client: httpx.AsyncClient, url: str) -> dict:
"content": extracted.get("text", ""),
"metadata": extracted.get("metadata", {}),
"extractor_used": extracted.get("extractor_used"),
"trace": trace.as_dict(),
"thin": extracted.get("thin", False),
}
if cache and result["content"] and not result["thin"]:
await cache.set_json(cache_key, result, config.EXTRACT_CACHE_TTL)
return {**result, "trace": trace.as_dict()}

View file

@ -2,3 +2,4 @@ fastapi>=0.115
uvicorn[standard]>=0.32
httpx>=0.27
mcp>=1.2
redis>=5.0