DR-256-backup / tools /fetch_corpus.py
Shangy's picture
Add files using upload-large-folder tool
42bebde verified
Raw History Blame Contribute Delete
56.2 kB
#!/usr/bin/env python3
"""Fetch a checkpointed, zero-paid-API corpus from a URL manifest.
The safe default fetches cached Wikipedia article HTML and URLs that the teacher
already routed through r.jina.ai. Arbitrary direct-web fetching is opt-in so a
smoke test cannot accidentally crawl 12,000 domains.
"""
from __future__ import annotations
import argparse
import asyncio
import difflib
import hashlib
import json
import re
import time
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from html.parser import HTMLParser
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, quote, unquote, urlsplit, urlunsplit
from urllib.robotparser import RobotFileParser
import httpx
try:
import pymupdf
except ImportError: # optional direct-crawl dependency
pymupdf = None
try:
import trafilatura
except ImportError: # optional direct-crawl dependency
trafilatura = None
try:
from charset_normalizer import from_bytes as detect_charset
except ImportError: # httpx environments normally provide this, but keep a fallback
detect_charset = None
try:
from .common import read_jsonl
from .corpus_db import connect, fts_counts, ingest_manifest, rebuild_fts, save_fetch_result, status_counts
except ImportError: # direct script execution
from common import read_jsonl
from corpus_db import connect, fts_counts, ingest_manifest, rebuild_fts, save_fetch_result, status_counts
class HTMLTextExtractor(HTMLParser):
BLOCK_TAGS = {
"article",
"blockquote",
"br",
"dd",
"div",
"dl",
"dt",
"figcaption",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"li",
"main",
"p",
"pre",
"section",
"table",
"td",
"th",
"tr",
}
IGNORED_TAGS = {"canvas", "footer", "form", "nav", "noscript", "script", "style", "svg"}
def __init__(self, content_root_id: str | None = None) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self.title_parts: list[str] = []
self.ignored_depth = 0
self.in_title = False
self.content_root_id = content_root_id
self.capture_content = content_root_id is None
self.root_tag = ""
self.root_tag_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.casefold()
if tag == "title":
self.in_title = True
if not self.capture_content:
attributes = dict(attrs)
if attributes.get("id") != self.content_root_id:
return
self.capture_content = True
self.root_tag = tag
self.root_tag_depth = 1
elif self.content_root_id and tag == self.root_tag:
self.root_tag_depth += 1
if tag in self.IGNORED_TAGS:
self.ignored_depth += 1
if tag in self.BLOCK_TAGS and not self.ignored_depth:
self.parts.append("\n")
def handle_endtag(self, tag: str) -> None:
tag = tag.casefold()
if tag == "title":
self.in_title = False
if not self.capture_content:
return
if tag in self.IGNORED_TAGS and self.ignored_depth:
self.ignored_depth -= 1
if tag in self.BLOCK_TAGS and not self.ignored_depth:
self.parts.append("\n")
if self.content_root_id and tag == self.root_tag:
self.root_tag_depth -= 1
if self.root_tag_depth == 0:
self.capture_content = False
def handle_data(self, data: str) -> None:
if self.in_title:
self.title_parts.append(data)
if not self.capture_content or self.ignored_depth or self.in_title:
return
self.parts.append(data)
def result(self) -> tuple[str, str]:
title = re.sub(r"\s+", " ", " ".join(self.title_parts)).strip()
lines = [re.sub(r"[ \t\f\v]+", " ", line).strip() for line in "".join(self.parts).splitlines()]
text = "\n".join(line for line in lines if line)
return title, text
@dataclass
class HTTPBody:
status_code: int
content_type: str
final_url: str
body: bytes
@dataclass
class RobotsPolicy:
"""One origin's parsed robots.txt policy.
The policy is cached per origin, but ``can_fetch`` must still be evaluated
for every target URL because robots rules are path-specific.
"""
robots_url: str
parser: RobotFileParser | None
default_allowed: bool
status: str
reason: str
fetched_at: str
http_status: int | None = None
content_sha256: str = ""
def decision(self, user_agent: str, target_url: str) -> tuple[bool, str]:
if self.parser is None:
return self.default_allowed, self.reason
allowed = self.parser.can_fetch(user_agent, target_url)
verdict = "allows" if allowed else "disallows"
return allowed, f"robots.txt {verdict} this URL"
class FetchFailure(ValueError):
"""Expected fetch/extraction rejection with diagnostics worth persisting."""
def __init__(
self,
message: str,
*,
http_status: int | None = None,
content_type: str = "",
source: str = "",
) -> None:
super().__init__(message)
self.http_status = http_status
self.content_type = content_type
self.source = source
class HostRateLimiter:
def __init__(self, interval: float) -> None:
self.interval = interval
self._locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
self._next: defaultdict[str, float] = defaultdict(float)
self._host_intervals: defaultdict[str, float] = defaultdict(float)
def set_host_interval(self, hostname: str, interval: float) -> None:
self._host_intervals[hostname.casefold()] = max(self._host_intervals[hostname.casefold()], interval)
async def defer(self, hostname: str, delay: float) -> None:
"""Apply server backpressure to every coroutine targeting a host."""
hostname = hostname.casefold()
async with self._locks[hostname]:
self._next[hostname] = max(self._next[hostname], time.monotonic() + max(0.0, delay))
async def wait(self, hostname: str) -> None:
hostname = hostname.casefold()
while True:
async with self._locks[hostname]:
now = time.monotonic()
delay = self._next[hostname] - now
if delay <= 0:
interval = max(self.interval, self._host_intervals[hostname])
self._next[hostname] = now + interval
return
await asyncio.sleep(delay)
def retry_after_seconds(value: str, *, now: datetime | None = None) -> float | None:
value = value.strip()
if not value:
return None
try:
return max(0.0, float(value))
except ValueError:
pass
try:
retry_at = parsedate_to_datetime(value)
if retry_at.tzinfo is None:
retry_at = retry_at.replace(tzinfo=timezone.utc)
current = now or datetime.now(timezone.utc)
return max(0.0, (retry_at - current).total_seconds())
except (TypeError, ValueError, OverflowError):
return None
def wikipedia_title(url: str) -> str:
parsed = urlsplit(url)
if parsed.path.startswith("/wiki/"):
return unquote(parsed.path[len("/wiki/") :]).replace("_", " ")
return parse_qs(parsed.query).get("title", [""])[0]
def title_tokens(value: str) -> list[str]:
return re.findall(r"[^\W_]+", value.casefold(), flags=re.UNICODE)
def title_similarity(left: str, right: str) -> float:
left_key = " ".join(title_tokens(left))
right_key = " ".join(title_tokens(right))
if not left_key or not right_key:
return 0.0
left_tokens = set(left_key.split())
right_tokens = set(right_key.split())
token_score = 2 * len(left_tokens & right_tokens) / (len(left_tokens) + len(right_tokens))
return max(token_score, difflib.SequenceMatcher(None, left_key, right_key).ratio())
def safe_wikipedia_title_match(original: str, candidate: str) -> bool:
original_token_list = title_tokens(original)
candidate_token_list = title_tokens(candidate)
original_tokens = set(original_token_list)
candidate_tokens = set(candidate_token_list)
if not original_tokens or not candidate_tokens:
return False
if (
len(original_token_list) == len(candidate_token_list) + 1
and original_token_list[0] in {"the", "a", "an"}
and original_token_list[1:] == candidate_token_list
):
# A stale title that differs only by an initial article is highly
# ambiguous (for example, two different films named "The Little Lady"
# and "Little Lady"). Prefer a miss over silently changing entities.
return False
original_coverage = len(original_tokens & candidate_tokens) / len(original_tokens)
candidate_position = 0
for token in original_token_list:
if token == candidate_token_list[candidate_position]:
candidate_position += 1
if candidate_position == len(candidate_token_list):
break
return (
candidate_tokens.issubset(original_tokens)
and candidate_position == len(candidate_token_list)
and original_coverage >= 2 / 3
and title_similarity(original, candidate) >= 0.65
)
def wikipedia_qualifier_supported(original: str, candidate: str, lead_text: str) -> bool:
"""Require a dropped parenthetical qualifier to be explicit in the article lead."""
qualifier_match = re.search(r"\(([^()]*)\)\s*$", original)
if not qualifier_match:
return True
aliases = {"tv": "television"}
def normalized_tokens(value: str) -> list[str]:
return [aliases.get(token, token) for token in title_tokens(value)]
qualifier_tokens = normalized_tokens(qualifier_match.group(1))
if not qualifier_tokens:
return True
candidate_tokens = set(normalized_tokens(candidate))
if set(qualifier_tokens).issubset(candidate_tokens):
return True
qualifier_key = " ".join(qualifier_tokens)
lead_key = " ".join(normalized_tokens(lead_text[:800]))
return qualifier_key in lead_key
def wikipedia_qualifier_type_consistent(original: str, lead_text: str) -> bool:
"""Reject an explicit lead type that conflicts with a title qualifier.
Search can return a work whose title happens to contain the qualifier word;
for example ``Unity (band)`` resolves to the album *Unity Band*. Limit this
check to the first lead sentence and to unambiguous media-type conflicts so
that later "other uses" text cannot turn a mismatch into false support.
"""
qualifier_match = re.search(r"\(([^()]*)\)\s*$", original)
if not qualifier_match:
return True
qualifier_key = " ".join(title_tokens(qualifier_match.group(1)))
qualifier_tokens = set(qualifier_key.split())
first_line = next((line.strip() for line in lead_text.splitlines() if line.strip()), "")
first_sentence = re.split(r"[.!?](?:\s|$)", first_line, maxsplit=1)[0]
about_match = re.search(
r"\bthis article is about\s+(.{1,240}?)(?:[.!?](?:\s|$)|\bfor (?:other|the)\b)",
lead_text[:1200],
re.IGNORECASE | re.DOTALL,
)
if about_match:
# A Wikipedia hatnote is stronger entity-type evidence than an
# incidental mention later in the lead. For example, the stale URL
# ``My Sister Eileen (musical)`` redirects to a page which explicitly
# says it is about the short stories and book, while merely listing a
# musical among several adaptations farther down.
first_sentence = about_match.group(1)
elif first_sentence.casefold().startswith("for "):
# Navigation hatnotes such as "For the film, see ..." describe a
# different page and must not be treated as the current page's type.
first_sentence = ""
descriptor_tokens = set(title_tokens(first_sentence))
sport_qualifiers = {
"baseball",
"basketball",
"bridge",
"cricket",
"football",
"golf",
"hockey",
"rugby",
"tennis",
}
sport_conflicts = {"album", "book", "film", "movie", "novel", "painting", "single", "song"}
if qualifier_tokens & sport_qualifiers and (
{"video", "game"}.issubset(descriptor_tokens) or descriptor_tokens & sport_conflicts
):
return False
type_rules: tuple[tuple[set[str], set[str], set[str]], ...] = (
(
{"film", "director"},
{"director", "filmmaker"},
{"album", "book", "film", "movie", "novel", "painting", "single", "song"},
),
(
{"band"},
{"band", "duo", "group", "trio"},
{"album", "book", "film", "movie", "novel", "painting", "single", "song"},
),
(
{"song"},
{"single", "song"},
{"album", "band", "book", "film", "group", "movie", "novel", "painting"},
),
(
{"album"},
{"album", "ep"},
{"band", "book", "film", "group", "movie", "novel", "painting", "single", "song"},
),
(
{"film"},
{"film", "movie"},
{"album", "band", "book", "group", "novel", "painting", "single", "song"},
),
(
{"novel"},
{"book", "novel"},
{"album", "band", "film", "group", "movie", "painting", "single", "song"},
),
(
{"painting"},
{"artwork", "painting"},
{"album", "band", "book", "film", "group", "movie", "novel", "single", "song"},
),
(
{"musical"},
{"musical"},
{"book", "film", "movie", "novel", "series", "stories", "story", "television"},
),
)
matching_rule = next((rule for rule in type_rules if rule[0].issubset(qualifier_tokens)), None)
if matching_rule is None:
return True
_, expected_types, conflicting_types = matching_rule
if descriptor_tokens & expected_types:
return True
return not bool(descriptor_tokens & conflicting_types)
def wikipedia_dropped_title_tokens_supported(original: str, candidate: str, lead_text: str) -> bool:
"""Require title tokens omitted by a search candidate to occur early in its lead."""
original_tokens = title_tokens(original)
candidate_counts = Counter(title_tokens(candidate))
missing_tokens: list[str] = []
for token in original_tokens:
if candidate_counts[token]:
candidate_counts[token] -= 1
else:
missing_tokens.append(token)
if not missing_tokens:
return True
if original_tokens[0] == "category" and any(token.isdecimal() for token in missing_tokens):
# A year-specific category commonly resolves to its parent category,
# whose member list mentions that year near the top. That mention is
# hierarchy navigation, not evidence that the narrower page survived.
return False
lead_tokens = set(title_tokens(lead_text)[:128])
return all(token in lead_tokens for token in missing_tokens)
def is_wikipedia_disambiguation_lead(lead_text: str) -> bool:
"""Detect search results whose lead is a disambiguation list rather than an article."""
return bool(re.search(r"\b(?:may|can|could)(?:\s+also)?\s+refer\s+to\b", lead_text[:1000], re.IGNORECASE))
def wikipedia_html_page_flags(html: str) -> tuple[bool, bool]:
"""Return MediaWiki disambiguation and set-index markers from raw HTML."""
lowered = html.casefold()
is_disambiguation = "mw:pageprop/disambiguation" in lowered
is_set_index = any(
marker in lowered
for marker in (
"category:all_set_index_articles",
"category:set_index_articles",
"template:ship_index",
)
)
return is_disambiguation, is_set_index
def decode_text(body: bytes, content_type: str) -> str:
"""Decode web text using declared/meta charset before statistical fallback."""
charset_match = re.search(r"charset\s*=\s*['\"]?([^\s;'\"]+)", content_type, flags=re.IGNORECASE)
if not charset_match:
charset_match = re.search(rb"(?i)charset\s*=\s*['\"]?([^\s;'\"/>]+)", body[:8192])
declared = charset_match.group(1).decode("ascii", errors="ignore") if charset_match else ""
else:
declared = charset_match.group(1)
if declared:
try:
return body.decode(declared)
except (LookupError, UnicodeDecodeError):
pass
try:
return body.decode("utf-8")
except UnicodeDecodeError:
pass
if detect_charset is not None:
match = detect_charset(body).best()
if match is not None:
return str(match)
return body.decode("utf-8", errors="replace")
def extract_html_document(html: str, url: str, *, content_root_id: str | None = None) -> tuple[str, str, str]:
"""Extract an HTML title and main text, with a dependency-free fallback."""
parser = HTMLTextExtractor(content_root_id=content_root_id)
parser.feed(html)
title, fallback_text = parser.result()
if content_root_id or trafilatura is None:
return title, fallback_text, "direct_html"
extracted = trafilatura.extract(
html,
url=url,
include_comments=False,
include_tables=True,
include_images=False,
include_links=False,
deduplicate=True,
output_format="json",
with_metadata=True,
)
try:
payload = json.loads(extracted) if extracted else {}
except json.JSONDecodeError:
payload = {}
if payload:
title = str(payload.get("title") or title)
main_text = str(payload.get("text") or "").strip()
else:
main_text = (extracted or "").strip()
if main_text:
return title, main_text, "direct_html_trafilatura"
return title, fallback_text, "direct_html_fallback"
def clean_title(title: str, max_chars: int = 500) -> str:
value = re.sub(r"\s+", " ", title or "").strip()
if len(value) <= max_chars:
return value
return value[: max_chars - 1].rstrip() + "…"
def extract_pdf_document(body: bytes, url: str, max_pages: int) -> tuple[str, str]:
"""Extract reading-order text from a PDF with bounded page work."""
if pymupdf is None:
raise FetchFailure("PDF extraction requires PyMuPDF")
try:
with pymupdf.open(stream=body, filetype="pdf") as document:
if document.needs_pass:
raise FetchFailure("encrypted PDF requires a password")
metadata = document.metadata or {}
title = str(metadata.get("title") or "").strip()
parts = [
document[index].get_text("text", sort=True).strip()
for index in range(min(document.page_count, max_pages))
]
text = "\n\n".join(part for part in parts if part)
if document.page_count > max_pages:
text += f"\n\n[PDF truncated after {max_pages} of {document.page_count} pages]"
except FetchFailure:
raise
except Exception as exc:
raise FetchFailure(f"invalid/unreadable PDF: {exc}") from exc
if not title:
title = unquote(Path(urlsplit(url).path).name).removesuffix(".pdf").replace("_", " ")
return title, text
def error_page_reason(title: str, text: str) -> str:
"""Return a reason for obvious challenge/error shells, otherwise empty."""
title_key = re.sub(r"\s+", " ", title).strip().casefold().rstrip(" .")
exact_titles = {
"access denied",
"attention required! | cloudflare",
"bad gateway",
"checking your browser",
"error",
"forbidden",
"internal server error",
"just a moment",
"not found",
"page not found",
"robot challenge screen",
"security check required",
"service unavailable",
}
status_title = re.fullmatch(
r"(?:4\d\d|5\d\d)(?:\s*[-:]?\s*)(?:access denied|bad gateway|error|forbidden|internal server error|not found|service unavailable)",
title_key,
)
if title_key in exact_titles or status_title:
return f"error/challenge title: {title or '(empty)'}"
prefix = text[:3000].casefold()
challenge_phrases = (
"checking the site connection security",
"checking your browser before accessing",
"performing security verification",
"please enable javascript and cookies to continue",
"press and hold to confirm you are a human",
"verify you are not a bot",
)
phrase = next((item for item in challenge_phrases if item in prefix), "")
return f"challenge text: {phrase}" if phrase else ""
def parse_jina_reader(text: str) -> tuple[str, str]:
"""Strip Jina Reader's transport header and reject obvious error pages."""
title_match = re.search(r"(?m)^Title:\s*(.+)$", text)
title = title_match.group(1).strip() if title_match else ""
content_match = re.search(r"(?m)^Markdown Content:\s*$", text)
header = text[: content_match.start()] if content_match else ""
content = text[content_match.end() :].strip() if content_match else text.strip()
warnings = " ".join(re.findall(r"(?im)^Warning:\s*(.+)$", header))
warning_key = warnings.casefold()
rejected = (
bool(error_page_reason(title, content))
or "requiring captcha" in warning_key
or bool(re.search(r"target url returned error\s+(?:4\d\d|5\d\d)", warning_key))
)
if rejected:
reason = title or warnings or content[:120]
raise ValueError(f"Jina Reader returned a challenge/error page: {reason}")
return title, content
class Fetcher:
def __init__(
self,
*,
timeout: float,
max_bytes: int,
min_chars: int,
per_host_interval: float,
retries: int,
wikipedia_source: str,
max_pdf_pages: int,
respect_robots: bool,
wikipedia_search_fallback: bool,
jina_direct_fallback: bool,
direct_jina_fallback: bool,
user_agent: str,
robots_retries: int = 2,
) -> None:
self.max_bytes = max_bytes
self.min_chars = min_chars
self.retries = retries
self.wikipedia_source = wikipedia_source
self.max_pdf_pages = max_pdf_pages
self.respect_robots = respect_robots
self.wikipedia_search_fallback = wikipedia_search_fallback
self.jina_direct_fallback = jina_direct_fallback
self.direct_jina_fallback = direct_jina_fallback
self.robot_user_agent = user_agent.split(maxsplit=1)[0]
self.robots_retries = robots_retries
self._robots_tasks: dict[str, asyncio.Task[RobotsPolicy]] = {}
self._robots_decisions: dict[str, dict[str, Any]] = {}
self.rate_limiter = HostRateLimiter(per_host_interval)
self.client = httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(timeout),
headers={"User-Agent": user_agent, "Accept-Encoding": "gzip, deflate"},
)
async def close(self) -> None:
await self.client.aclose()
async def get_bytes(
self,
url: str,
*,
params: dict[str, str] | None = None,
max_bytes: int | None = None,
retries: int | None = None,
) -> HTTPBody:
hostname = (urlsplit(url).hostname or "unknown").casefold()
byte_limit = self.max_bytes if max_bytes is None else max_bytes
retry_count = self.retries if retries is None else retries
for attempt in range(retry_count + 1):
await self.rate_limiter.wait(hostname)
try:
async with self.client.stream("GET", url, params=params) as response:
content_length = response.headers.get("content-length")
if content_length and int(content_length) > byte_limit:
raise ValueError(f"response too large: Content-Length={content_length}")
chunks: list[bytes] = []
size = 0
async for chunk in response.aiter_bytes():
size += len(chunk)
if size > byte_limit:
raise ValueError(f"response exceeded byte limit={byte_limit}")
chunks.append(chunk)
result = HTTPBody(
status_code=response.status_code,
content_type=response.headers.get("content-type", ""),
final_url=str(response.url),
body=b"".join(chunks),
)
retry_after = response.headers.get("retry-after", "")
if result.status_code not in {429, 500, 502, 503, 504} or attempt == retry_count:
return result
parsed_retry_after = retry_after_seconds(retry_after)
if parsed_retry_after is not None:
# Respect server backpressure without letting one origin
# stall a resumable corpus job for minutes or hours.
parsed_retry_after = min(parsed_retry_after, 30.0)
if result.status_code == 429:
delay = max(parsed_retry_after or 0.0, 30.0)
await self.rate_limiter.defer(hostname, delay)
else:
delay = parsed_retry_after if parsed_retry_after is not None else min(2 ** (attempt + 1), 30)
await asyncio.sleep(delay)
except httpx.TransportError:
if attempt == retry_count:
raise
await asyncio.sleep(min(2 ** (attempt + 1), 30))
raise AssertionError("unreachable")
async def _load_robots_policy(self, target_url: str) -> RobotsPolicy:
parsed = urlsplit(target_url)
robots_url = urlunsplit((parsed.scheme, parsed.netloc, "/robots.txt", "", ""))
fetched_at = datetime.now(timezone.utc).isoformat()
try:
response = await self.get_bytes(robots_url, max_bytes=512_000, retries=self.robots_retries)
except (httpx.HTTPError, UnicodeError, ValueError) as exc:
return RobotsPolicy(
robots_url=robots_url,
parser=None,
default_allowed=False,
status="unavailable",
reason=f"robots.txt unavailable: {type(exc).__name__}: {exc}",
fetched_at=fetched_at,
)
if response.status_code in {401, 403, 429} or response.status_code >= 500:
return RobotsPolicy(
robots_url=robots_url,
parser=None,
default_allowed=False,
status="unavailable",
reason=f"robots.txt returned HTTP {response.status_code}",
fetched_at=fetched_at,
http_status=response.status_code,
)
if response.status_code >= 400:
return RobotsPolicy(
robots_url=robots_url,
parser=None,
default_allowed=True,
status="absent",
reason=f"robots.txt absent (HTTP {response.status_code})",
fetched_at=fetched_at,
http_status=response.status_code,
)
content_sha256 = hashlib.sha256(response.body).hexdigest()
try:
parser = RobotFileParser()
parser.set_url(robots_url)
parser.parse(decode_text(response.body, response.content_type).splitlines())
hostname = (parsed.hostname or "").casefold()
crawl_delay = parser.crawl_delay(self.robot_user_agent) or parser.crawl_delay("*")
if crawl_delay is not None:
self.rate_limiter.set_host_interval(hostname, float(crawl_delay))
except (UnicodeError, ValueError) as exc:
return RobotsPolicy(
robots_url=robots_url,
parser=None,
default_allowed=False,
status="invalid",
reason=f"invalid robots.txt: {type(exc).__name__}: {exc}",
fetched_at=fetched_at,
http_status=response.status_code,
content_sha256=content_sha256,
)
return RobotsPolicy(
robots_url=robots_url,
parser=parser,
default_allowed=False,
status="parsed",
reason="robots.txt parsed",
fetched_at=fetched_at,
http_status=response.status_code,
content_sha256=content_sha256,
)
async def robots_decision(self, target_url: str) -> dict[str, Any]:
"""Return an auditable, path-specific decision for one target URL."""
parsed = urlsplit(target_url)
origin = urlunsplit((parsed.scheme.casefold(), parsed.netloc.casefold(), "", "", ""))
task = self._robots_tasks.get(origin)
if task is None:
task = asyncio.create_task(self._load_robots_policy(target_url))
self._robots_tasks[origin] = task
policy = await task
allowed, reason = policy.decision(self.robot_user_agent, target_url)
decision = {
"target_url": target_url,
"origin": origin,
"robots_url": policy.robots_url,
"user_agent": self.robot_user_agent,
"allowed": allowed,
"reason": reason,
"policy_status": policy.status,
"robots_http_status": policy.http_status,
"robots_content_sha256": policy.content_sha256,
"robots_fetched_at": policy.fetched_at,
"checked_at": datetime.now(timezone.utc).isoformat(),
}
self._robots_decisions[target_url] = decision
return decision
async def enforce_robots(self, target_url: str) -> dict[str, Any] | None:
if not self.respect_robots:
return None
decision = await self.robots_decision(target_url)
if not decision["allowed"]:
raise FetchFailure(str(decision["reason"]), source="robots")
return decision
async def fetch_wikipedia_api(self, canonical_url: str) -> dict[str, Any]:
parsed = urlsplit(canonical_url)
title = wikipedia_title(canonical_url)
if not title:
raise ValueError("could not extract a Wikipedia title")
api_url = f"https://{parsed.hostname}/w/api.php"
response = await self.get_bytes(
api_url,
params={
"action": "query",
"prop": "extracts|info",
"explaintext": "1",
"redirects": "1",
"inprop": "url",
"format": "json",
"formatversion": "2",
"titles": title,
},
)
if response.status_code >= 400:
raise RuntimeError(f"HTTP {response.status_code}")
payload = json.loads(response.body.decode("utf-8"))
pages = payload.get("query", {}).get("pages", [])
if not pages or pages[0].get("missing") is True:
raise ValueError("Wikipedia page is missing")
page = pages[0]
return {
"title": str(page.get("title") or title),
"text": str(page.get("extract") or ""),
"source": "wikipedia_api",
"http_status": response.status_code,
"content_type": response.content_type,
}
async def fetch_wikipedia_search_fallback(self, canonical_url: str) -> dict[str, Any]:
"""Resolve a stale Wikipedia title through same-language MediaWiki search."""
parsed = urlsplit(canonical_url)
original_title = wikipedia_title(canonical_url)
if not original_title:
raise FetchFailure("Wikipedia URL has no recoverable title", source="wikipedia_search")
api_url = f"https://{parsed.hostname}/w/api.php"
response = await self.get_bytes(
api_url,
params={
"action": "query",
"list": "search",
"srsearch": original_title,
"srnamespace": "0",
"srlimit": "5",
"format": "json",
"formatversion": "2",
},
retries=max(self.retries, 3),
)
if response.status_code >= 400:
raise FetchFailure(
f"Wikipedia search HTTP {response.status_code}",
http_status=response.status_code,
content_type=response.content_type,
source="wikipedia_search",
)
payload = json.loads(decode_text(response.body, response.content_type))
candidates = payload.get("query", {}).get("search", [])
ranked = sorted(
(
(title_similarity(original_title, str(item.get("title") or "")), str(item.get("title") or ""))
for item in candidates
),
reverse=True,
)
safe_ranked = [item for item in ranked if safe_wikipedia_title_match(original_title, item[1])]
if not safe_ranked:
best = ranked[0] if ranked else (0.0, "")
raise FetchFailure(
f"Wikipedia title search found no close match for {original_title!r}; best={best[1]!r} score={best[0]:.3f}",
source="wikipedia_search",
)
resolved_title = safe_ranked[0][1]
resolved_path = "/wiki/" + quote(resolved_title.replace(" ", "_"), safe="()_,-")
resolved_url = urlunsplit((parsed.scheme or "https", parsed.netloc, resolved_path, "", ""))
raw = await self.fetch_generic(resolved_url, content_root_id="mw-content-text")
raw["title"] = re.sub(r"\s+-\s+Wikipedia$", "", raw["title"]).strip()
is_disambiguation = bool(raw.pop("_wikipedia_disambiguation", False))
is_set_index = bool(raw.pop("_wikipedia_set_index", False))
if is_disambiguation or is_wikipedia_disambiguation_lead(str(raw.get("text") or "")):
raise FetchFailure(
f"Wikipedia search candidate {resolved_title!r} is a disambiguation page",
http_status=raw.get("http_status"),
content_type=str(raw.get("content_type") or ""),
source="wikipedia_search",
)
if is_set_index:
raise FetchFailure(
f"Wikipedia search candidate {resolved_title!r} is a set-index page",
http_status=raw.get("http_status"),
content_type=str(raw.get("content_type") or ""),
source="wikipedia_search",
)
if not wikipedia_dropped_title_tokens_supported(
original_title, resolved_title, str(raw.get("text") or "")
):
raise FetchFailure(
f"Wikipedia search candidate {resolved_title!r} does not support omitted title tokens from "
f"{original_title!r}",
http_status=raw.get("http_status"),
content_type=str(raw.get("content_type") or ""),
source="wikipedia_search",
)
if not wikipedia_qualifier_type_consistent(original_title, str(raw.get("text") or "")):
raise FetchFailure(
f"Wikipedia search candidate {resolved_title!r} has a lead type that conflicts with "
f"{original_title!r}",
http_status=raw.get("http_status"),
content_type=str(raw.get("content_type") or ""),
source="wikipedia_search",
)
if not wikipedia_qualifier_supported(original_title, resolved_title, str(raw.get("text") or "")):
raise FetchFailure(
f"Wikipedia search candidate {resolved_title!r} does not support the qualifier in {original_title!r}",
http_status=raw.get("http_status"),
content_type=str(raw.get("content_type") or ""),
source="wikipedia_search",
)
raw["source"] = "wikipedia_search_html"
return raw
async def fetch_generic(self, fetch_url: str, *, content_root_id: str | None = None) -> dict[str, Any]:
response = await self.get_bytes(fetch_url)
if response.status_code >= 400:
raise FetchFailure(
f"HTTP {response.status_code}",
http_status=response.status_code,
content_type=response.content_type,
source="http",
)
content_type = response.content_type.casefold()
hostname = (urlsplit(fetch_url).hostname or "").casefold()
wikipedia_disambiguation = False
wikipedia_set_index = False
if hostname == "r.jina.ai":
decoded = decode_text(response.body, response.content_type)
try:
title, text = parse_jina_reader(decoded)
except ValueError as exc:
raise FetchFailure(
str(exc),
http_status=response.status_code,
content_type=response.content_type,
source="jina_reader",
) from exc
source = "jina_reader"
elif "application/pdf" in content_type or response.body.startswith(b"%PDF-"):
title, text = await asyncio.to_thread(
extract_pdf_document, response.body, response.final_url, self.max_pdf_pages
)
source = "direct_pdf_pymupdf"
elif (
content_type.startswith("text/") and "text/html" not in content_type and "text/xml" not in content_type
) or any(item in content_type for item in ("application/json", "application/ld+json")):
decoded = decode_text(response.body, response.content_type)
title = ""
text = decoded
source = "direct_text"
else:
if content_type.startswith(("audio/", "image/", "video/")) or any(
item in content_type
for item in ("application/gzip", "application/zip", "application/x-7z-compressed", "application/x-rar")
):
raise FetchFailure(
f"non-text content type: {response.content_type}",
http_status=response.status_code,
content_type=response.content_type,
source="unsupported",
)
decoded = decode_text(response.body, response.content_type)
prefix = decoded.lstrip().lower()
if (
"text/html" in content_type
or "application/xhtml+xml" in content_type
or prefix.startswith(("<!doctype html", "<html"))
):
if hostname == "wikipedia.org" or hostname.endswith(".wikipedia.org"):
wikipedia_disambiguation, wikipedia_set_index = wikipedia_html_page_flags(decoded)
title, text, source = await asyncio.to_thread(
extract_html_document,
decoded,
response.final_url,
content_root_id=content_root_id,
)
elif any(item in content_type for item in ("application/xml", "text/xml", "+xml")) or prefix.startswith(
"<?xml"
):
parser = HTMLTextExtractor()
parser.feed(decoded)
title, text = parser.result()
source = "direct_xml"
else:
raise FetchFailure(
f"unsupported content type: {response.content_type or 'unknown'}",
http_status=response.status_code,
content_type=response.content_type,
source="unsupported",
)
reason = error_page_reason(title, text)
if reason:
raise FetchFailure(
reason,
http_status=response.status_code,
content_type=response.content_type,
source=source,
)
if len(text.strip()) < self.min_chars:
raise FetchFailure(
f"extracted only {len(text.strip())} characters",
http_status=response.status_code,
content_type=response.content_type,
source=source,
)
result = {
"title": title,
"text": text,
"source": source,
"http_status": response.status_code,
"content_type": response.content_type,
}
if hostname == "wikipedia.org" or hostname.endswith(".wikipedia.org"):
result["_wikipedia_disambiguation"] = wikipedia_disambiguation
result["_wikipedia_set_index"] = wikipedia_set_index
return result
def finalize(self, result: dict[str, Any] | Exception) -> dict[str, Any]:
try:
if isinstance(result, Exception):
raise result
text = re.sub(r"\x00", "", result.pop("text", "")).strip()
if len(text) < self.min_chars:
raise ValueError(f"extracted only {len(text)} characters")
result["title"] = clean_title(str(result.get("title") or ""))
result.update({"status": "success", "text": text, "error": ""})
except (httpx.HTTPError, json.JSONDecodeError, RuntimeError, UnicodeError, ValueError) as exc:
result = {
"status": "failed",
"title": "",
"text": "",
"source": str(getattr(exc, "source", "")),
"http_status": getattr(exc, "http_status", None),
"content_type": str(getattr(exc, "content_type", "")),
"error": f"{type(exc).__name__}: {exc}"[:1000],
}
result["fetched_at"] = datetime.now(timezone.utc).isoformat()
return result
async def fetch_record(self, record: dict[str, Any]) -> dict[str, Any]:
canonical_host = (urlsplit(record["canonical_url"]).hostname or "").casefold()
try:
if canonical_host == "wikipedia.org" or canonical_host.endswith(".wikipedia.org"):
if self.wikipedia_source == "api":
raw = await self.fetch_wikipedia_api(record["canonical_url"])
else:
try:
raw = await self.fetch_generic(record["canonical_url"], content_root_id="mw-content-text")
raw["title"] = re.sub(r"\s+-\s+Wikipedia$", "", raw["title"]).strip()
raw["source"] = "wikipedia_html"
except FetchFailure as direct_error:
if direct_error.http_status != 404 or not self.wikipedia_search_fallback:
raise
try:
raw = await self.fetch_wikipedia_search_fallback(record["canonical_url"])
except (httpx.HTTPError, json.JSONDecodeError, UnicodeError, ValueError) as search_error:
raise FetchFailure(
f"Wikipedia direct fetch failed ({direct_error}); search fallback failed ({search_error})",
http_status=getattr(search_error, "http_status", None),
content_type=str(getattr(search_error, "content_type", "")),
source="wikipedia_direct_then_search",
) from search_error
else:
fetch_host = (urlsplit(record["fetch_url"]).hostname or "").casefold()
if fetch_host == "r.jina.ai":
try:
raw = await self.fetch_generic(record["fetch_url"])
except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as jina_error:
if not self.jina_direct_fallback:
raise
try:
await self.enforce_robots(record["canonical_url"])
raw = await self.fetch_generic(record["canonical_url"])
except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as direct_error:
raise FetchFailure(
f"Jina failed ({jina_error}); direct fallback failed ({direct_error})",
http_status=getattr(direct_error, "http_status", None),
content_type=str(getattr(direct_error, "content_type", "")),
source="jina_then_direct",
) from direct_error
else:
try:
await self.enforce_robots(record["canonical_url"])
raw = await self.fetch_generic(record["canonical_url"])
except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as direct_error:
if not self.direct_jina_fallback or getattr(direct_error, "source", "") in {
"robots",
"unsupported",
}:
raise
reader_url = f"https://r.jina.ai/{record['canonical_url']}"
try:
raw = await self.fetch_generic(reader_url)
except (httpx.HTTPError, RuntimeError, UnicodeError, ValueError) as jina_error:
raise FetchFailure(
f"Direct fetch failed ({direct_error}); Jina fallback failed ({jina_error})",
http_status=getattr(jina_error, "http_status", None),
content_type=str(getattr(jina_error, "content_type", "")),
source="direct_then_jina",
) from jina_error
except (httpx.HTTPError, json.JSONDecodeError, RuntimeError, UnicodeError, ValueError) as exc:
raw = exc
result = self.finalize(raw)
robots_decision = self._robots_decisions.get(record["canonical_url"])
if robots_decision is not None:
result["_robots_decision"] = robots_decision
return result
def domain_matches(hostname: str, allowed_domain: str) -> bool:
host = hostname.casefold().strip(".")
allowed = allowed_domain.casefold().strip(".")
return host == allowed or host.endswith("." + allowed)
def is_wikipedia(record: dict[str, Any]) -> bool:
host = (urlsplit(record["canonical_url"]).hostname or "").casefold()
return host == "wikipedia.org" or host.endswith(".wikipedia.org")
def is_allowed(record: dict[str, Any], allow_domains: list[str], allow_direct_all: bool) -> bool:
canonical_host = urlsplit(record["canonical_url"]).hostname or ""
fetch_host = urlsplit(record["fetch_url"]).hostname or ""
if canonical_host == "wikipedia.org" or canonical_host.endswith(".wikipedia.org"):
return True
if fetch_host.casefold() == "r.jina.ai":
return True
if allow_direct_all:
return True
return any(domain_matches(canonical_host, allowed) for allowed in allow_domains)
async def fetch_manifest(
manifest_path: Path,
database_path: Path,
*,
limit: int,
concurrency: int,
timeout: float,
max_bytes: int,
min_chars: int,
per_host_interval: float,
retries: int,
wikipedia_source: str,
max_pdf_pages: int,
respect_robots: bool,
wikipedia_search_fallback: bool,
jina_direct_fallback: bool,
direct_jina_fallback: bool,
allow_domains: list[str],
allow_direct_all: bool,
only_wikipedia: bool,
retry_failed: bool,
user_agent: str,
rebuild_index: bool,
robots_retries: int = 2,
) -> dict[str, Any]:
records = list(read_jsonl(manifest_path))
by_id = {record["url_id"]: record for record in records}
connection = connect(database_path)
ingest_manifest(connection, records)
status_by_id = {row["url_id"]: row["status"] for row in connection.execute("SELECT url_id, status FROM documents")}
candidates = [
record
for record in records
if is_allowed(record, allow_domains, allow_direct_all)
and (not only_wikipedia or is_wikipedia(record))
and (
status_by_id.get(record["url_id"]) == "pending"
or (retry_failed and status_by_id.get(record["url_id"]) == "failed")
)
]
candidates.sort(
key=lambda record: (
0 if record["domain"].endswith("wikipedia.org") else 1 if record.get("has_jina_reader_url") else 2,
-int(record.get("visit_count", 0)),
record["url_id"],
)
)
if limit:
candidates = candidates[:limit]
queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
for record in candidates:
queue.put_nowait(record)
progress: Counter[str] = Counter()
progress_lock = asyncio.Lock()
fetcher = Fetcher(
timeout=timeout,
max_bytes=max_bytes,
min_chars=min_chars,
per_host_interval=per_host_interval,
retries=retries,
wikipedia_source=wikipedia_source,
max_pdf_pages=max_pdf_pages,
respect_robots=respect_robots,
wikipedia_search_fallback=wikipedia_search_fallback,
jina_direct_fallback=jina_direct_fallback,
direct_jina_fallback=direct_jina_fallback,
user_agent=user_agent,
robots_retries=robots_retries,
)
async def worker() -> None:
while True:
try:
record = queue.get_nowait()
except asyncio.QueueEmpty:
return
result = await fetcher.fetch_record(record)
save_fetch_result(connection, record["url_id"], result)
async with progress_lock:
progress[result["status"]] += 1
done = sum(progress.values())
if done == 1 or done % 50 == 0 or done == len(candidates):
print(
f"fetched {done}/{len(candidates)} success={progress['success']} failed={progress['failed']}"
)
queue.task_done()
try:
await asyncio.gather(*(worker() for _ in range(max(1, concurrency))))
finally:
await fetcher.close()
indexed = rebuild_fts(connection) if rebuild_index else None
index_counts = fts_counts(connection) if rebuild_index else None
summary = {
"manifest_records": len(by_id),
"eligible_records": sum(is_allowed(record, allow_domains, allow_direct_all) for record in records),
"attempted": len(candidates),
"wikipedia_source": wikipedia_source,
"respect_robots": respect_robots,
"robots_retries": robots_retries,
"wikipedia_search_fallback": wikipedia_search_fallback,
"jina_direct_fallback": jina_direct_fallback,
"direct_jina_fallback": direct_jina_fallback,
"html_extractor": "trafilatura" if trafilatura is not None else "stdlib_fallback",
"pdf_extractor": "pymupdf" if pymupdf is not None else "unavailable",
"attempt_results": dict(progress),
"database_status": status_counts(connection),
"fts_documents": indexed,
"fts_chunks": index_counts["chunks"] if index_counts else None,
"database": str(database_path),
}
connection.close()
return summary
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=Path, required=True, help="urls.jsonl from extract_retrieval_manifest.py")
parser.add_argument("--database", type=Path, required=True)
parser.add_argument("--limit", type=int, default=0, help="maximum URLs this invocation; 0 means all eligible")
parser.add_argument("--concurrency", type=int, default=4)
parser.add_argument("--timeout", type=float, default=30.0)
parser.add_argument("--max-bytes", type=int, default=8_000_000)
parser.add_argument("--min-chars", type=int, default=100)
parser.add_argument("--per-host-interval", type=float, default=0.25)
parser.add_argument("--retries", type=int, default=3)
parser.add_argument("--robots-retries", type=int, default=2)
parser.add_argument("--max-pdf-pages", type=int, default=500)
parser.add_argument(
"--wikipedia-source",
choices=("html", "api"),
default="html",
help="HTML is faster/cached; API produces cleaner plaintext but is much slower for full extracts",
)
parser.add_argument("--allow-domain", action="append", default=[], help="opt in a direct-fetch domain")
parser.add_argument("--allow-direct-all", action="store_true", help="direct-fetch every domain; use responsibly")
parser.add_argument(
"--ignore-robots",
action="store_true",
help="ignore robots.txt for direct-origin requests (not recommended)",
)
parser.add_argument(
"--wikipedia-search-fallback",
action="store_true",
help="resolve stale Wikipedia 404 titles via conservative same-language MediaWiki search",
)
parser.add_argument(
"--only-wikipedia",
action="store_true",
help="restrict this invocation to Wikipedia records (useful for a slow recovery pass)",
)
parser.add_argument(
"--jina-direct-fallback",
action="store_true",
help="when a recorded Jina Reader fetch fails, try the canonical origin subject to robots.txt",
)
parser.add_argument(
"--direct-jina-fallback",
action="store_true",
help="when an allowed direct-origin request fails, try the public Jina Reader endpoint",
)
parser.add_argument("--retry-failed", action="store_true")
parser.add_argument("--rebuild-index", action="store_true")
parser.add_argument(
"--user-agent",
default="Miles-DeepResearch9K-Corpus/0.1 (local academic research)",
)
args = parser.parse_args()
if (
args.limit < 0
or args.concurrency < 1
or args.per_host_interval < 0
or args.retries < 0
or args.max_pdf_pages < 1
or args.robots_retries < 0
):
parser.error(
"--limit/--retries must be non-negative, --concurrency/--max-pdf-pages >= 1, and --per-host-interval >= 0"
)
summary = asyncio.run(
fetch_manifest(
args.manifest,
args.database,
limit=args.limit,
concurrency=args.concurrency,
timeout=args.timeout,
max_bytes=args.max_bytes,
min_chars=args.min_chars,
per_host_interval=args.per_host_interval,
retries=args.retries,
wikipedia_source=args.wikipedia_source,
max_pdf_pages=args.max_pdf_pages,
respect_robots=not args.ignore_robots,
wikipedia_search_fallback=args.wikipedia_search_fallback,
jina_direct_fallback=args.jina_direct_fallback,
direct_jina_fallback=args.direct_jina_fallback,
allow_domains=args.allow_domain,
allow_direct_all=args.allow_direct_all,
only_wikipedia=args.only_wikipedia,
retry_failed=args.retry_failed,
user_agent=args.user_agent,
rebuild_index=args.rebuild_index,
robots_retries=args.robots_retries,
)
)
print(json.dumps(summary, indent=2, sort_keys=True))
if __name__ == "__main__":
main()