Files
floop/code/knowledge/wiki.py
T
onibot 109885773c knowledge: typed Fact extraction via dspy native structured output
His direction: stop explaining string formats to the LLM and parsing
them back with Python — that's exactly what dspy does natively and
better. The pipe format ('subject | relation | object | quote') was
fragile (run-L verbose values, pipe-in-quote ambiguity, STOP_TABLE
string protocol).

THE CHANGE (extractor only, PR-10 scope):
- Fact(BaseModel) with subject/relation/object/quote OutputFields
- ExtractSignature.facts: list[Fact] — the adapter renders the JSON
  schema into the prompt itself (verified in a live run's prompt log)
  and parses responses back into typed Fact objects
- STOP_TABLE string protocol -> stop: bool OutputField
- expert.py consumes typed objects; the cand dict is built at the
  check_candidate boundary only (checks.py unchanged)
- parse_facts/parse_stop_table kept as LEGACY for existing tests only

VERIFIED:
- dspy 3.4.1 pattern E2E'd first with a raw-text engine: list[Fact]
  parses back as Fact objects, schema rendered in prompt (tmp probes)
- full suite 12/12 green (74 tests) — tablefrags.py updated to script
  typed Fact objects
- live E2E run (ollama-cloud glm-5.3-flash, Italy rivers): correct
  Po/Adige/Tiber answer; prompt log shows the native JSON schema;
  table rows ingested cleanly (22 rows, quotes verbatim)

NEXT (his direction, not this PR): apply the same typed-output law to
ALL floop signatures — INIT subquestions, ROUTE engine choice,
AnswerFromKG, SelectTable, SkimPromote, Translate, VerifyCount.
2026-10-22 14:21:13 +02:00

407 lines
17 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] = []
raw_marks: list[bool] = [] # per-cell '!' marker seen (mixed rows)
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:
# mixed row ('!' first cell + '|' data cells) is a DATA
# row — a data row's leading !scope="row" th is a row
# LABEL, not a header (run-G bug: the world rivers table
# turned into 1,825 'header' cells and zero rows)
header = row_is_header and all(raw_marks)
flush_row(raw_cells, header)
raw_cells, raw_marks = [], []
row_is_header = False
continue
if line.startswith("!"):
raw_cells.extend(re.split(r"!!", line.lstrip("!")))
raw_marks.extend([True] * len(re.split(r"!!", line.lstrip("!"))))
row_is_header = True
continue
if line.startswith("|"):
cells = re.split(r"\|\|", line.lstrip("|"))
raw_cells.extend(cells)
raw_marks.extend([False] * len(cells))
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 and all(raw_marks))
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
CITATION_TPL = ("cref", "cref2", "efn", "sfn", "fn", "citation", "cite", "note",
"refn", "anchor")
def tables_as_chunks(wikitext: str, max_tables: int = 3,
rows_per_chunk: int = 40) -> list[dict]:
"""Tables for the EXTRACT path, as small structured fragments — never a
22k-char table dump (run G, call 8/80).
Every fragment REPEATS THE HEADER: the extractor must be able to tell
'troç 2/10' — which table, which columns — from the fragment alone.
The first fragment of a table also carries the caption, so the extract
LLM can early-skip a table whose SUBJECT is already hopeless (world
rivers vs Italy) without reading all fragments.
"""
frags: list[dict] = []
for t in parse_tables(wikitext, max_tables=max_tables):
rows = t.rows
n_total = max(1, -(-len(rows) // rows_per_chunk)) # ceil
for j in range(0, len(rows), rows_per_chunk):
part = j // rows_per_chunk
frag = {
"table_idx": t.idx,
"caption": t.caption or "",
"header": t.header,
"part": part + 1,
"of": n_total,
"rows": rows[j: j + rows_per_chunk],
}
frags.append(frag)
return frags
def format_table_frag(frag: dict) -> str:
"""Render a fragment for the extractor: header + caption + part marker +
rows, one 'a | b | c' line per row. The extractor sees WHICH table it is
in, so it can answer STOP_TABLE when rows cannot contain the answer."""
head = " | ".join(frag["header"]) if frag["header"] else "(no header)"
caption = f"caption: {frag['caption']}" if frag["caption"] else ""
part = f"table {frag['table_idx']} — part {part_of(frag)}" if frag["of"] > 1 else (
f"table {frag['table_idx']}")
lines = [l if isinstance(l, str) else " | ".join(l) for l in frag["rows"]]
out = [caption] if caption else []
out += [part, head, "rows:"] + lines
return chr(10).join(out)
def part_of(frag: dict) -> str:
return f"{frag['part']}/{frag['of']}"
def parse_stop_table(out_text: str) -> bool:
"""LEGACY textual STOP_TABLE detector — kept only for tests. Production
code reads the typed `stop: bool` field of ExtractSignature."""
return "STOP_TABLE" in (out_text or "").upper()[:80]
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). The raw wikitext
stays on the page (skim's infobox surface) and {{convert|N|unit}}
resolves to 'N unit' (PR-1 unit-loss fix).
NO '== Tables ==' prose enrichment anymore: a 226-row table flattened
into page.text became one 22k-char chunk that hung the extract call
(run G, call 8/80) and let verify_count cite the table as 'prose'.
Tables now reach the extract path as small per-table fragments
(tables_as_chunks), and the LIST/harvest paths read page.tables
directly."""
page = self.fetch(title)
wikitext = self.fetch_wikitext(title)
page.tables = parse_tables(wikitext)
page.wikitext = wikitext
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", [])]