Files
floop/code/knowledge/wiki.py
T
onibot e5482bd092 feat(logic): setop engine + set gate — the Europe count computed end-to-end
A) SET GATE: enumerations are answered only from membership sets, never from mention rows (the probe early-exit that served 'Armenia, Cyprus, Georgia, Turkey' to 'what countries are in Europe' is dead). Sets carry origin_question; the gate matches stem-Jaccard>=0.5 so a set is served to its own question only. B) SETOP ENGINE: logic's first real engine — a count over list rows is computed (difference/intersection/count over norm_name'd items, table markers 'Austria*' == 'Austria'), before ROUTE, zero LLM calls, verified=True because the computation IS the check. C) Catalog honesty: knowledge 'lists are ONE fetch', logic 'how-many over lists in evidence', floop 'NOT mere size'. Plus four substrate bugs the live runs exposed: LM-proxy prompt cache (instant answers are cache hits, never trust zero latency), _context rendering list rows as scalars ('E1: 50' routed 'those countries' to user), <br> concatenation in multi-value name cells, multi-line refs leaking into values ('franceincludes the 101 departments' -> France dropped from EU -> 24 not 23). Cold E2E: Q1 50 states ingested, Q2 27 EU members ingested, Q3 difference computed = 23, cited over E1/E2. 22/22 tests.
2026-10-18 19:49:24 +02:00

