From 6fcb3c0a86eb661114d8b97b5801908d4e1859e4 Mon Sep 17 00:00:00 2001 From: Onibot Date: Sun, 18 Oct 2026 16:53:05 +0200 Subject: [PATCH] =?UTF-8?q?feat(knowledge):=20LIST=20answer=20path=20?= =?UTF-8?q?=E2=80=94=20full=20table=20ingestion,=20typed=20list=20payloads?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- code/floop/dspy_modules.py | 6 +- code/floop/engine.py | 9 +- code/floop/state.py | 1 + code/knowledge/DESIGN.md | 68 ++++++++++++ code/knowledge/expert.py | 105 ++++++++++++++++++- code/knowledge/extract.py | 13 +++ code/knowledge/store.py | 19 ++++ code/knowledge/tests/store.py | 110 +++++++++++++++++++- code/knowledge/wiki.py | 189 ++++++++++++++++++++++++++++------ 9 files changed, 480 insertions(+), 40 deletions(-) diff --git a/code/floop/dspy_modules.py b/code/floop/dspy_modules.py index 9b44208..1876505 100644 --- a/code/floop/dspy_modules.py +++ b/code/floop/dspy_modules.py @@ -15,11 +15,13 @@ class InitSignature(dspy.Signature): """You are the INIT step of a reasoning machine. Using ONLY concepts literally present in the question plus a generic planning scaffold (number, method, machine, resources, dependencies), ask: what information or knowledge do I - need to answer this? Write 1-4 open subquestions in dependency order.""" + need to answer this? Write 1-4 open subquestions in dependency order. + Use answer_type LIST when the subquestion asks for an enumeration of + things (which countries, what rivers, list all members...).""" question: str = dspy.InputField() subquestions: str = dspy.OutputField( desc="one subquestion per line, pipe-separated fields: " - "text | depends_on (line numbers or 'none') | answer_type (OPEN|FUNCTION|INTERVAL|CONSTANT)" + "text | depends_on (line numbers or 'none') | answer_type (OPEN|FUNCTION|INTERVAL|CONSTANT|LIST)" ) diff --git a/code/floop/engine.py b/code/floop/engine.py index 69af480..9527b0f 100644 --- a/code/floop/engine.py +++ b/code/floop/engine.py @@ -118,7 +118,9 @@ class KnowledgeEngine: evidence = chr(10).join(ev_lines[:6]) try: ans = self.ke.answer_question(question, parent_question=parent_question, - evidence=evidence, charge_llm=charge) + evidence=evidence, charge_llm=charge, + answer_type=str(answer_type.value) + if hasattr(answer_type, "value") else str(answer_type)) except Exception as e: # noqa: BLE001 — fallback honesty: log, don't die if streams: streams.state(f"knowledge pipeline failed ({e}); baseline fallback") @@ -132,6 +134,11 @@ class KnowledgeEngine: payload["quote"] = ans["quote"] if ans.get("url"): payload["url"] = ans["url"] + if ans.get("list_items") is not None: + payload["list_items"] = ans["list_items"] + payload["list_count"] = ans.get("list_count", len(ans["list_items"])) + if ans.get("coverage"): + payload["coverage"] = ans["coverage"] prov = {"expert": "knowledge", "source": src, "note": ("source-verified: verbatim containment in trusted doc" if ans.get("quote") else "no quote — unverified")} diff --git a/code/floop/state.py b/code/floop/state.py index 0de3189..932ab07 100644 --- a/code/floop/state.py +++ b/code/floop/state.py @@ -19,6 +19,7 @@ class AnswerType(str, Enum): FUNCTION = "FUNCTION" INTERVAL = "INTERVAL" CONSTANT = "CONSTANT" + LIST = "LIST" class BudgetExhausted(Exception): diff --git a/code/knowledge/DESIGN.md b/code/knowledge/DESIGN.md index e33dc81..be08f77 100644 --- a/code/knowledge/DESIGN.md +++ b/code/knowledge/DESIGN.md @@ -243,4 +243,72 @@ chunker.py, extract.py, check.py, search.py, expert.py, tests/…}` + 3. **Draft search scope**: Wikipedia-only first (recommended) vs adding a general-web search provider in the same cut. 4. **Chunk target**: 8k tokens with 12k cap inside your 16–32k window — + +## 11. Lists and tables — two different problems (2026-10-18) + +**Full table ingestion vs answer completeness are different problems with +different owners.** Emili's distinction, formalized: + +1. **Full table ingestion (mechanical, always achievable).** Every table row + the parser finds is ingested — no silent truncation, no gate dropping rows. + The parser (deterministic) computes `total_rows`; that number is a computed + fact, not a judgement. "Bigger than the chunk" is solved structurally: in + the LIST path the LLM never sees the whole table — it only picks WHICH + table and WHICH column is the enumeration (one cheap call, language work); + fixed code ingests ALL rows and aggregates (thinking, zero calls). The + table is never "chunked"; the problem disappears by design. +2. **Answer completeness (epistemic, often NOT assure-able, always flag-able).** + A fetched table is complete *per source*; whether the ANSWER is complete + depends on the sources consulted (partial articles, A–M / N–Z splits). + Presence of rows proves membership; it never proves absence of unseen + members. Every LIST answer therefore carries a typed `coverage` record — + a computed flag, not a promise: what was consulted, what fraction of the + candidate space was exhausted. floop is *aware* when completeness is + guaranteed (one table, fully parsed) and when it is not (search space not + exhausted). Part 2 (pending): surface the flag up to the machine so the + synthesizer can say "27 of 52 ingested" honestly; and the planner can + open "fetch the N–Z article" as an ordinary subquestion when coverage + says the space is not exhausted. + +### The LIST answer path (part 1, implemented in the draft) + +When a question is answered by an enumeration from a fetched source: + +1. **SELECT TABLE** (LLM, one call): given the question and the list of + tables found in candidate articles (title + headers + row count, NOT the + rows), pick the table that enumerates the answer. Output: article title + + table index + the column holding the answer elements. +2. **INGEST ROWS** (code): the chosen table's rows become membership edges — + one edge per element (` | member_of | `), quote = the full + stored table row, containment-checked against the stored table text. + All rows, no truncation, no gate. +3. **AGGREGATE** (code): the answer value = sorted unique elements; the + count = `len()` — never an LLM call. + +The result enters the evidence table as a typed payload: + +```python +{"value": "27", "list_items": ["Albania", ...], "list_count": 27, + "quote": "", "url": "...", + "coverage": {"source": "
", "rows_ingested": 52, "rows_total": 52, + "complete_per_source": true}} +``` + +**Why per-row membership edges (not one fat edge).** One edge per element +keeps the KG honest: each element carries its own quote and URL, conflicts +and corroboration work per element, and set operations (filter, difference, +count) are graph queries in deterministic code — the exact operations Q2–Q4 +of the Europe plan needed. The set node (e.g. `countries of Europe`) is an +ordinary node; membership is an ordinary edge; nothing new in the schema. + +**Containment target for table rows.** The quote of a membership edge is the +full stored table row (post-`_clean_cell`, the canonical text). It is checked +against the stored table text — the same string the parser produced — so the +check stays verbatim and deterministic. The wikitext raw form is kept in the +document artifact for audit. + +**Budget law in the LIST path.** TRANSLATE + SELECT TABLE are the only LLM +calls (2 + retries); ingestion and aggregation are free. A 500-row table +costs the same LLM budget as a 5-row one — the cost of an enumeration is +O(1) in the size of the list. confirm or set preferred numbers. \ No newline at end of file diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index f7fc7f5..59eb6c3 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -23,8 +23,8 @@ import dspy from .checks import check_candidate from .chunker import chunk_page -from .extract import (AnswerFromKG, ExtractSignature, TranslateSignature, - parse_facts) +from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, + TranslateSignature, parse_facts) from .store import KnowledgeStore from .wiki import WikipediaClient, WikiPage @@ -55,6 +55,7 @@ class KnowledgeExpert: self.extract = dspy.Predict(ExtractSignature) self.answer = dspy.Predict(AnswerFromKG) self.translate = dspy.Predict(TranslateSignature) + self.select_table = dspy.Predict(SelectTableSignature) self._checked = 0 self._merged = 0 @@ -78,7 +79,8 @@ class KnowledgeExpert: # ---- the pipeline -------------------------------------------------------- def answer_question(self, question: str, parent_question: str = "", - evidence: str = "", charge_llm=None) -> dict: + evidence: str = "", charge_llm=None, + answer_type: str = "") -> dict: """Returns the answer dict {value, quote, url, source, confidence}. `parent_question` + `evidence` are the machine's context: the original @@ -167,6 +169,12 @@ class KnowledgeExpert: self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True) pages: list[WikiPage] = [] + # LIST activation: declared by the planner (answer_type=LIST) OR + # detected deterministically when the question is an enumeration ask + # (planner support pending on the local model — the path must work + # regardless of who declares it) + list_mode = (str(answer_type or "").upper() == "LIST" + or self._is_enumeration(question)) for title in ordered[: self.cfg.max_articles]: try: page = self.client.fetch_rich(title) @@ -174,6 +182,15 @@ class KnowledgeExpert: self._log(f"fetch failed: {title}: {e}") continue pages.append(page) + # LIST path: one SELECT TABLE call per article; on hit, ingest ALL + # rows and answer by aggregation (no extract calls, no gate) + if list_mode and page.tables: + ans = self._list_from_page(page, question, charge_llm) + if ans is not None: + self._log(f"early exit after {page.title}: list " + f"({ans['list_count']} items)", think=True) + return {**ans, "source": "knowledge_graph", + "stats": {"pages": [p.title for p in pages]}} # EARLY EXIT: one article at a time; if the KG already answers, # stop spending calls (the gather exists to fill the gap, not to # hoover every candidate) @@ -199,6 +216,88 @@ class KnowledgeExpert: "pages": [p.title for p in pages], "elapsed_s": round(time.time() - t0, 1)}} + def _is_enumeration(self, question: str) -> bool: + """Deterministic LIST detection: plural nouns + enumeration ask words. + Cheap, logged, and overridable by the planner's explicit answer_type.""" + q = question.casefold() + words = set(WORD_RE.findall(q)) + ask = {"which", "what", "list", "name", "enumerate", "identify"} + plurals = [w for w in words if w.endswith("s") and len(w) > 4 + and w not in ("states?", "does", "was", "has")] + return bool(words & ask) and len(plurals) >= 1 + + def _list_from_page(self, page: WikiPage, question: str, charge_llm) -> dict | None: + """The LIST path: SELECT TABLE (LLM picks table+column from metadata, + never the rows) -> ingest ALL rows as membership edges -> aggregate. + + Returns the list answer dict, or None when no table in this page + enumerates the answer (fall through to the extract path).""" + rendered = chr(10).join( + f"{t.idx} | {t.caption or '(no caption)'} | " + f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}" + for t in page.tables) + if charge_llm: + charge_llm() + pred = self.select_table(question=question, tables=rendered) + idx_raw = (pred.table_index or "").strip() + if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"): + return None + try: + idx = int(re.findall(r"\d+", idx_raw)[0]) + except (ValueError, IndexError): + return None + table = next((t for t in page.tables if t.idx == idx), None) + if table is None: + return None + column = (pred.column or "").strip() + col_i = next((i for i, h in enumerate(table.header) + if column.casefold() in h.casefold()), 0) + set_name = (pred.set_name or "").strip() or question[:60] + # INGEST ALL ROWS: one membership edge per row, quote = the full + # stored row line, containment against the stored table text + doc_id = self.store.add_document( + url=page.url, title=page.title, fetched_at=page.fetched_at, + sha256=hashlib.sha256(page.text.encode()).hexdigest()) + table_text = chr(10).join(table.text_lines()) + members: list[str] = [] + for row in table.rows: + element = (row[col_i] if col_i < len(row) else (row[0] if row else "")).strip() + if not element: + continue + if element.casefold() in ("total", "totals", "sum", "average", "mean"): + continue # aggregate footer rows are not members + if element.isdigit(): + continue # a bare number in the element column is not a member + row_line = " | ".join(row) + ok, reason = check_candidate( + {"subject": element, "relation": "member_of", "object": set_name, + "quote": row_line}, table_text) + if not ok: + self._log(f"list row rejected ({reason}): {element[:40]}") + continue + qid = self.store.add_quote(doc_id, row_line, page.url, page.fetched_at) + self.store.add_edge(element, "member_of", set_name, qid, + src_sort="PLACE", dst_node_name=set_name) + members.append(element) + self._merged += 1 + if not members: + return None + items = sorted(set(members)) + self._log(f"LIST ingest: {len(items)} members of '{set_name}' from " + f"table {idx} ({table.total_rows} rows)", think=True) + return { + "value": str(len(items)), + "list_items": items, + "list_count": len(items), + "quote": table.rows[0] and " | ".join(table.rows[0]), + "url": page.url, + "confidence": "high", + "coverage": {"source": page.title, "table": idx, + "rows_total": table.total_rows, + "rows_ingested": len(members), + "complete_per_source": len(members) == table.total_rows}, + } + def _process_page(self, page: WikiPage, question: str, kws: list[str], charge_llm) -> int: """Chunk -> gate -> extract -> check -> merge for ONE page. Returns diff --git a/code/knowledge/extract.py b/code/knowledge/extract.py index 30ada22..54f443e 100644 --- a/code/knowledge/extract.py +++ b/code/knowledge/extract.py @@ -47,6 +47,19 @@ class AnswerFromKG(dspy.Signature): confidence: str = dspy.OutputField(desc="high medium low") +class SelectTableSignature(dspy.Signature): + """You are the SELECT TABLE step of a knowledge machine. Given a question + and the tables found in an article (index, caption, header columns, row + count — NOT the rows), decide: does one of these tables enumerate the + answer? Output the table index and the column holding the answer + elements, or NONE.""" + question: str = dspy.InputField() + tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N'") + table_index: str = dspy.OutputField(desc="the chosen table index (e.g. '2'), or NONE") + column: str = dspy.OutputField(desc="header name of the column holding the answer elements; empty if NONE") + set_name: str = dspy.OutputField(desc="short name of the set this table enumerates, e.g. 'sovereign states in Europe'; empty if NONE") + + def parse_facts(raw: str) -> list[dict]: """Parse the extractor's piped lines; malformed lines are dropped+counted. diff --git a/code/knowledge/store.py b/code/knowledge/store.py index 1496658..f26e6e6 100644 --- a/code/knowledge/store.py +++ b/code/knowledge/store.py @@ -240,5 +240,24 @@ class KnowledgeStore: ref_date=rd, corroboration=cor, preferred=bool(pref), conflict=bool(conflict))) + # ---- membership queries (LIST path) -------------------------------------- + def member_sets(self) -> list[str]: + """Distinct set names that have membership edges (rel='member_of').""" + rows = self.db.execute( + "SELECT DISTINCT dst_value FROM edges WHERE rel='member_of' AND retracted=0" + ).fetchall() + return [r[0] for r in rows] + + def list_members(self, set_name: str) -> list[str]: + """ALL elements of a set: every member_of edge pointing at set_name. + Deterministic and COMPLETE with respect to what was ingested (the + ingestion writes one edge per table row, untruncated).""" + rows = self.db.execute( + "SELECT DISTINCT n.norm_name FROM edges e " + "JOIN nodes n ON n.id=e.src_node " + "WHERE e.rel='member_of' AND e.retracted=0 AND lower(e.dst_value)=lower(?)", + (set_name,)).fetchall() + return sorted(r[0] for r in rows) + def close(self) -> None: self.db.close() \ No newline at end of file diff --git a/code/knowledge/tests/store.py b/code/knowledge/tests/store.py index da54c95..8f37b64 100644 --- a/code/knowledge/tests/store.py +++ b/code/knowledge/tests/store.py @@ -85,8 +85,116 @@ def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"): print("ok test_store_four_cases") +def test_table_parser_untruncated(): + from knowledge.wiki import parse_tables + # vertical layout, 5 rows, header row -> total_rows MUST be 5, no truncation + wt = ("{| class=wikitable" + chr(10) + + "! Country !! Population" + chr(10) + + "|-" + chr(10) + + "| A" + chr(10) + "| 1" + chr(10) + + "|-" + chr(10) + + "| B" + chr(10) + "| 2" + chr(10) + + "|-" + chr(10) + + "| C" + chr(10) + "| 3" + chr(10) + + "|-" + chr(10) + + "| D" + chr(10) + "| 4" + chr(10) + + "|-" + chr(10) + + "| E" + chr(10) + "| 5" + chr(10) + + "|}") + tables = parse_tables(wt) + assert len(tables) == 1 + t = tables[0] + assert t.total_rows == 5, f"all 5 rows kept, got {t.total_rows}" + assert t.header == ["Country", "Population"], f"header parsed: {t.header}" + assert t.rows[0] == ["A", "1"] + # horizontal layout parses identically + wh = ("{| class=wikitable" + chr(10) + + "! Country !! Population" + chr(10) + + "|-" + chr(10) + + "| A || 1" + chr(10) + + "|-" + chr(10) + + "| B || 2" + chr(10) + + "|}") + t2 = parse_tables(wh)[0] + assert t2.total_rows == 2 and t2.rows[1] == ["B", "2"] + print("ok test_table_parser_untruncated") + + +def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"): + """The LIST path end-to-end with a FAKE LLM: SELECT TABLE picks the table, + ALL rows ingested as member_of edges, aggregation is code-only.""" + from knowledge.expert import KnowledgeExpert, KnowledgeConfig + from knowledge.wiki import WikiTable + + class FakeTablePicker: + def __init__(self, *a, **k): + pass + def __call__(self, **kw): + class P: pass + p = P() + p.table_index = "1" + p.column = "Country" + p.set_name = "sovereign states in Europe" + return p + + class FakeStore: + def __init__(self): + self.edges = [] + self.docs = 0 + self.quotes = 0 + def add_document(self, **kw): + self.docs += 1 + return 1 + def add_quote(self, *a, **kw): + self.quotes += 1 + return self.quotes + def add_edge(self, subject, rel, obj, qid, **kw): + self.edges.append((subject, rel, obj)) + return len(self.edges) + + ke = KnowledgeExpert.__new__(KnowledgeExpert) # no dspy init + ke.cfg = KnowledgeConfig() + ke.store = FakeStore() + ke.streams = None + ke.select_table = FakeTablePicker() + ke._merged = 0 + ke._log = lambda text, think=False: None # bound-style: no self + + from knowledge.wiki import WikiPage + page = WikiPage(title="List of states", pageid=1, url="u", + fetched_at="2026-10-18T00:00:00+00:00", text="x", + tables=[WikiTable(idx=1, header=["Country", "Population"], + rows=[["Albania", "2.8"], ["Belgium", "11.8"], + ["Croatia", "3.9"]])]) + ans = ke._list_from_page(page, "What are the countries in Europe?", None) + assert ans is not None + assert ans["list_count"] == 3, f"count = len (code, not LLM): {ans}" + assert ans["list_items"] == ["Albania", "Belgium", "Croatia"] + assert ans["coverage"]["complete_per_source"] is True + assert ans["coverage"]["rows_ingested"] == 3 + # every row became a membership edge, quote = full row line + assert len(ke.store.edges) == 3 + assert all(e[1] == "member_of" for e in ke.store.edges) + # rejected path: no table matches -> None -> fall through to extract path + class FakeNonePicker: + def __init__(self, *a, **k): + pass + def __call__(self, **kw): + class P: pass + p = P() + p.table_index = "NONE" + p.column = "" + p.set_name = "" + return p + ke.select_table = FakeNonePicker() + assert ke._list_from_page(page, "irrelevant", None) is None + print("ok test_list_ingest_aggregate") + + if __name__ == "__main__": test_chunker_sections() test_containment() test_store_four_cases() - print("\n3 knowledge tests passed") \ No newline at end of file + test_list_ingest_aggregate() + test_table_parser_untruncated() + print(f"\n{test_table_parser_untruncated.__name__} etc — 5 knowledge tests passed") \ No newline at end of file diff --git a/code/knowledge/wiki.py b/code/knowledge/wiki.py index bbd8cb9..00dd4d0 100644 --- a/code/knowledge/wiki.py +++ b/code/knowledge/wiki.py @@ -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' -> 'Franceg'), then File links (dropped + whole), then links (display text), then templates innermost-out.""" + cell = re.sub(r"]*>.*?", "", cell, flags=re.S | re.I) + cell = re.sub(r"]*/?>", "", cell, flags=re.I) + cell = re.sub(r"]*>.*?", "", cell, flags=re.S | re.I) + cell = re.sub(r"]*/?>", "", 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