Chunking

Structure-aware Markdown chunking and boundary-quality scoring.

Use md_chunks_structural (or md_chunks_structural_batch for a corpus with one GIL release) to split Markdown hierarchically at parsed top-level block boundaries. md_chunks_greedy uses a local boundary-and-length score, md_chunks implements the original heading/paragraph splitter, and score_chunks evaluates chunk boundary quality against a target word count.

chunks = md_chunks_structural("# A\n\nFirst section.\n\n## B\n\nSecond section.", target_words=5)
assert len(chunks) == 2 and chunks[0]["start"] == "h1" and chunks[1]["start"] == "h2"
assert score_chunks(chunks, target_words=5)["start_score"] == 0.0

All functions raise ValueError on non-positive target_words or length_scale, and score_chunks raises ValueError on an empty chunk list or unknown start label.

md_chunks_structural

def md_chunks_structural(
    markdown:str, # Markdown document text
    target_words:int=700, # Target visible word count per chunk (must be positive)
)->list[dict]: # List of `{'md': str, 'start': str}` chunk dicts (`start` is `'h1'`..`'h6'` or `'body'`)

Split markdown hierarchically, cutting only at parsed top-level block boundaries.

md_chunks_structural_batch

def md_chunks_structural_batch(
    markdowns:Iterable[str], # Sequence or iterable of Markdown documents
    target_words:int=700, # Target visible word count per chunk
    batch_size:int=128, # Documents processed per Rust GIL release
)->list[list[dict]]: # Per-document lists of `{'md': str, 'start': str}` chunk dicts

Chunk a batch of Markdown documents structurally with one GIL release per batch.

md_chunks_greedy

def md_chunks_greedy(
    markdown:str, # Markdown document text
    target_words:int=700, # Target visible word count per chunk
    length_scale:int=200, # Word-count scale trading off chunk length against boundary penalty
)->list[dict]: # List of `{'md': str, 'start': str}` chunk dicts

Split markdown at parsed block boundaries using a local length-and-boundary score.

md_chunks

def md_chunks(
    markdown:str, # Markdown document text
    target_words:int=700, # Target visible word count per chunk
)->list[dict]: # List of `{'md': str, 'start': str}` chunk dicts

Split markdown hierarchically using the original heading/paragraph algorithm.

score_chunks

def score_chunks(
    chunks:Iterable[dict], # Non-empty iterable of `{'md': str, 'start': str}` chunk dicts
    target_words:int=700, # Target visible word count per chunk
    length_scale:int=50, # Divisor scaling mean absolute word-count error
    start_penalties:dict | None=None, # Custom start-boundary penalty map (defaults to `START_PENALTIES`)
)->dict: # Dict with `score`, `start_score`, `length_score`, `lengths`, `starts`, `max_length`

Score chunk quality by mean start-boundary penalty plus scaled mean absolute target-length error.