Files
floop/code/knowledge/wiki.py
T
onibot 73fe5cc8e1 knowledge: PR-1 skim surfaces — read articles in passing (KNOWLEDGE §7)
The Italy run (Run G) failed with the data in hand: Q1's LIST ingest
early-exited on the length table and discarded the same article's 27-row
discharge table; the Adige/Tiber discharges live in infobox templates,
invisible to both the plain extract and parse_tables; and {{cvt|50|m3/s}}
cleaned to "50" — units silently dropped everywhere.

PR-1 builds the skim's surfaces and signals (deterministic, zero LLM):

- knowledge/skim.py: skim_article() builds a per-article SkimSheet —
  section headings with term hits, table identity (caption/headers/row
  count), infobox parameter keys with resolved quantity values, link
  candidates from goal-relevant regions — from material fetch_rich
  already downloads.
- quantity-unit patterns (find_quantities): "50 m3/s" is a
  vocabulary-independent signal; the Italy discharge section's heading
  says "above 50 m3/s", never "discharge" — this finds what keyword
  search cannot.
- wiki.resolve_convert: {{convert|N|unit}} resolves to "N unit" inside
  _clean_cell BEFORE the generic template pass (which kept only the first
  argument and dropped the unit). Captions and cells keep units.
- WikiPage.wikitext: fetch_rich stores the raw source (infobox surface).
- _process_page: gated chunks are RANKED by skim signals (question + goal
  terms + quantity patterns) instead of first-N in document order.

Live smoke (real Wikipedia, no LLM): the Italy sheet shows table 2
"Rivers of Italy above 50 m3/s of average flow at the mouth", 27 rows,
quantities 50/350/239/235/187/170 m3/s; the Adige sheet shows infobox
discharge1_avg = 235 m3/s.

Tests: 6 new (knowledge/tests/skim.py), suite 35/35 green.
PR-2 (opportunistic harvest + seen-index) and PR-3 (notices to the
machine) follow.
2026-10-20 14:52:38 +02:00

348 lines
15 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 ""
CONVERT_RE = re.compile(r"\{\{(?:convert|cvt)\|([^{}]+)\}\}", re.I)
_UNIT_CANON = {"cuft/s": "cu ft/s", "ft3/s": "cu ft/s", "m³/s": "m3/s",
"km²": "km2", "mi²": "mi2"}
def resolve_convert(text: str) -> str:
"""Resolve {{convert|N|unit|...}} / {{cvt|N|unit|...}} to 'N unit'.
The primary unit is the fact; display-side secondary units are dropped
(PR-1 unit-loss fix: a caption saying 'above {{cvt|50|m3/s}}' cleaned
to 'above 50' — the unit is data, quantities carry values AND units)."""
def _one(m: re.Match) -> str:
parts = [p.strip() for p in m.group(1).split("|")]
if len(parts) < 2 or not parts[0]:
return m.group(0)
num = parts[0].rstrip(".,")
unit = parts[1].replace("\u00a0", " ").strip()
unit = unit.lower()
unit = _UNIT_CANON.get(unit, unit)
return f"{num} {unit}"
return CONVERT_RE.sub(_one, text or "")
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. convert/cvt
templates resolve to 'N unit' BEFORE the generic template pass — the
generic pass keeps only the first argument and would drop the unit."""
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)
cell = resolve_convert(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)
wikitext: str = "" # raw source (infobox params live here; PR-1)
@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. The raw wikitext stays on the page (skim's
infobox surface) and the '== Tables ==' prose block keeps units:
{{convert|N|unit}} resolves to 'N unit' (PR-1 unit-loss fix)."""
page = self.fetch(title)
wikitext = self.fetch_wikitext(title)
page.tables = parse_tables(wikitext)
page.wikitext = 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", [])]