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.
125 lines
5.9 KiB
Python
125 lines
5.9 KiB
Python
"""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") |