"""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