Cut Where the Meaning Changes
Split a document where its meaning changes instead of every N words. Implement semantic_chunks(sentences, embed, percentile=90, min_size=2, max_size=8), which returns the chunks as lists of consecutive sentences, in order. embed(sentence) returns a vector (a stand-in for an embedding model); distance(u, v), the cosine distance, is provided.
- Gaps. Embed every sentence and take the distance between each sentence and the next:
nsentences given - 1gaps. - Threshold. The
percentile-th percentile of this document's gaps by nearest rank: sort the gaps ascending and take the one at 1-based rankceil(percentile * len(gaps) / 100), at least 1. - Cut between two sentences when their gap is strictly greater than the threshold. A gap equal to the threshold is not a cut.
- Too small. While there is more than one chunk and some chunk has fewer than
min_sizesentences, take the first such chunk and merge it with a neighbour: the one across its smaller gap (the earlier neighbour when its two gaps are equal). The first chunk can only merge forward, the last only back. - Too big. Then split every chunk longer than
max_sizeinto pieces ofmax_sizesentences from its start; the last piece keeps the rest, however short. - No sentences give
[]; one sentence gives one chunk.
The catch. The threshold is not a fixed distance. Embedding models differ, and so do documents: the shifts in a page that jumps from baking to taxes are far apart, the shifts inside one contract are close. Taking the percentile over the gaps of the document being split cuts each document at its own largest shifts: about the top (100 - percentile) percent of its gaps.