Emili's home run failed where the VPS seemed to work: warm-KG illusion; cold path never validated. Reproduced with a wiped KG. Fixes: (1) tables_as_text parses BOTH wikitext layouts (horizontal pipes and one-cell-per-line with row separators) + _clean_cell drops attrs/links/templates; (2) gather searches all queries, dedupes, ranks globally by title relevance, fetches ONE article at a time with EARLY EXIT when the KG answers; (3) hybrid order keeps each query's top-1 slot guaranteed (title relevance buries entity pages like 'Loire'). Also: NameError from refactor caught by baseline fallback; counters accumulate. Cold E2E verified: France (table quote) -> Loire (early exit, 1 article) in 2hops. RUNLOG Run D.
189 lines
8.0 KiB
Python
189 lines
8.0 KiB
Python
"""Wikipedia access via the official MediaWiki API (action API, en.wikipedia only).
|
|
|
|
Why raw API over the `wikipedia` pip package (tested 2026-10-17): the package
|
|
sends params with empty-string values (e.g. redirects: '') which make the API
|
|
return an HTML error page instead of JSON, and its default User-Agent is blocked
|
|
(403). The official action API called directly with a proper session is reliable
|
|
and gives us search + plain-text extracts + revision ids in one place.
|
|
|
|
Search-first per Emili (2026-10-17): use the Wikipedia search engine to find
|
|
articles, then fetch and analyze them chunk by chunk.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
|
|
import requests
|
|
|
|
API = "https://en.wikipedia.org/w/api.php"
|
|
UA = "floop-bot/0.1 (research; contact: emili@oniricapps.com)"
|
|
LANG = "en"
|
|
|
|
|
|
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str:
|
|
"""Parse wikitext tables into one text line per row ('cell | cell | cell').
|
|
|
|
Handles BOTH layouts: horizontal rows ('| a || b || c') and vertical cells
|
|
(one cell per line, rows separated by '|-'). Cell attributes
|
|
('| style=... | value') are dropped; links/templates resolved. Containment
|
|
is checked against the ENRICHED page text."""
|
|
out: list[str] = []
|
|
for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S):
|
|
if len(out) >= max_tables:
|
|
break
|
|
rows: list[str] = []
|
|
cells: list[str] = []
|
|
for line in m.group(1).splitlines():
|
|
line = line.strip()
|
|
if not line or line.startswith("|+"): # blank / caption
|
|
continue
|
|
if line.startswith("|-") or line.startswith("!-"): # row separator
|
|
if cells:
|
|
rows.append(" | ".join(cells))
|
|
cells = []
|
|
continue
|
|
if line.startswith("|") or line.startswith("!"):
|
|
body = line.lstrip("|!")
|
|
for cell in re.split(r"\|\||!!", body):
|
|
cell = _clean_cell(cell)
|
|
if cell:
|
|
cells.append(cell)
|
|
if cells:
|
|
rows.append(" | ".join(cells))
|
|
if rows:
|
|
out.append(chr(10).join(rows[:max_rows]))
|
|
return (chr(10) * 2).join(out)
|
|
|
|
|
|
def _clean_cell(cell: str) -> str:
|
|
"""Resolve links ([[a|b]]->b), templates ({{t|arg}}->arg), drop attrs and tags."""
|
|
cell = re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", cell)
|
|
cell = re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", cell)
|
|
cell = re.sub(r"\{\{[^}]*\}\}", "", cell)
|
|
if "|" in cell and "=" in cell.split("|")[0]: # '| attrs | value' -> value
|
|
cell = cell.split("|")[-1]
|
|
cell = re.sub(r"<[^>]+>", "", cell)
|
|
return cell.strip(" '\u201c\u201d")
|
|
|
|
|
|
class WikiError(RuntimeError):
|
|
pass
|
|
|
|
|
|
@dataclass
|
|
class WikiPage:
|
|
"""A fetched article: plain text + section structure, verbatim-preserving."""
|
|
title: str
|
|
pageid: int
|
|
url: str
|
|
text: str # the full plain-text extract (contains section headings)
|
|
fetched_at: str # ISO timestamp
|
|
rev_id: int | None = None
|
|
|
|
@property
|
|
def sections(self) -> list[str]:
|
|
"""Heading lines as present in the extract (== Section == markers)."""
|
|
return re.findall(r"^==+ .+? ==+\s*$", self.text, flags=re.M)
|
|
|
|
|
|
class WikipediaClient:
|
|
"""Thin, honest client over the MediaWiki action API. All calls logged by the caller."""
|
|
|
|
def __init__(self, timeout: int = 15, max_retries: int = 2, backoff: float = 1.5):
|
|
self.timeout = timeout
|
|
self.max_retries = max_retries
|
|
self.backoff = backoff
|
|
self.session = requests.Session()
|
|
self.session.headers.update({"User-Agent": UA})
|
|
self.calls = 0
|
|
|
|
# ---- low-level ---------------------------------------------------------
|
|
def _get(self, **params) -> dict:
|
|
params.setdefault("format", "json")
|
|
params.setdefault("formatversion", "2")
|
|
last_err: Exception | None = None
|
|
for attempt in range(self.max_retries + 1):
|
|
self.calls += 1
|
|
try:
|
|
r = self.session.get(API, params=params, timeout=self.timeout)
|
|
if r.status_code == 403:
|
|
raise WikiError("403 forbidden — check User-Agent policy compliance")
|
|
r.raise_for_status()
|
|
ct = r.headers.get("content-type", "")
|
|
if "json" not in ct:
|
|
raise WikiError(f"non-JSON response (content-type={ct}) — API misuse")
|
|
return r.json()
|
|
except (requests.RequestException, WikiError) as e:
|
|
last_err = e
|
|
if attempt < self.max_retries:
|
|
time.sleep(self.backoff * (attempt + 1))
|
|
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
|
|
|
|
# ---- api surface --------------------------------------------------------
|
|
def search(self, query: str, limit: int = 5) -> list[str]:
|
|
"""Official search: list=search. Returns candidate article titles."""
|
|
data = self._get(action="query", list="search", srsearch=query, srlimit=limit)
|
|
return [h["title"] for h in data.get("query", {}).get("search", [])]
|
|
|
|
def summary(self, title: str) -> str:
|
|
data = self._get(action="query", titles=title, prop="extracts",
|
|
explaintext=True, exintro=True, redirects=True)
|
|
pages = data.get("query", {}).get("pages", [])
|
|
if not pages:
|
|
raise WikiError(f"no page for {title!r}")
|
|
pg = pages[0]
|
|
if "missing" in pg:
|
|
raise WikiError(f"page missing: {title!r}")
|
|
return pg.get("extract", "")
|
|
|
|
def fetch(self, title: str) -> WikiPage:
|
|
"""Full plain-text extract with headings preserved (for section chunking)."""
|
|
from datetime import datetime, timezone
|
|
data = self._get(action="query", titles=title, prop="extracts|info",
|
|
explaintext=True, redirects=True, inprop="url")
|
|
pages = data.get("query", {}).get("pages", [])
|
|
if not pages:
|
|
raise WikiError(f"no page for {title!r}")
|
|
pg = pages[0]
|
|
if "missing" in pg or "extract" not in pg:
|
|
raise WikiError(f"page missing or empty: {title!r}")
|
|
return WikiPage(
|
|
title=pg["title"],
|
|
pageid=pg["pageid"],
|
|
url=pg.get("fullurl", f"https://{LANG}.wikipedia.org/wiki/{pg['title'].replace(' ', '_')}"),
|
|
text=pg["extract"],
|
|
fetched_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
rev_id=pg.get("lastrevid"),
|
|
)
|
|
|
|
def fetch_wikitext(self, title: str) -> str:
|
|
"""Raw wikitext (tables live here; the plain extract drops them)."""
|
|
data = self._get(action="query", titles=title, prop="revisions",
|
|
rvprop="content", rvslots="main", redirects=True)
|
|
pages = data.get("query", {}).get("pages", [])
|
|
if not pages:
|
|
raise WikiError(f"no page for {title!r}")
|
|
pg = pages[0]
|
|
if "missing" in pg or "revisions" not in pg:
|
|
raise WikiError(f"page missing: {title!r}")
|
|
return pg["revisions"][0]["slots"]["main"]["content"]
|
|
|
|
def fetch_rich(self, title: str) -> WikiPage:
|
|
"""Extract + table text appended: wikitext tables are parsed into rows
|
|
and appended as text so ranking/list questions have their data."""
|
|
page = self.fetch(title)
|
|
extra = tables_as_text(self.fetch_wikitext(title))
|
|
if extra:
|
|
page.text = page.text + "\n\n== Tables ==\n" + extra
|
|
return page
|
|
|
|
def disambiguation(self, title: str) -> list[str]:
|
|
"""Titles a disambiguation page points to (handles the wiki lib's classic trap)."""
|
|
data = self._get(action="query", titles=title, prop="links", pllimit=50,
|
|
plnamespace=0, redirects=True)
|
|
pages = data.get("query", {}).get("pages", [])
|
|
if not pages:
|
|
return []
|
|
return [l["title"] for l in pages[0].get("links", [])] |