mod tokens;
pub use tokens::{NAMED_TOKENIZERS, TokenCounter, estimate};
use super::json::plain_text::{block_plain, plain_of};
use super::plain;
use crate::model::{Block, BlockKind, Document};
use serde::Serialize;
const PATH_SEPARATOR: &str = " > ";
const BLOCK_SEPARATOR: &str = "\n\n";
const JOIN_SLACK_TOKENS: usize = 1;
const CELL_SEPARATOR: &str = " | ";
#[derive(Debug, Clone)]
pub struct ChunkOptions {
pub max_tokens: usize,
pub counter: TokenCounter,
}
impl Default for ChunkOptions {
fn default() -> Self {
Self {
max_tokens: 512,
counter: TokenCounter::estimate(),
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Chunk {
pub id: usize,
pub text: String,
pub tokens: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub section: Vec<String>,
pub blocks: Vec<usize>,
pub pages: Vec<usize>,
}
pub fn render_chunks(doc: &Document, opts: &ChunkOptions) -> Vec<Chunk> {
let mut builder = Builder::new(opts, doc.meta.title.clone());
let mut headings: Vec<(u8, String)> = Vec::new();
for block in &doc.blocks {
if let BlockKind::Heading { level } = block.kind {
builder.flush();
while headings.last().is_some_and(|&(open, _)| open >= level) {
headings.pop();
}
headings.push((level, plain_of(&block.spans)));
continue;
}
let text = block_text(block);
if text.is_empty() {
continue;
}
builder.enter(headings.iter().map(|(_, heading)| heading.clone()).collect());
builder.add_block(block, &text);
}
builder.flush();
builder.chunks
}
pub fn chunks_jsonl(chunks: &[Chunk]) -> String {
let mut out = String::new();
for chunk in chunks {
out.push_str(&serde_json::to_string(chunk).expect("a chunk serialises"));
out.push('\n');
}
out
}
fn block_text(block: &Block) -> String {
let BlockKind::Figure { .. } = block.kind else {
return block_plain(block).unwrap_or_default().trim().to_string();
};
let mut parts = vec![plain_of(&block.spans)];
match &block.table {
Some(table) => parts.extend(table.rows.iter().map(|row| {
row.iter()
.map(|cell| plain_of(&cell.spans))
.collect::<Vec<_>>()
.join(CELL_SEPARATOR)
})),
None => parts.extend(block.rows.first().map(|row| plain(row))),
}
parts.retain(|part| !part.trim().is_empty());
parts.join("\n").trim().to_string()
}
struct Builder<'a> {
opts: &'a ChunkOptions,
title: Option<String>,
chunks: Vec<Chunk>,
section: Vec<String>,
head: String,
body: Vec<String>,
blocks: Vec<usize>,
pages: Vec<usize>,
}
impl<'a> Builder<'a> {
fn new(opts: &'a ChunkOptions, title: Option<String>) -> Self {
Self {
opts,
title,
chunks: Vec::new(),
section: Vec::new(),
head: String::new(),
body: Vec::new(),
blocks: Vec::new(),
pages: Vec::new(),
}
}
fn enter(&mut self, section: Vec<String>) {
if section == self.section {
return;
}
self.flush();
let head = section.join(PATH_SEPARATOR);
self.head = if self.count(&head) * 2 > self.opts.max_tokens {
String::new()
} else {
head
};
self.section = section;
}
fn add_block(&mut self, block: &Block, text: &str) {
let room = self
.opts
.max_tokens
.saturating_sub(self.head_tokens() + JOIN_SLACK_TOKENS)
.max(1);
let pieces = if self.count(text) > room {
split_long(text, room, &self.opts.counter)
} else {
vec![text.to_string()]
};
for piece in pieces {
if !self.body.is_empty() && self.count(&self.text_with(&[&piece])) > self.opts.max_tokens {
self.flush();
}
self.body.push(piece);
if self.blocks.last() != Some(&block.id) {
self.blocks.push(block.id);
}
if !self.pages.contains(&block.page) {
self.pages.push(block.page);
}
}
}
fn flush(&mut self) {
if self.body.is_empty() {
return;
}
let text = self.text_with(&[]);
self.pages.sort_unstable();
self.chunks.push(Chunk {
id: self.chunks.len(),
tokens: self.count(&text),
text,
title: self.title.clone(),
section: self.section.clone(),
blocks: std::mem::take(&mut self.blocks),
pages: std::mem::take(&mut self.pages),
});
self.body.clear();
}
fn text_with(&self, more: &[&str]) -> String {
let body = self.body.iter().map(String::as_str).chain(more.iter().copied());
std::iter::once(self.head.as_str())
.filter(|head| !head.is_empty())
.chain(body)
.collect::<Vec<_>>()
.join(BLOCK_SEPARATOR)
}
fn head_tokens(&self) -> usize {
if self.head.is_empty() {
0
} else {
self.count(&format!("{}{BLOCK_SEPARATOR}", self.head))
}
}
fn count(&self, text: &str) -> usize {
self.opts.counter.count(text)
}
}
fn split_long(text: &str, budget: usize, counter: &TokenCounter) -> Vec<String> {
let mut pieces = Vec::new();
let mut current = String::new();
for sentence in sentences(text) {
let candidate = if current.is_empty() {
sentence.to_string()
} else {
format!("{current} {sentence}")
};
if counter.count(&candidate) <= budget {
current = candidate;
continue;
}
if !current.is_empty() {
pieces.push(std::mem::take(&mut current));
}
let mut rest = sentence;
while counter.count(rest) > budget {
let (head, tail) = cut(rest, budget, counter);
pieces.push(head.to_string());
rest = tail;
}
current = rest.to_string();
}
if !current.is_empty() {
pieces.push(current);
}
pieces
}
fn sentences(text: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut start = 0;
let mut prev: Option<char> = None;
let mut chars = text.char_indices().peekable();
while let Some((i, ch)) = chars.next() {
if ch.is_whitespace() && prev.is_some_and(|last| matches!(last, '.' | '!' | '?')) {
let mut end_ws = i + ch.len_utf8();
while let Some(&(j, next)) = chars.peek() {
if !next.is_whitespace() {
break;
}
end_ws = j + next.len_utf8();
chars.next();
}
let next = text[end_ws..].chars().next();
if next
.is_some_and(|first| first.is_ascii_uppercase() || first.is_ascii_digit() || matches!(first, '(' | '['))
{
out.push(&text[start..i]);
start = end_ws;
}
prev = Some(' ');
continue;
}
prev = Some(ch);
}
out.push(&text[start..]);
out.retain(|sentence| !sentence.trim().is_empty());
out
}
fn cut<'t>(text: &'t str, budget: usize, counter: &TokenCounter) -> (&'t str, &'t str) {
let mut ends: Vec<usize> = text
.char_indices()
.filter(|&(i, ch)| ch.is_whitespace() && i > 0 && !text[..i].ends_with(char::is_whitespace))
.map(|(i, _)| i)
.collect();
if ends.first().is_none_or(|&end| counter.count(&text[..end]) > budget) {
ends = text.char_indices().skip(1).map(|(i, _)| i).collect();
}
let fits = ends.partition_point(|&end| counter.count(&text[..end]) <= budget);
let end = if fits == 0 {
ends.first().copied().unwrap_or(text.len())
} else {
ends[fits - 1]
};
(text[..end].trim_end(), text[end..].trim_start())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Span;
fn block(id: usize, kind: BlockKind, text: &str) -> Block {
let mut block = Block::new(id, kind);
block.spans = vec![Span::plain(text)];
block
}
fn doc(blocks: Vec<Block>) -> Document {
Document {
meta: crate::model::Meta {
title: Some("A Paper".into()),
..Default::default()
},
pages: Vec::new(),
body_size: 10.0,
leading: 12.0,
body_font: String::new(),
math_font: String::new(),
blocks,
pictures: Vec::new(),
}
}
#[test]
fn chunks_follow_sections_and_carry_their_path() {
let doc = doc(vec![
block(0, BlockKind::Heading { level: 1 }, "1 Intro"),
block(1, BlockKind::Paragraph { in_abstract: false }, "First."),
block(2, BlockKind::Heading { level: 2 }, "1.1 More"),
block(3, BlockKind::Paragraph { in_abstract: false }, "Second."),
]);
let chunks = render_chunks(&doc, &ChunkOptions::default());
assert_eq!(chunks.len(), 2);
assert_eq!(chunks[0].text, "1 Intro\n\nFirst.");
assert_eq!(chunks[1].text, "1 Intro > 1.1 More\n\nSecond.");
assert_eq!(chunks[1].section, ["1 Intro", "1.1 More"]);
assert_eq!(chunks[1].blocks, [3]);
assert_eq!(chunks[1].title.as_deref(), Some("A Paper"));
}
#[test]
fn blocks_of_a_section_share_a_chunk_until_it_is_full() {
let para = |id| block(id, BlockKind::Paragraph { in_abstract: false }, "one two three four");
let doc = doc(vec![
block(0, BlockKind::Heading { level: 1 }, "S"),
para(1),
para(2),
para(3),
]);
let opts = ChunkOptions {
max_tokens: 9,
..Default::default()
};
let chunks = render_chunks(&doc, &opts);
assert_eq!(
chunks.iter().map(|chunk| chunk.blocks.clone()).collect::<Vec<_>>(),
[vec![1, 2], vec![3]]
);
assert!(chunks.iter().all(|chunk| chunk.tokens <= 9));
}
#[test]
fn a_long_block_is_cut_at_sentence_ends() {
let pieces = split_long("One two. Three four. Five six.", 6, &TokenCounter::estimate());
assert_eq!(pieces, ["One two. Three four.", "Five six."]);
}
#[test]
fn a_long_sentence_is_cut_between_words() {
let pieces = split_long("a b c d e", 2, &TokenCounter::estimate());
assert_eq!(pieces, ["a b", "c d", "e"]);
}
#[test]
fn abbreviations_before_lower_case_do_not_end_sentences() {
assert_eq!(
sentences("See e.g. the table. Then go."),
["See e.g. the table.", "Then go."]
);
}
}