docling-core 2.94.2

Core DoclingDocument data model and serializers for docling.rs (a Rust port of docling).
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
//! Splitting an oversized Markdown-table chunk (#1269) — docling-core's
//! `HybridChunker.segment` table path under `repeat_table_header=True`,
//! `omit_header_on_overflow=False` (its defaults): the table's header row and
//! separator repeat atop every piece (`LineBasedTokenChunker` with the header
//! as its prefix), and a table whose rows do not fit beside the header is cut
//! by columns into complete sub-tables (`_split_table_by_columns`), since
//! cutting a row mid-cell would leave an invalid Markdown fragment.
//!
//! The triplet form keeps the older prefix-less line splitter in the parent
//! module: its serializer has no header lines, so the two agree there.

use super::ChunkTokenizer;

/// docling-core's `MARKDOWN_SEPARATOR_ROW_RE`: `^\|(\s*:?-+:?\s*\|)+\s*$`.
fn is_separator_row(line: &str) -> bool {
    let Some(mut rest) = line.strip_prefix('|') else {
        return false;
    };
    let mut cells = 0usize;
    loop {
        let t = rest.trim_start();
        let t = t.strip_prefix(':').unwrap_or(t);
        let dashes = t.len() - t.trim_start_matches('-').len();
        if dashes == 0 {
            break;
        }
        let t = &t[dashes..];
        let t = t.strip_prefix(':').unwrap_or(t);
        let t = t.trim_start();
        match t.strip_prefix('|') {
            Some(r) => {
                cells += 1;
                rest = r;
            }
            None => break,
        }
    }
    cells > 0 && rest.trim().is_empty()
}

/// `str.splitlines(True)` for `\n`-separated text: every line keeps its
/// terminator, a trailing unterminated line is kept, no empty tail.
fn lines_keep_ends(text: &str) -> Vec<String> {
    text.split_inclusive('\n').map(str::to_string).collect()
}

/// `MarkdownTableSerializer.get_header_and_body_lines`: the line before the
/// first separator row and the separator are the header, everything after
/// it the body; no separator (or one on the first line) — no header.
pub(super) fn header_and_body_lines(table_text: &str) -> (Vec<String>, Vec<String>) {
    let all = lines_keep_ends(table_text);
    match all
        .iter()
        .position(|l| is_separator_row(l.strip_suffix('\n').unwrap_or(l)))
    {
        None | Some(0) => (Vec::new(), all),
        Some(sep) => (all[sep - 1..=sep].to_vec(), all[sep + 1..].to_vec()),
    }
}

/// `HybridChunker.segment` for a chunk whose one item is a Markdown table:
/// the pieces of `text`, each within `available` tokens where the tokenizer
/// allows it.
pub(super) fn segment<T: ChunkTokenizer>(text: &str, available: usize, tok: &T) -> Vec<String> {
    let (header, body) = header_and_body_lines(text);
    let preamble = match header.first().and_then(|h| text.find(h.as_str())) {
        Some(start) if start > 0 => text[..start].to_string(),
        _ => String::new(),
    };
    let table_prefix: String = header.concat();
    let full_prefix = format!("{preamble}{table_prefix}");
    // Concatenated counts, not sums: token counts are not additive.
    let any_row_overflows = body
        .iter()
        .any(|line| tok.count_tokens(&format!("{table_prefix}{line}")) > available);
    if any_row_overflows {
        return split_by_columns(&header, &body, &preamble, available, tok);
    }
    let segments = LineChunker::new(tok, available, full_prefix.clone()).chunk_text(&body);
    strip_repeated_preamble(segments, &preamble, &full_prefix)
}

/// The preamble (a caption ahead of the header) counts against every
/// piece's budget but is printed on the first piece only.
fn strip_repeated_preamble(segments: Vec<String>, preamble: &str, prefix: &str) -> Vec<String> {
    if preamble.is_empty() {
        return segments;
    }
    segments
        .into_iter()
        .enumerate()
        .map(|(i, s)| {
            if i > 0 && s.starts_with(prefix) {
                s[preamble.len()..].to_string()
            } else {
                s
            }
        })
        .collect()
}

/// `_split_table_by_columns`'s `parse_cells`: a row's cells, split on the
/// `|`s an even number of backslashes precede, each trimmed.
fn parse_cells(row: &str) -> Vec<String> {
    let mut line = row.trim();
    if line.is_empty() {
        return Vec::new();
    }
    line = line.strip_prefix('|').unwrap_or(line);
    if let Some(inner) = line.strip_suffix('|') {
        let backslashes = inner.len() - inner.trim_end_matches('\\').len();
        if backslashes % 2 == 0 {
            line = inner;
        }
    }
    let mut cells = Vec::new();
    let mut current = String::new();
    let mut bs = 0usize;
    for ch in line.chars() {
        match ch {
            '\\' => {
                bs += 1;
                current.push(ch);
            }
            '|' if bs % 2 == 1 => {
                current.push(ch);
                bs = 0;
            }
            '|' => {
                cells.push(current.trim().to_string());
                current.clear();
                bs = 0;
            }
            _ => {
                bs = 0;
                current.push(ch);
            }
        }
    }
    cells.push(current.trim().to_string());
    cells
}

