diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index 3e1c1a6..e39b554 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -23,6 +23,7 @@ import dspy from .checks import check_candidate, quote_containment from .chunker import chunk_page +from .skim import find_quantities, skim_article from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, TranslateSignature, VerifyCountSignature, parse_facts) from .store import KnowledgeStore, norm_name @@ -132,6 +133,8 @@ class KnowledgeExpert: if evidence: context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}" kws = self._keywords(question) + goal_terms = self._keywords(parent_question) if parent_question else [] + ev_entities = [e for e in self._expected_entities(evidence or "")][:8] # LIST activation (moved up: the set gate needs it before the probe) list_mode = (str(answer_type or "").upper() == "LIST" or self._is_enumeration(question)) @@ -230,6 +233,14 @@ class KnowledgeExpert: self._log(f"fetch failed: {title}: {e}") continue pages.append(page) + # SKIM (PR-1): the structural read, in passing — question AND goal + # oriented; surfaces + signals, zero LLM. The sheet drives chunk + # ranking in _process_page (PR-2 wires its harvest + notices). + sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms, + evidence_entities=ev_entities) + self._log(f"skim {page.title}: {len(sheet.tables)} tables, " + f"{len(sheet.infobox_quantities)} infobox quantities, " + f"{len(sheet.link_candidates)} link candidates", think=True) # 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: @@ -244,7 +255,8 @@ class KnowledgeExpert: # stop spending calls (the gather exists to fill the gap, not to # hoover every candidate). For enumerations the set gate applies # here too: mention rows never answer a list question. - self._process_page(page, question, kws, charge_llm) + self._process_page(page, question, kws, charge_llm, + goal_terms=goal_terms) if list_mode: hit = self._set_gate_hit(probe_seeds, question) if hit is not None: @@ -460,14 +472,32 @@ class KnowledgeExpert: } def _process_page(self, page: WikiPage, question: str, kws: list[str], - charge_llm) -> int: - """Chunk -> gate -> extract -> check -> merge for ONE page. Returns - number of candidates merged this page. Counters ACCUMULATE on self.""" + charge_llm, goal_terms: list[str] | None = None) -> int: + """Chunk -> gate -> RANK (skim) -> extract -> check -> merge for ONE + page. Returns number of candidates merged this page. Counters + ACCUMULATE on self. + + PR-1: chunks are RANKED by skim signals (question terms + goal terms + + quantity-unit patterns) instead of taking the first N in document + order — the Italy run burned its extract slots on tangential chunks + while the discharge table sat later in the document. A chunk without + ANY signal is skipped for free.""" chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target, cap=self.cfg.chunk_chars_cap) - gated = [c for c in chunks if self._gate(c, kws)][: self.cfg.max_chunks_extracted] - self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated in") - for chunk in gated: + gated = [c for c in chunks if self._gate(c, kws)] + if goal_terms: + from .store import stem + + def rank(c) -> tuple[int, int]: + low = c.text.casefold() + sig = sum(1 for t in set(kws + goal_terms) + if t and (t in low or stem(t) in low)) + return (sig + 2 * len(find_quantities(c.text)), -c.idx) + gated.sort(key=rank, reverse=True) + capped = gated[: self.cfg.max_chunks_extracted] + self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated, " + f"{len(capped)} extracted (skim-ranked)", think=True) + for chunk in capped: if charge_llm: charge_llm() raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text) diff --git a/code/knowledge/skim.py b/code/knowledge/skim.py new file mode 100644 index 0000000..e933ea0 --- /dev/null +++ b/code/knowledge/skim.py @@ -0,0 +1,201 @@ +"""Skim: the fast structural read of a fetched article, in passing. + +KNOWLEDGE.md §7. Every article the gather fetches is skimmed — headings, +tables, infobox params, term hits — oriented to the current question AND +the run goal, so information seen in passing is not thrown away when the +call returns. All deterministic, zero LLM, built from material fetch_rich +already downloads. + +Outputs of this module: +- SkimSheet: the per-article record (headings, tables, infobox, term hits, + link candidates) — surfaces + signals only, never content decisions. +- quantity patterns: `50 m3/s`, `1,460 m3/s` — unit signals that find + material where the vocabulary cannot (the Italy discharge table's heading + says "above 50 m3/s", never "discharge"). +- the infobox surface: parameter keys + resolved quantity values parsed + from the page wikitext (where Adige's discharge lives — invisible to the + plain extract and to parse_tables). +""" +from __future__ import annotations + +import re +from dataclasses import dataclass, field + +from .wiki import resolve_convert + +# --- quantity-unit patterns (the vocabulary-independent signal) ------------ +# number (with , or . thousands, optional decimals) followed by a unit token +_QTY_RE = re.compile( + r"\b(\d{1,3}(?:[.,]\d{3})*(?:\.\d+)?)" # number, , thousands, opt decimals + r"[\s\u00a0-]*(m3/s|m³/s|cu\s*ft/s|cuft/s|ft3/s" + r"|km2|km²|km|mi2|mi²|mi|kg|mm|cm|m|s|%)\b", + re.I) + + +def _canon_unit(u: str) -> str: + """Canonical unit display form (wiki.resolve_convert's stored forms).""" + u = u.lower().replace("\u00a0", " ").strip() + return {"cuft/s": "cu ft/s", "ft3/s": "cu ft/s", "m³/s": "m3/s", + "km²": "km2", "mi²": "mi2"}.get(u, u) + + +def find_quantities(text: str) -> list[str]: + """All quantity+unit spans in text (normalized: '1,460 m3/s').""" + out: list[str] = [] + for m in _QTY_RE.finditer(text or ""): + out.append(f"{m.group(1)} {_canon_unit(m.group(2))}") + return out + + +# --- the skim sheet --------------------------------------------------------- + +@dataclass +class SkimTable: + """A table as the skim sees it: identity + signals, never rows.""" + idx: int + caption: str = "" + header: list[str] = field(default_factory=list) + rows_total: int = 0 + quantities: list[str] = field(default_factory=list) + hits: int = 0 # term hits across caption+header + + def describe(self) -> str: + cap = resolve_convert(self.caption) or "(no caption)" + return (f"table {self.idx}: {cap} | header: " + f"{', '.join(self.header[:6])} | rows: {self.rows_total}") + + +@dataclass +class SkimSection: + title: str + hits: int = 0 + quantities: list[str] = field(default_factory=list) + + +@dataclass +class SkimSheet: + title: str + url: str + headings: list[SkimSection] = field(default_factory=list) + tables: list[SkimTable] = field(default_factory=list) + infobox_keys: list[str] = field(default_factory=list) + infobox_quantities: dict[str, str] = field(default_factory=dict) + link_candidates: list[str] = field(default_factory=list) + + def notice(self) -> str: + """Compact notice for the machine (payload['skim']). One line: + tables seen (identity + signal), infobox quantity params, link + candidates — what a later step could come back for.""" + parts = [] + if self.tables: + parts.append("; ".join(t.describe() for t in self.tables[:3])) + if self.infobox_quantities: + parts.append("infobox: " + ", ".join( + f"{k}={v}" for k, v in list(self.infobox_quantities.items())[:4])) + if self.link_candidates: + parts.append("linked: " + ", ".join(self.link_candidates[:6])) + return f"{self.title}: " + " | ".join(parts) if parts else "" + + +HEADING_RE = re.compile(r"^(={2,6})\s*(.+?)\s*\1\s*$", re.M) +INFOBOX_RE = re.compile(r"\{\{[Ii]nfobox\s+([^|{}]+)(.*?)\n\}\}", re.S) +PARAM_RE = re.compile(r"^\s*\|\s*([A-Za-z0-9_]+)\s*=\s*(.*)$", re.M) +LINK_RE = re.compile(r"\[\[([^\]|]+)(?:\|[^\]]*)?\]\]") + + +def _hits(text: str, terms: list[str]) -> int: + """Count distinct term hits (stem-level, casefolded) in text.""" + from .store import stem + low = (text or "").casefold() + n = 0 + for t in terms: + if t and (t in low or stem(t) in low): + n += 1 + return n + + +def _norm_entities(entities: list[str]) -> list[str]: + from .store import norm_name + return [norm_name(e) for e in entities if len(e) > 2] + + +def skim_article(page, question_terms: list[str], goal_terms: list[str], + evidence_entities: list[str]) -> SkimSheet: + """Build the skim sheet for one fetched WikiPage. + + `page` is a knowledge/wiki.WikiPage (text + tables + wikitext, as + fetch_rich returns since PR-1). Terms: words/stems of the CURRENT + question, of the RUN GOAL, and entities already in evidence. + Deterministic; no LLM.""" + sheet = SkimSheet(title=page.title, url=page.url) + all_terms = [t for t in set(question_terms + goal_terms) if len(t) > 2] + ent_terms = _norm_entities(evidence_entities) + + # headings + per-section signals (regex positions, level-agnostic) + text = page.text or "" + marks = [(m.start(), m.end(), m.group(2)) + for m in HEADING_RE.finditer(text)] + sections: list[tuple[str, str, str]] = [] # (title, body, start) + for i, (start, end, title) in enumerate(marks): + body_end = marks[i + 1][0] if i + 1 < len(marks) else len(text) + sections.append((title, text[end:body_end], text[start:body_end])) + for title, body, _full in sections: + sheet.headings.append(SkimSection( + title=title, + hits=_hits(title + " " + body, all_terms + ent_terms), + quantities=find_quantities(body))) + # preamble (before first heading) — quantities only + pre = text[:marks[0][0]] if marks else text + if find_quantities(pre): + sheet.headings.append(SkimSection(title="(preamble)", hits=0, + quantities=find_quantities(pre))) + + # tables: caption/headers/row-count + quantity signals + for t in getattr(page, "tables", None) or []: + cap = t.caption or "" + ttext = "\n".join(t.text_lines()) + qtys = find_quantities(resolve_convert(cap)) + find_quantities(ttext) + seen: list[str] = [] + for q in qtys: + if q not in seen: + seen.append(q) + sheet.tables.append(SkimTable( + idx=t.idx, caption=cap, header=list(t.header), + rows_total=t.total_rows, quantities=seen[:10], + hits=_hits(cap + " " + " ".join(t.header), all_terms))) + + # infobox: parameter keys + quantity values (units resolved) — from the + # page wikitext (fetch_rich stores it since PR-1); pages without one are + # skipped honestly + wt = getattr(page, "wikitext", "") or "" + m = INFOBOX_RE.search(wt) + if m: + keys, quants = [], {} + for pm in PARAM_RE.finditer(m.group(2)): + key, val = pm.group(1), pm.group(2).strip() + keys.append(key) + resolved = resolve_convert(val) + if resolved != val: # a {{convert}} value: quantity + quants[key] = resolved + elif find_quantities(val): # bare number+unit in the param + quants[key] = find_quantities(val)[0] + sheet.infobox_keys = keys + sheet.infobox_quantities = quants + + # links inside goal-relevant regions (harvest candidates, capped at 12): + # a region is goal-relevant when its title or body hits a goal term or + # carries a quantity signal (the Italy case: the signal '50 m3/s' lives + # IN the section heading, the body below it holds the table's links) + links: list[str] = [] + for title, body, _full in sections: + if goal_terms and (_hits(title + " " + body, goal_terms) > 0 + or find_quantities(title + " " + body)): + for lm in LINK_RE.finditer(body): + target = lm.group(1).split("#")[0].strip() + if (target and target not in links + and ":" not in target[:6]): # skip File:/etc ns + links.append(target) + if len(links) >= 12: + break + sheet.link_candidates = links[:12] + return sheet \ No newline at end of file diff --git a/code/knowledge/tests/skim.py b/code/knowledge/tests/skim.py new file mode 100644 index 0000000..da8345f --- /dev/null +++ b/code/knowledge/tests/skim.py @@ -0,0 +1,125 @@ +"""Skim tests (PR-1): quantities, convert resolution, infobox surface, +skim sheet signals on a synthetic page, chunk ranking. +No network, no LLM. Run: uv run python knowledge/tests/skim.py +""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/ +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) + +from knowledge.skim import (SkimSheet, find_quantities, skim_article) +from knowledge.wiki import WikiPage, WikiTable, parse_tables, resolve_convert +from knowledge.expert import KnowledgeExpert, KnowledgeConfig + + +def test_find_quantities(): + assert find_quantities("the river carries 1,460 m3/s at its mouth") == ["1,460 m3/s"] + assert find_quantities("above 50 m³/s of average flow") == ["50 m3/s"] + assert find_quantities("52,000 cu ft/s (1,460 m3/s)") == ["52,000 cu ft/s", "1,460 m3/s"] + assert find_quantities("a rank 1 river of 652 km length") == ["652 km"] + assert find_quantities("no numbers here") == [] + print("ok test_find_quantities") + + +def test_resolve_convert(): + assert resolve_convert("above {{cvt|50|m3/s}} of flow") == "above 50 m3/s of flow" + assert resolve_convert("{{convert|235|m3/s|cuft/s|abbr=on}}") == "235 m3/s" + assert resolve_convert("{{convert|1540|cuft/s|m3/s|abbr=on}}") == "1540 cu ft/s" + assert resolve_convert("no template") == "no template" + # unit survives the FULL cell-clean pipeline (the root bug: caption + # cleaned to 'above 50', the unit silently dropped) + from knowledge.wiki import _clean_cell + assert _clean_cell("Rivers above {{cvt|50|m3/s}}") == "Rivers above 50 m3/s" + print("ok test_resolve_convert") + + +def test_infobox_surface(): + wt = ("{{Infobox river | river_name = Adige\n" + " | discharge1_avg = {{convert|235|m3/s|cuft/s|abbr=on}}\n" + " | discharge1_max = 1,200 m3/s\n" + " | mouth = [[Adriatic Sea]]\n" + "}}") + page = WikiPage(title="Adige", pageid=1, url="u", text="== Course ==\nIt flows east.", + fetched_at="t", wikitext=wt) + sheet = skim_article(page, question_terms=["discharge"], goal_terms=["water flow"], + evidence_entities=[]) + assert sheet.infobox_quantities.get("discharge1_avg") == "235 m3/s", sheet.infobox_quantities + assert sheet.infobox_quantities.get("discharge1_max") == "1,200 m3/s" + assert "discharge1_avg" in sheet.infobox_keys + print("ok test_infobox_surface") + + +def test_table_surface_and_notice(): + tables = parse_tables( + "{| class=\"wikitable\"\n|+ Rivers above {{cvt|50|m3/s}}\n" + "! Rank !! River !! Flow at the mouth\n|-\n" + "| 1 || Po || 1540\n|-\n| 4 || Adige || 235\n|}") + page = WikiPage(title="List of rivers of Italy", pageid=1, url="u", + text=("== List of Italian rivers above 50 m3/s (1,800 cu ft/s) ==\n" + "The Po discharges 1,460 m3/s."), + fetched_at="t", tables=tables, wikitext="") + sheet = skim_article(page, question_terms=["longest", "rivers"], + goal_terms=["water", "flow"], evidence_entities=["Po", "Adige"]) + assert len(sheet.tables) == 1 + t = sheet.tables[0] + assert t.rows_total == 2 + assert t.quantities and any("m3/s" in q for q in t.quantities), t.quantities + assert any("50 m3/s" in h.quantities[0] or h.quantities for h in sheet.headings + if h.title.startswith("List of Italian")), sheet.headings + n = sheet.notice() + assert "table 1" in n and "rows: 2" in n, n + print("ok test_table_surface_and_notice") + + +def test_link_candidates_goal_regions(): + body = ("== List of Italian rivers above 50 m3/s ==\n" + "The largest is the [[Po (river)|Po]]; the second is the [[Adige]].\n") + page = WikiPage(title="List of rivers of Italy", pageid=1, url="u", + text=body, fetched_at="t", wikitext="") + sheet = skim_article(page, question_terms=["rivers"], goal_terms=["flow"], + evidence_entities=[]) + assert "Po (river)" in sheet.link_candidates, sheet.link_candidates + assert "Adige" in sheet.link_candidates + print("ok test_link_candidates_goal_regions") + + +def test_chunk_ranking_by_skim(): + """The PR-1 behaviour change: gated chunks are RANKED (question + goal + terms + quantities), not taken in document order.""" + import inspect + src = inspect.getsource(KnowledgeExpert._process_page) + assert "goal_terms" in src, "ranking must be wired to goal terms" + # behavioural: rank puts the quantity-bearing chunk first + from knowledge.chunker import chunk_page + text = ("== Geography ==\nItaly is a country in Southern Europe with a long" + " Mediterranean coastline. The climate is varied across regions.\n\n" + "== Hydrology ==\nRiver flow: the Po carries 1,460 m3/s, the Tiber 239 m3/s.\n") + page = WikiPage(title="X", pageid=1, url="u", text=text, fetched_at="t") + expert = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init + expert.cfg = KnowledgeConfig() + expert._log = lambda *a, **k: None + from knowledge.store import stem + from knowledge.skim import find_quantities as fq + chunks = chunk_page(text, target=1000, cap=2000) + gated = [c for c in chunks if expert._gate(c, ["po"])] + goal_terms = ["water", "flow"] + def rank(c): + low = c.text.casefold() + sig = sum(1 for t in set(["po"] + goal_terms) if t and (t in low or stem(t) in low)) + return (sig + 2 * len(fq(c.text)), -c.idx) + gated.sort(key=rank, reverse=True) + assert "Hydrology" in gated[0].heading_path, [c.heading_path for c in gated] + print("ok test_chunk_ranking_by_skim") + + +if __name__ == "__main__": + test_find_quantities() + test_resolve_convert() + test_infobox_surface() + test_table_surface_and_notice() + test_link_candidates_goal_regions() + test_chunk_ranking_by_skim() + print("\nskim PR-1 tests passed") \ No newline at end of file diff --git a/code/knowledge/wiki.py b/code/knowledge/wiki.py index 373932c..5f2d301 100644 --- a/code/knowledge/wiki.py +++ b/code/knowledge/wiki.py @@ -157,12 +157,37 @@ def _tpl_arg(content: str) -> str: 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:
variants become ' / ' separators FIRST (multi-value name cells like 'Albania
Republic of Albania
ALB' must not - concatenate), then refs, File links, links, templates.""" + 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"", " / ", cell, flags=re.I) cell = re.sub(r"]*>.*?", "", cell, flags=re.S | re.I) cell = re.sub(r"]*/?>", "", cell, flags=re.I) @@ -170,6 +195,7 @@ def _clean_cell(cell: str) -> str: 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) + cell = resolve_convert(cell) while "{{" in cell: new = re.sub(r"\{\{([^{}]*)\}\}", lambda mm: _tpl_arg(mm.group(1)), cell) if new == cell: @@ -206,6 +232,7 @@ class WikiPage: 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]: @@ -299,10 +326,13 @@ class WikipediaClient: """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.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