Files
rag-lab/src/raglab/chunking.py
T
2026-10-28 20:44:22 +07:00

88 lines
2.5 KiB
Python

"""Markdown-aware chunking with overlap.
The splitter respects headings and paragraph boundaries first, then falls back
to a hard window with overlap. Every chunk keeps its heading trail so that a
retrieved fragment is readable on its own.
"""
from __future__ import annotations
import hashlib
import re
from dataclasses import dataclass
HEADING = re.compile(r"^(#{1,6})\s+(.*)$")
SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
@dataclass(frozen=True)
class Chunk:
id: str
doc_id: str
title: str
text: str
meta: dict
def _split_long(text: str, target: int, overlap: int) -> list[str]:
if len(text) <= target:
return [text]
sentences = SENTENCE_END.split(text)
parts: list[str] = []
current = ""
for sentence in sentences:
candidate = f"{current} {sentence}".strip()
if len(candidate) <= target:
current = candidate
continue
if current:
parts.append(current)
current = sentence
while len(current) > target:
parts.append(current[:target])
current = current[target - overlap:]
if current:
parts.append(current)
return parts
def chunk_markdown(doc_id: str, text: str, target: int = 900, overlap: int = 120) -> list[Chunk]:
title = ""
trail: list[str] = []
blocks: list[tuple[str, str]] = []
buffer: list[str] = []
def flush() -> None:
body = "\n".join(buffer).strip()
if body:
header = " > ".join(trail) if trail else title
blocks.append((header, body))
buffer.clear()
for line in text.splitlines():
heading = HEADING.match(line)
if heading:
flush()
level = len(heading.group(1))
name = heading.group(2).strip()
if level == 1 and not title:
title = name
trail = trail[: level - 1] + [name]
continue
buffer.append(line)
flush()
chunks: list[Chunk] = []
for header, body in blocks:
for piece in _split_long(body, target, overlap):
digest = hashlib.sha1(f"{doc_id}|{header}|{piece}".encode("utf-8")).hexdigest()[:16]
chunks.append(
Chunk(
id=f"{doc_id}:{digest}",
doc_id=doc_id,
title=header or title or doc_id,
text=piece.strip(),
meta={"chars": len(piece)},
)
)
return chunks