/// `_split_table_by_columns`: column slices of the table, each a complete
/// compact sub-table (header, `| - |` separator, rows). A slice takes as
/// many columns as fit *all* rows in one piece; when not even one column
/// does (a tall table), as many as fit each row beside the header, and the
/// rows of that slice are packed line by line under the repeated header.
/// The preamble opens the first piece only.
fn split_by_columns<T: ChunkTokenizer>(
    header: &[String],
    body: &[String],
    preamble: &str,
    available: usize,
    tok: &T,
) -> Vec<String> {
    let header_rows: Vec<Vec<String>> = header
        .iter()
        .filter(|l| !is_separator_row(l.strip_suffix('\n').unwrap_or(l)))
        .map(|l| parse_cells(l))
        .collect();
    let body_rows: Vec<Vec<String>> = body
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| parse_cells(l))
        .collect();
    let n_cols = header_rows
        .iter()
        .chain(&body_rows)
        .map(Vec::len)
        .min()
        .unwrap_or(0);
    if n_cols == 0 {
        // Malformed: the body rows without a header.
        return vec![body.concat()];
    }
    let row_line = |row: &[String], a: usize, b: usize| format!("| {} |\n", row[a..b].join(" | "));
    let build_header = |a: usize, b: usize, with_preamble: bool| -> String {
        let mut s = String::new();
        if with_preamble {
            s.push_str(preamble);
        }
        for h in &header_rows {
            s.push_str(&row_line(h, a, b));
        }
        s.push_str(&format!("| {} |\n", vec!["-"; b - a].join(" | ")));
        s
    };
    let build_subtable = |a: usize, b: usize, with_preamble: bool| -> String {
        let mut s = build_header(a, b, with_preamble);
        for r in &body_rows {
            s.push_str(&row_line(r, a, b));
        }
        s
    };
    let rows_fit_with_header = |a: usize, b: usize, with_preamble: bool| -> bool {
        let hdr = build_header(a, b, with_preamble);
        if tok.count_tokens(&hdr) >= available {
            return false;
        }
        body_rows
            .iter()
            .all(|r| tok.count_tokens(&format!("{hdr}{}", row_line(r, a, b))) <= available)
    };
    // The largest `end` in `start+1..=n_cols` passing `fits` (monotone).
    let largest = |start: usize, fits: &dyn Fn(usize) -> bool| -> Option<usize> {
        let (mut lo, mut hi) = (start + 1, n_cols);
        let mut best = None;
        while lo <= hi {
            let mid = (lo + hi) / 2;
            if fits(mid) {
                best = Some(mid);
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        best
    };

    let mut segments = Vec::new();
    let mut start = 0usize;
    let mut first = true;
    while start < n_cols {
        let all_rows = largest(start, &|end| {
            tok.count_tokens(&build_subtable(start, end, first)) <= available
        });
        if let Some(end) = all_rows {
            segments.push(build_subtable(start, end, first));
            start = end;
        } else {
            let end =
                largest(start, &|end| rows_fit_with_header(start, end, first)).unwrap_or(start + 1);
            let sub_header = build_header(start, end, first);
            let lines: Vec<String> = body_rows.iter().map(|r| row_line(r, start, end)).collect();
            let mut pieces =
                LineChunker::new(tok, available, sub_header.clone()).chunk_text(&lines);
            if first {
                pieces = strip_repeated_preamble(pieces, preamble, &sub_header);
            }
            segments.extend(pieces);
            start = end;
        }
        first = false;
    }
    segments
}

/// docling-core's `LineBasedTokenChunker.chunk_text` with a prefix and
/// `omit_prefix_on_overflow=False`: lines are packed whole under the prefix,
/// a line is cut only when it does not fit even a fresh chunk, and a prefix
/// that alone fills the budget is emitted once, split, ahead of prefix-less
/// chunks.
struct LineChunker<'t, T: ChunkTokenizer> {
    tok: &'t T,
    max: usize,
    prefix: String,
    /// The prefix's tokens when it fits a chunk with room to spare, else 0
    /// (the prefix is then not repeated).
    prefix_len: usize,
}

impl<'t, T: ChunkTokenizer> LineChunker<'t, T> {
    fn new(tok: &'t T, max: usize, prefix: String) -> Self {
        let prefix_len = if prefix.is_empty() {
            0
        } else {
            let n = tok.count_tokens(&prefix);
            if n >= max {
                0
            } else {
                n
            }
        };
        Self {
            tok,
            max,
            prefix,
            prefix_len,
        }
    }

