Files
floop/code/knowledge/skim.py
onibot 1ebb4cfc0d knowledge: PR-3 skim notices to the loop + bounded lead promotion
PR-1 made the skim SEE (surfaces + signals); PR-2 made it HARVEST
deterministically. PR-3 closes the loop (KNOWLEDGE.md §7):

- Skim notices: every knowledge answer's stats carry what the fetched
  articles contained beyond the answer (table identities, infobox
  quantities, link candidates, goal-filtered). The engine copies them
  into payload['skim']; the machine renders them to the ROUTER context
  ('seen in passing (E1): ...') and to the run notes — later steps know
  what exists and where it lives instead of re-searching blind. A notice
  is a pointer, never evidence: it answers nothing by itself.
- Bounded lead promotion (Emili's 'deterministic + LLM fallback'):
  quantity tables that match NO goal word are queued as leads (PR-2);
  now ONE dspy call (SkimPromoteSignature) decides over the tables'
  IDENTITY lines (caption/headers/rows/quantities — never the rows),
  per fetched page with leads, only when leads exist. The LLM proposes;
  fixed code disposes: a promoted table still passes the entity-overlap
  check (a world discharge table is refused for Po/Adige/Tiber), the
  named column must exist, and ingestion goes through the same
  containment-checked _ingest_scalar_table as the deterministic path.
- Refactor: row ingestion extracted to _ingest_scalar_table (shared by
  harvest + promotion); _entity_overlap_count shared; skim state
  (_skim_notices/_skim_leads/_current_goal_question) reset per call.
- find_quantities: fix plain-digit quantities ('1540 m3/s', '1000 m3/s')
  — the thousands-separator-only regex missed them, and caption+header
  now join with a space ('m3/sRiver' broke the unit boundary).

Live smoke (real Wikipedia, scripted decision): goal terms without
'flow' queue both Italy tables as leads; the promoted 'Flow at the
mouth' table ingests all 27 rivers (Po 1540, Adige 235, Tiber 239
m3/s) containment-checked; promotion of the length table with a
'Flow' column name is refused (column does not exist).

Tests: 4 new (knowledge/tests/promote.py); suite 43/43 green.
2026-10-20 16:24:43 +02:00

202 lines
8.2 KiB
Python

"""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 (thousands with , or ., optional decimals; OR plain digits — '1540'
# and '1000' carry no thousands separator) followed by a unit token
_QTY_RE = re.compile(
r"\b(\d{1,3}(?:[.,]\d{3})*(?:\.\d+)?|\d+(?:\.\d+)?)"
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