kakemono 0.15.0

Convert scientific-paper PDFs (arXiv) and Word documents into clean, readable HTML in four fidelity modes, Word documents, Markdown, LaTeX or EPUB books
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Chunks output: the text of the document cut into pieces ready to embed
//! for retrieval (RAG), one JSON object per line (`.jsonl`).
//!
//! Chunks follow the structure of the document: blocks are grouped by
//! section, a chunk never holds two sections, and a block is cut only when
//! it does not fit in one chunk (at sentence ends, else between words).
//! Each chunk starts with its section path ("3 Model > 3.2 Attention"), so
//! that a piece of text keeps the context a reader has. The paper title is
//! not repeated in the text: retrieval within one paper gains nothing from
//! it, and measured on Qasper (100 papers, two embedding models) a title on
//! every chunk lost 3 to 5 points of evidence recall. It is in each chunk's
//! metadata instead, to filter or prefix when searching several papers.
//!
//! Figures and tables give their caption and, for a rebuilt table, its rows
//! (cells joined by ` | `); formulas are written as `$$LaTeX$$` when their
//! structure is known. Pictures are left out.

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;

/// Separator of the parts of a section path in a chunk's text.
const PATH_SEPARATOR: &str = " > ";

/// Separator between the section path and the text, and between blocks.
const BLOCK_SEPARATOR: &str = "\n\n";

/// Tokens kept free in a chunk for the break before a piece: counts are
/// not quite additive (the estimate counts the space before a number, real
/// tokenizers merge across the break).
const JOIN_SLACK_TOKENS: usize = 1;

/// Separator between the cells of a table row.
const CELL_SEPARATOR: &str = " | ";

/// Everything that controls how a document is cut into chunks.
#[derive(Debug, Clone)]
pub struct ChunkOptions {
    /// Largest size of a chunk, in tokens, section path included.
    pub max_tokens: usize,
    /// How tokens are counted: an estimate by default (see
    /// [`TokenCounter`]).
    pub counter: TokenCounter,
}

impl Default for ChunkOptions {
    /// At most 512 tokens, the input limit of most embedding models,
    /// counted by the estimate.
    fn default() -> Self {
        Self {
            max_tokens: 512,
            counter: TokenCounter::estimate(),
        }
    }
}

/// One chunk: its text and where it comes from.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Chunk {
    /// Number of the chunk, in reading order, from 0.
    pub id: usize,
    /// The text to embed: the section path, a blank line, then the text of
    /// the blocks, separated by blank lines.
    pub text: String,
    /// Size of `text` in tokens, as [`ChunkOptions::counter`] counts them.
    pub tokens: usize,
    /// Title of the document.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Headings of the sections the chunk is in, outermost first; empty
    /// before the first heading.
    pub section: Vec<String>,
    /// Ids of the blocks the text comes from (the `id` of the JSON output).
    pub blocks: Vec<usize>,
    /// Pages the text is on, from 0.
    pub pages: Vec<usize>,
}

/// Cuts a document into chunks.
pub fn render_chunks(doc: &Document, opts: &ChunkOptions) -> Vec<Chunk> {
    let mut builder = Builder::new(opts, doc.meta.title.clone());
    // The headings open above the current block: (level, text).
    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
}

/// The chunks as JSON Lines: one object per line, each line ending with a
/// line break.
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
}

/// The text of one block as a reader (or a language model) reads it; empty
/// for a block without text.
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()
}

/// Builds the chunks one block at a time.
struct Builder<'a> {
    /// The options.
    opts: &'a ChunkOptions,
    /// Title of the document, copied into each chunk.
    title: Option<String>,
    /// The chunks written so far.
    chunks: Vec<Chunk>,
    /// Headings of the current section, outermost first.
    section: Vec<String>,
    /// The section path at the start of the current chunk's text (empty
    /// when it is left out).
    head: String,
    /// The texts of the current chunk.
    body: Vec<String>,
    /// Ids of the blocks of the current chunk.
    blocks: Vec<usize>,
    /// Pages of the current chunk.
    pages: Vec<usize>,
}

impl<'a> Builder<'a> {
    /// An empty builder.
    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(),
        }
    }

    /// Moves to the section `section`: a new section starts a new chunk.
    /// The section path heads the chunks of the section, unless it takes
    /// more than half of a chunk.
    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;
    }

    /// Adds the text of `block` to the chunks, cut into pieces when it does
    /// not fit in one.
    fn add_block(&mut self, block: &Block, text: &str) {
        // What a chunk holds besides its section path, less the token that
        // the break before a piece can cost (before a number).
        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);
            }
        }
    }

    /// Ends the current chunk, if it has text.
    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();
    }

    /// The text of the current chunk with `more` pieces added: the section
    /// path, then the pieces.
    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)
    }

    /// Tokens taken by the section path at the start of a chunk.
    fn head_tokens(&self) -> usize {
        if self.head.is_empty() {
            0
        } else {
            self.count(&format!("{}{BLOCK_SEPARATOR}", self.head))
        }
    }

    /// The number of tokens of `text`.
    fn count(&self, text: &str) -> usize {
        self.opts.counter.count(text)
    }
}

/// Cuts `text` into pieces of at most `budget` tokens: whole sentences
/// where they fit, a sentence longer than the budget between words, and a
/// word longer than the budget between characters.
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
}

/// The sentences of `text`: it is cut at white space that follows `.`, `!`
/// or `?` and comes before a capital, a digit or an opening bracket, so
/// that "e.g. the" and "Fig. 2a" are not cut while "end. The" is (a cut
/// after an abbreviation before a capital is harmless).
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
}

/// Cuts `text` (more than `budget` tokens) into its longest head of at most
/// `budget` tokens and the rest: between words, or between characters when
/// the first word alone is too long. The head is never empty.
fn cut<'t>(text: &'t str, budget: usize, counter: &TokenCounter) -> (&'t str, &'t str) {
    // Ends of the candidate heads: after each word, else after each char.
    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();
    }
    // The count grows with the head: find the last end that fits.
    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;

    /// A block of `kind` with `text`, on page 0.
    fn block(id: usize, kind: BlockKind, text: &str) -> Block {
        let mut block = Block::new(id, kind);
        block.spans = vec![Span::plain(text)];
        block
    }

    /// A document titled "A Paper" with these blocks.
    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()
        };
        // "S" + two paragraphs of 4 tokens = 9 tokens; the third goes on.
        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() {
        // Each word and each full stop is one token: two sentences make 6.
        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."]
        );
    }
}