    fn count(&self, s: &str) -> usize {
        self.tok.count_tokens(s)
    }

    /// The prefix a fresh chunk starts with.
    fn fresh(&self) -> &str {
        if self.prefix_len > 0 {
            &self.prefix
        } else {
            ""
        }
    }

    fn chunk_text(&self, lines: &[String]) -> Vec<String> {
        let mut chunks: Vec<String> = Vec::new();
        let mut current = String::new();
        let mut current_len = 0usize;
        if !self.prefix.is_empty() && self.prefix_len == 0 {
            // The prefix alone overflows: its own pieces first, then the
            // lines without it.
            chunks.extend(
                LineChunker::new(self.tok, self.max, String::new())
                    .chunk_text(std::slice::from_ref(&self.prefix)),
            );
        } else {
            current = self.prefix.clone();
            current_len = self.prefix_len;
        }
        for line in lines {
            let mut remaining = line.clone();
            loop {
                if self.count(&format!("{current}{remaining}")) <= self.max {
                    current.push_str(&remaining);
                    current_len = self.count(&current);
                    break;
                }
                let fresh = self.fresh().to_string();
                if self.count(&format!("{fresh}{remaining}")) <= self.max {
                    if !current.is_empty() {
                        chunks.push(std::mem::take(&mut current));
                    }
                    current = fresh;
                    current_len = self.prefix_len;
                    continue;
                }
                // Too large even for a fresh chunk: cut off what fits.
                let available = self.max.saturating_sub(current_len);
                let (mut take, mut rest) =
                    split_by_token_limit(&remaining, available, "", self.tok);
                while !take.is_empty() && self.count(&format!("{current}{take}")) > self.max {
                    let limit = self.count(&take).saturating_sub(1);
                    let (t, returned) = split_by_token_limit(&take, limit, "", self.tok);
                    take = t;
                    rest = format!("{returned}{rest}");
                }
                if take.is_empty() {
                    let (t, r) = split_by_token_limit(&rest, self.max, &current, self.tok);
                    take = t;
                    rest = r;
                }
                if take.is_empty() {
                    if !current.is_empty() && current != self.fresh() {
                        chunks.push(std::mem::take(&mut current));
                        current = self.fresh().to_string();
                        current_len = self.prefix_len;
                        remaining = rest;
                        continue;
                    }
                    // Not one character fits beside the prefix (docling
                    // raises here): emit it alone rather than fail or spin.
                    let mut chars = rest.chars();
                    take = chars.next().map(String::from).unwrap_or_default();
                    rest = chars.as_str().to_string();
                    if take.is_empty() {
                        break;
                    }
                }
                current.push_str(&take);
                chunks.push(std::mem::take(&mut current));
                current = self.fresh().to_string();
                current_len = self.prefix_len;
                remaining = rest;
                if remaining.is_empty() {
                    break;
                }
            }
        }
        if !current.is_empty() && (self.prefix_len == 0 || current != self.prefix) {
            chunks.push(current);
        }
        chunks
    }
}

/// `LineBasedTokenChunker._split_by_token_limit` (word boundary preferred):
/// the longest char-prefix `head` of `text` with `prefix + head` within
/// `limit` tokens, snapped back to its last space when that still fits.
fn split_by_token_limit<T: ChunkTokenizer>(
    text: &str,
    limit: usize,
    prefix: &str,
    tok: &T,
) -> (String, String) {
    if limit == 0 || text.is_empty() {
        return (String::new(), text.to_string());
    }
    let count = |head: &str| tok.count_tokens(&format!("{prefix}{head}"));
    if count(text) <= limit {
        return (text.to_string(), String::new());
    }
    let chars: Vec<char> = text.chars().collect();
    let head = |n: usize| chars[..n].iter().collect::<String>();
    let (mut lo, mut hi) = (0usize, chars.len());
    let mut best: Option<usize> = None;
    while lo <= hi {
        let mid = (lo + hi) / 2;
        if count(&head(mid)) <= limit {
            best = Some(mid);
            lo = mid + 1;
        } else if mid == 0 {
            break;
        } else {
            hi = mid - 1;
        }
    }
    let mut best = match best {
        Some(b) if b > 0 => b,
        _ => match (1..chars.len()).rev().find(|&i| count(&head(i)) <= limit) {
            Some(i) => i,
            None => return (String::new(), text.to_string()),
        },
    };
    if let Some(space) = chars[..best].iter().rposition(|c| *c == ' ') {
        if space > 0 && count(&head(space)) <= limit {
            best = space;
        }
    }
    (head(best), chars[best..].iter().collect())
}