knowledge: PR-1 skim surfaces — read articles in passing (KNOWLEDGE §7)
The Italy run (Run G) failed with the data in hand: Q1's LIST ingest
early-exited on the length table and discarded the same article's 27-row
discharge table; the Adige/Tiber discharges live in infobox templates,
invisible to both the plain extract and parse_tables; and {{cvt|50|m3/s}}
cleaned to "50" — units silently dropped everywhere.
PR-1 builds the skim's surfaces and signals (deterministic, zero LLM):
- knowledge/skim.py: skim_article() builds a per-article SkimSheet —
section headings with term hits, table identity (caption/headers/row
count), infobox parameter keys with resolved quantity values, link
candidates from goal-relevant regions — from material fetch_rich
already downloads.
- quantity-unit patterns (find_quantities): "50 m3/s" is a
vocabulary-independent signal; the Italy discharge section's heading
says "above 50 m3/s", never "discharge" — this finds what keyword
search cannot.
- wiki.resolve_convert: {{convert|N|unit}} resolves to "N unit" inside
_clean_cell BEFORE the generic template pass (which kept only the first
argument and dropped the unit). Captions and cells keep units.
- WikiPage.wikitext: fetch_rich stores the raw source (infobox surface).
- _process_page: gated chunks are RANKED by skim signals (question + goal
terms + quantity patterns) instead of first-N in document order.
Live smoke (real Wikipedia, no LLM): the Italy sheet shows table 2
"Rivers of Italy above 50 m3/s of average flow at the mouth", 27 rows,
quantities 50/350/239/235/187/170 m3/s; the Adige sheet shows infobox
discharge1_avg = 235 m3/s.
Tests: 6 new (knowledge/tests/skim.py), suite 35/35 green.
PR-2 (opportunistic harvest + seen-index) and PR-3 (notices to the
machine) follow.
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user