fix(knowledge): cold-start gather — vertical tables, global rank, early exit

Emili's home run failed where the VPS seemed to work: warm-KG illusion; cold path never validated. Reproduced with a wiped KG. Fixes: (1) tables_as_text parses BOTH wikitext layouts (horizontal pipes and one-cell-per-line with row separators) + _clean_cell drops attrs/links/templates; (2) gather searches all queries, dedupes, ranks globally by title relevance, fetches ONE article at a time with EARLY EXIT when the KG answers; (3) hybrid order keeps each query's top-1 slot guaranteed (title relevance buries entity pages like 'Loire'). Also: NameError from refactor caught by baseline fallback; counters accumulate. Cold E2E verified: France (table quote) -> Loire (early exit, 1 article) in 2hops. RUNLOG Run D.
This commit is contained in:
2026-10-17 10:39:34 +02:00
parent 9094b2aec0
commit 6db05fef48
3 changed files with 162 additions and 53 deletions
+31 -13
View File
@@ -23,33 +23,51 @@ LANG = "en"
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str:
"""Parse wikitext tables into plain text rows. Used by fetch_rich so
ranking/list articles (whose data lives in tables, not prose) carry
their facts; containment is checked against the ENRICHED text."""
"""Parse wikitext tables into one text line per row ('cell | cell | cell').
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] = []
for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S):
if len(out) >= max_tables:
break
rows: list[str] = []
cells: list[str] = []
for line in m.group(1).splitlines():
line = line.strip()
if re.fullmatch(r"\|-?", line): # wikitext row separator, not a cell
if not line or line.startswith("|+"): # blank / caption
continue
if line.startswith("!") or line.startswith("|"):
cells = [c.strip().lstrip("!|").strip() for c in line.split("||")]
cells = [re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\}\}", "", c) for c in cells]
cells = [re.sub(r"<[^>]+>", "", c).replace("!!", " ").strip() for c in cells if c]
if line.startswith("|-") or line.startswith("!-"): # row separator
if cells:
rows.append(" | ".join(cells))
if len(rows) >= max_rows:
break
cells = []
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))
out.append(chr(10).join(rows[:max_rows]))
return (chr(10) * 2).join(out)
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)
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")
class WikiError(RuntimeError):
pass