feat(knowledge): LIST answer path — full table ingestion, typed list payloads

Part 1 of the lists design (DESIGN.md §11): mechanical full ingestion, separated from epistemic answer-completeness. parse_tables rewritten as a GRID parser: cells accumulate until |- (both layouts), empty cells kept as placeholders (image cells clean to ''; dropping them shifted France rows to start at 'FRA'), rowspan/colspan expanded at placement, total_rows is the computed extent — no truncation. _clean_cell: refs/sup/File links dropped, citation templates (cref2/efn...) resolve empty, links take display text, attrs split first. LIST path in expert.py: deterministic enumeration detection OR planner-declared LIST; SELECT TABLE (one LLM call over table metadata, never rows); ingest ALL rows as member_of edges (quote = full row line, containment against stored table text); aggregate via len() — no LLM. AnswerType.LIST added; evidence payloads carry list_items + coverage. Verified live cold: 50 sovereign states from the Europe article table (51 rows - Total footer), every member with verbatim quote. 19/19 tests.
This commit is contained in:
2026-10-18 16:53:10 +02:00
parent a78f65de2c
commit 6fcb3c0a86
9 changed files with 480 additions and 40 deletions
+156 -33
View File
@@ -22,65 +22,184 @@ 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').
@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)
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] = []
@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(out) >= max_tables:
if len(tables) >= max_tables:
break
rows: list[str] = []
cells: list[str] = []
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 or line.startswith("|+"): # blank / caption
if not line:
continue
if line.startswith("|-") or line.startswith("!-"): # row separator
if cells:
rows.append(" | ".join(cells))
cells = []
if line.startswith("|+"): # caption
t.caption = _clean_cell(line[2:])
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]))
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
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 ([[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)
"""Resolve links/templates to display text; drop refs, File links, tags.
Order matters: refs with content first (else their text leaks into the
value — 'France<ref name=g/>' -> 'Franceg'), then File links (dropped
whole), then links (display text), then templates innermost-out."""
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, verbatim-preserving."""
"""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]:
@@ -171,10 +290,14 @@ class WikipediaClient:
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."""
"""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)
extra = tables_as_text(self.fetch_wikitext(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