318 lines
13 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"
@dataclass
class WikiTable:
"""One parsed wikitext table: header row + all data rows, untruncated."""
idx: int # 1-based, order in the page
caption: str = ""
header: list[str] = field(default_factory=list)
rows: list[list[str]] = field(default_factory=list)
@property
def total_rows(self) -> int:
return len(self.rows)
def text_lines(self) -> list[str]:
"""Canonical stored text: one 'a | b | c' line per row (containment target)."""
out = []
if self.header:
out.append(" | ".join(self.header))
out.extend(" | ".join(r) for r in self.rows)
return out
def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
"""Parse ALL wikitext tables into typed WikiTables via a GRID parser.
Three alignment laws fix the misaligned-row bugs:
- cells ACCUMULATE until a '|-' separator — vertical layout (one cell per
line) and horizontal layout ('a || b') both build ONE row until then;
- EMPTY cells are KEPT as placeholders (image cells clean to '' — dropping
them shifted every following cell left; 'France' rows started at 'FRA');
- rowspan/colspan expand at placement so every physical row aligns.
NO row truncation: `total_rows` is the computed extent of the source."""
tables: list[WikiTable] = []
for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S):
if len(tables) >= max_tables:
break
t = WikiTable(idx=len(tables) + 1)
grid: list[list[str]] = []
header_grid: list[list[str]] = []
spans: dict[int, str] = {} # col -> carried value (rowspan)
span_left: dict[int, int] = {} # col -> rows still to carry it
raw_cells: list[str] = []
row_is_header = False
def flush_row(cells: list[str], is_header: bool) -> None:
"""Place raw cells on a physical row: strip attrs, expand spans."""
row: list[str] = []
col = 0
for c in cells:
while span_left.get(col, 0) > 0: # carried rowspan cell
row.append(spans.get(col, ""))
span_left[col] -= 1
col += 1
attrs, rest = _split_attrs(c)
value = _clean_cell(rest)
try:
rowspan = max(1, int(attrs.get("rowspan", 1) or 1))
colspan = max(1, int(attrs.get("colspan", 1) or 1))
except ValueError:
rowspan = colspan = 1
for _ in range(colspan):
if rowspan > 1:
spans[col] = value
span_left[col] = rowspan - 1
row.append(value)
col += 1
while span_left.get(col, 0) > 0: # trailing spans
row.append(spans.get(col, ""))
span_left[col] -= 1
col += 1
(header_grid if is_header else grid).append(row)
for line in m.group(1).splitlines():
line = line.strip()
if not line:
continue
if line.startswith("|+"): # caption
t.caption = _clean_cell(line[2:])
continue
if line.startswith("|-") or line.startswith("!-"):
if raw_cells:
flush_row(raw_cells, row_is_header)
raw_cells, row_is_header = [], False
continue
if line.startswith("!"):
raw_cells.extend(re.split(r"!!", line.lstrip("!")))
row_is_header = True
continue
if line.startswith("|"):
raw_cells.extend(re.split(r"\|\|", line.lstrip("|")))
continue
# continuation line: multi-line refs/templates inside a cell do
# not start with a marker — they belong to the previous raw cell
if raw_cells:
raw_cells[-1] += " " + line
continue
if raw_cells:
flush_row(raw_cells, row_is_header)
if header_grid:
t.header = [c for r in header_grid for c in r]
t.rows = grid
if t.rows or t.header:
tables.append(t)
return tables
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str:
"""Legacy helper for prose enrichment (fetch_rich). The LIST path uses
parse_tables directly — untruncated and typed."""
out: list[str] = []
for t in parse_tables(wikitext, max_tables=max_tables):
lines = t.text_lines()
out.append(chr(10).join(lines[:max_rows]))
return (chr(10) * 2).join(out)
CITATION_TPL = ("cref", "cref2", "efn", "sfn", "fn", "citation", "cite", "note",
"refn", "anchor")
def _tpl_arg(content: str) -> str:
"""Resolve a template body to its display text: the first argument after
the template name that is not a named parameter (no '='). Citation/footnote
templates ({{cref2|j}}, {{efn|...}}) resolve to EMPTY — they are markup,
not content."""
parts = [p.strip() for p in content.split("|")]
name = parts[0].casefold().split("<")[0].strip()
if any(name == t or name.startswith(t) for t in CITATION_TPL):
return ""
for p in parts[1:]:
if p and "=" not in p:
return p
return ""
def _clean_cell(cell: str) -> str:
"""Resolve links/templates to display text; drop refs, File links, tags.
Order matters: <br> variants become ' / ' separators FIRST (multi-value
name cells like 'Albania<br>Republic of Albania<br>ALB' must not
concatenate), then refs, File links, links, templates."""
cell = re.sub(r"<br\s*/?>", " / ", cell, flags=re.I)
cell = re.sub(r"<ref[^>]*>.*?</ref>", "", cell, flags=re.S | re.I)
cell = re.sub(r"<ref[^>]*/?>", "", cell, flags=re.I)
cell = re.sub(r"<sup[^>]*>.*?</sup>", "", cell, flags=re.S | re.I)
cell = re.sub(r"<sup[^>]*/?>", "", cell, flags=re.I)
cell = re.sub(r"\[\[(?:File|Image):.*?\]\]", "", cell, flags=re.I | re.S)
cell = re.sub(r"\[\[(?:[^|\]]*\|)*([^\]]+)\]\]", r"\1", cell)
while "{{" in cell:
new = re.sub(r"\{\{([^{}]*)\}\}", lambda mm: _tpl_arg(mm.group(1)), cell)
if new == cell:
break
cell = new
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")
def _split_attrs(raw: str) -> tuple[dict, str]:
"""Split leading wikitext cell attributes ('style=.. rowspan="2" |') from
the value. Returns ({attr: value}, rest)."""
if "|" in raw:
head, rest = raw.split("|", 1)
if "=" in head and re.search(r"[a-zA-Z]+\s*=", head):
attrs = dict(re.findall(r"([a-zA-Z]+)\s*=\s*\"?([^\s\"]+)\"?", head))
return attrs, rest
return {}, raw
class WikiError(RuntimeError):
pass
@dataclass
class WikiPage:
"""A fetched article: plain text + section structure + typed tables."""
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
tables: list[WikiTable] = field(default_factory=list)
@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 + typed tables: wikitext tables are parsed UNTRUNCATED into
WikiTable objects (total_rows is a computed fact). Prose enrichment
(== Tables == section) kept for the chunk path; the LIST path reads
page.tables directly."""
page = self.fetch(title)
wikitext = self.fetch_wikitext(title)
page.tables = parse_tables(wikitext)
extra = tables_as_text(wikitext)
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", [])]