knowledge/: wiki.py (official MediaWiki API, own session+UA; fetch_rich appends wikitext tables as text - plain extracts drop them), chunker.py (section-aware, level paths), checks.py (verbatim containment, quote-aware), store.py (SQLite append-only, 4 contradiction cases, probe by entity AND relation with stemming), extract.py (dspy Signatures: TRANSLATE resolves pronouns from context and emits queries+entities, EXTRACT per chunk, ANSWER from KG rows), expert.py (the pipeline: KG-first probe -> gap -> translate -> search -> fetch_rich -> chunk -> gate -> extract -> check -> merge -> re-probe -> answer). Wiring: KnowledgeEngine in floop/engine.py (machine injects charge+modules at call time; baseline fallback on pipeline failure), machine routes knowledge questions to it, config.yaml knowledge: block. E2E verified live: Loire length answered from KG with zero network; the 2-hop EU-river question resolved France (population table row quote) -> Loire (KG hit) in 12 calls/75s. Six live-run bugs closed (wiki lib 403/HTML, dropped tables, pipes-in-quotes parse, gate stemming, relation probe, pronoun context). RUNLOG Run C added; code/README honest map updated. Tests 17/17.
78 lines
2.5 KiB
Python
78 lines
2.5 KiB
Python
"""Section-aware chunker for Wikipedia plain-text extracts.
|
|
|
|
The MediaWiki extract keeps headings as '== Section ==' / '=== Sub ===' lines.
|
|
Each chunk = one (sub)section; a chunk never mixes sections, so its heading
|
|
path is always honest. A section longer than the cap is split at sentence
|
|
boundaries; all its pieces carry the same path.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass
|
|
|
|
HEADING_RE = re.compile(r"^(={2,6})\s*(.+?)\s*\1\s*$", re.M)
|
|
SENTENCE_RE = re.compile(r"(?<=[.!?])\s+(?=[A-Z\"'(])")
|
|
|
|
|
|
@dataclass
|
|
class Chunk:
|
|
idx: int
|
|
heading_path: str # e.g. "Course > Upper Loire"
|
|
text: str # the chunk body
|
|
char_start: int # offset into the full text
|
|
|
|
|
|
def _split_long(text: str, cap: int) -> list[str]:
|
|
"""Split a too-long section at sentence boundaries into <=cap pieces."""
|
|
if len(text) <= cap:
|
|
return [text]
|
|
sentences = SENTENCE_RE.split(text)
|
|
out: list[str] = []
|
|
cur = ""
|
|
for s in sentences:
|
|
if cur and len(cur) + len(s) + 1 > cap:
|
|
out.append(cur)
|
|
cur = s
|
|
else:
|
|
cur = f"{cur} {s}".strip()
|
|
if cur:
|
|
out.append(cur)
|
|
return out
|
|
|
|
|
|
def chunk_page(text: str, target: int = 32000, cap: int = 48000) -> list[Chunk]:
|
|
"""Split a plain-text extract into one chunk per (sub)section.
|
|
|
|
`target` packs nothing (kept for API compat); `cap` guards the extraction
|
|
call size. Sizes in CHARS (draft: ~4 chars/token).
|
|
"""
|
|
marks = [(m.start(), m.end(), len(m.group(1)), m.group(2))
|
|
for m in HEADING_RE.finditer(text)]
|
|
chunks: list[Chunk] = []
|
|
|
|
def add(path: str, body: str, start: int) -> None:
|
|
if not body.strip():
|
|
return
|
|
for j, piece in enumerate(_split_long(body, cap)):
|
|
chunks.append(Chunk(idx=len(chunks), heading_path=path,
|
|
text=piece, char_start=start))
|
|
|
|
if not marks:
|
|
add("", text, 0)
|
|
return chunks
|
|
|
|
# preamble (before first heading)
|
|
if marks[0][0] > 0:
|
|
add("", text[: marks[0][0]], 0)
|
|
|
|
# walk headings maintaining a level stack -> honest paths
|
|
stack: list[tuple[int, str]] = [] # (level, title)
|
|
for i, (h_start, h_end, level, title) in enumerate(marks):
|
|
while stack and stack[-1][0] >= level:
|
|
stack.pop()
|
|
stack.append((level, title))
|
|
next_start = marks[i + 1][0] if i + 1 < len(marks) else len(text)
|
|
body = text[h_end:next_start]
|
|
add(" > ".join(t for _, t in stack), body, h_start)
|
|
|
|
return chunks |