docling 2.52.6

DocumentConverter and format backends 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
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
448
449
450
451
452
453
454
455
//! CSV backend.
//!
//! Mirrors `docling.backend.csv_backend.CsvDocumentBackend`: sniff the delimiter
//! among `, ; \t | :` from the first line (falling back to comma), parse the
//! whole file with RFC-4180 quote handling, and emit one table whose width is
//! the widest row (ragged rows are padded). Row 0 is the header.

use csv::ReaderBuilder;
use docling_core::{DoclingDocument, Node, Table, TableCell};

use crate::backend::DeclarativeBackend;
use crate::error::ConversionError;
use crate::source::SourceDocument;

pub struct CsvBackend;

impl DeclarativeBackend for CsvBackend {
    fn convert(&self, source: &SourceDocument) -> Result<DoclingDocument, ConversionError> {
        let text = source.text()?;
        let text: &str = &text;
        let delimiter = detect_delimiter(text);
        // docling reads with `csv.reader(strict=True)` and, since 2.129
        // (docling#4260), turns its `csv.Error` into a load error rather
        // than letting it escape: a closing quote followed by anything but
        // the delimiter or a line end, or a quote still open at EOF. The
        // `csv` crate is lenient about both, so they are checked up front.
        check_strict_quoting(text, delimiter)
            .map_err(|e| ConversionError::Parse(format!("csv: malformed quoting — {e}")))?;

        let mut reader = ReaderBuilder::new()
            .delimiter(delimiter)
            .has_headers(false)
            .flexible(true)
            .from_reader(text.as_bytes());

        let mut rows: Vec<Vec<String>> = Vec::new();
        for record in reader.records() {
            let record = record.map_err(|e| ConversionError::with_source("csv", e))?;
            // Cell escaping (newlines, pipes) happens centrally in the serializer.
            rows.push(record.iter().map(str::to_string).collect());
        }

        let mut doc = DoclingDocument::new(&source.name);
        if !rows.is_empty() {
            let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
            // A ragged file's short rows hold only the cells they have, as
            // docling adds a `TableCell` per value read (its grid fills the
            // rest); the text grid is padded for the serializers.
            let cells = rows.iter().any(|r| r.len() != num_cols).then(|| {
                rows.iter()
                    .enumerate()
                    .flat_map(|(r, row)| {
                        row.iter().enumerate().map(move |(c, text)| TableCell {
                            text: text.clone(),
                            bbox: None,
                            start_row: r,
                            start_col: c,
                            row_span: 1,
                            col_span: 1,
                            column_header: r == 0,
                            row_header: false,
                            row_section: false,
                        })
                    })
                    .collect()
            });
            for row in &mut rows {
                row.resize(num_cols, String::new());
            }
            doc.push(Node::Table(Table {
                rows,
                location: None,
                structure: None,
                cell_blocks: None,
                cells,
                caption: None,
                caption_parent: Default::default(),
                caption_location: None,
            }));
        }
        Ok(doc)
    }
}

/// Python `csv`'s strict-mode errors: `'<delimiter>' expected after '"'`
/// when a quoted field's closing quote is followed by anything other than
/// the delimiter, a line end or EOF (`""` inside the field is an escaped
/// quote), and `unexpected end of data` when EOF arrives inside a quoted
/// field. A quote inside an *unquoted* field is ordinary text, as in Python.
fn check_strict_quoting(text: &str, delimiter: u8) -> Result<(), String> {
    let d = delimiter as char;
    let mut chars = text.chars().peekable();
    let mut field_start = true;
    let mut line = 1usize;
    while let Some(c) = chars.next() {
        if field_start && c == '"' {
            // Inside a quoted field.
            loop {
                match chars.next() {
                    None => {
                        return Err(format!(
                            "unexpected end of data in a quoted field (line {line})"
                        ))
                    }
                    Some('"') => match chars.peek() {
                        Some('"') => {
                            chars.next();
                        }
                        Some(&n) if n == d => {
                            chars.next();
                            field_start = true;
                            break;
                        }
                        Some('\n') | Some('\r') | None => {
                            field_start = true;
                            break;
                        }
                        Some(n) => {
                            return Err(format!(
                                "'{d}' expected after '\"' (line {line}), found {n:?}"
                            ))
                        }
                    },
                    Some('\n') => line += 1,
                    Some(_) => {}
                }
            }
            continue;
        }
        if c == '\n' {
            line += 1;
        }
        field_start = c == d || c == '\n' || c == '\r';
    }
    Ok(())
}

/// Sniff the delimiter from the first line: the candidate (`, ; \t | :`) that
/// occurs most often wins. When the first line carries none — a quoted field
/// spanning several lines cuts it mid-quote (docling#3985, 2.123) — retry
/// over the first 4 KiB, which closes the quote; comma remains the default
/// when nothing matches at all. The first line stays authoritative otherwise:
/// widening the sample unconditionally would change the delimiter picked for
/// ragged files.
fn detect_delimiter(text: &str) -> u8 {
    const CANDIDATES: [u8; 5] = *b",;\t|:";
    let count_best = |sample: &[u8]| {
        let mut best = b',';
        let mut best_count = 0usize;
        for &c in &CANDIDATES {
            let n = sample.iter().filter(|&&b| b == c).count();
            if n > best_count {
                best_count = n;
                best = c;
            }
        }
        (best, best_count)
    };
    let first = text.lines().next().unwrap_or("");
    // docling#4896: a header holding several candidates — a comma inside a
    // semicolon file's `Weight (kg, net)`, the `:` of a comma file's
    // `Time (hh:mm:ss)` — is read by the occurrences outside brackets, where
    // a column name rarely splits; only a header with none there falls back
    // to every occurrence.
    match count_best(&outside_brackets(first)) {
        (best, n) if n > 0 => best,
        _ => match count_best(first.as_bytes()) {
            (best, n) if n > 0 => best,
            _ => {
                let bytes = text.as_bytes();
                count_best(&bytes[..bytes.len().min(4096)]).0
            }
        },
    }
}

/// `line`'s bytes outside `()`, `[]` and `{}` — docling's
/// `_count_outside_brackets` (an unbalanced closer is ignored).
fn outside_brackets(line: &str) -> Vec<u8> {
    let mut depth = 0usize;
    let mut out = Vec::with_capacity(line.len());
    for b in line.bytes() {
        match b {
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth = depth.saturating_sub(1),
            _ if depth == 0 => out.push(b),
            _ => {}
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::InputFormat;

    fn convert(bytes: &[u8]) -> DoclingDocument {
        let src = SourceDocument::from_bytes("data", InputFormat::Csv, bytes.to_vec());
        CsvBackend.convert(&src).unwrap()
    }

    /// docling#4896's cases (`test_header_with_second_delimiter_uses_following_rows`):
    /// a header holding two candidate delimiters — a comma inside a
    /// semicolon file's column name, a `:` in `Time (hh:mm)` of a ragged
    /// comma file — still splits on the file's delimiter, and the quoting
    /// (`'n/a'`, an unclosed `'90s music`) stays literal.
    #[test]
    fn header_with_a_second_delimiter_splits_on_the_files_one() {
        for (payload, expected) in [
            (
                "Product;Weight (kg, net);Price\nApple;0,2;1,50\nPear;0,35;2\n",
                &[
                    "Product",
                    "Weight (kg, net)",
                    "Price",
                    "Apple",
                    "0,2",
                    "1,50",
                    "Pear",
                    "0,35",
                    "2",
                ][..],
            ),
            (
                "Product,Weight (kg; net),Price\nApple,0.2,1.50\nPear,0.35,2\n",
                &[
                    "Product",
                    "Weight (kg; net)",
                    "Price",
                    "Apple",
                    "0.2",
                    "1.50",
                    "Pear",
                    "0.35",
                    "2",
                ][..],
            ),
            (
                "Date,Time (hh:mm),Value,Note\n2024-01-01,10:30,5,a\n2024-01-02,11:45,6\n",
                &[
                    "Date",
                    "Time (hh:mm)",
                    "Value",
                    "Note",
                    "2024-01-01",
                    "10:30",
                    "5",
                    "a",
                    "2024-01-02",
                    "11:45",
                    "6",
                ][..],
            ),
            (
                "id,ratio (a;b),x,y\n1,2;3,4,5\n2,6;7,8\n",
                &[
                    "id",
                    "ratio (a;b)",
                    "x",
                    "y",
                    "1",
                    "2;3",
                    "4",
                    "5",
                    "2",
                    "6;7",
                    "8",
                ][..],
            ),
            (
                "id,ratio (a;b),x,y\n1,0.5,2,3\n2,0.7,4\n",
                &[
                    "id",
                    "ratio (a;b)",
                    "x",
                    "y",
                    "1",
                    "0.5",
                    "2",
                    "3",
                    "2",
                    "0.7",
                    "4",
                ][..],
            ),
            (
                "Time (hh:mm:ss),Value\n10:30:00,5\n11:45:00\n",
                &["Time (hh:mm:ss)", "Value", "10:30:00", "5", "11:45:00"][..],
            ),
            (
                "Time (hh:mm),Value\n10:30,5\n11:45\n",
                &["Time (hh:mm)", "Value", "10:30", "5", "11:45"][..],
            ),
            (
                "Name,Time hh:mm:ss,Value\nA,10:30:00,5\nB,11:45:00\n",
                &[
                    "Name",
                    "Time hh:mm:ss",
                    "Value",
                    "A",
                    "10:30:00",
                    "5",
                    "B",
                    "11:45:00",
                ][..],
            ),
            (
                "Start: time,Value\n10:30,5\n11:45\n",
                &["Start: time", "Value", "10:30", "5", "11:45"][..],
            ),
            (
                "Date,Time (hh:mm),Note\n2024-01-01,10:30,'n/a'\n2024-01-02,11:45,'90s music\n",
                &[
                    "Date",
                    "Time (hh:mm)",
                    "Note",
                    "2024-01-01",
                    "10:30",
                    "'n/a'",
                    "2024-01-02",
                    "11:45",
                    "'90s music",
                ][..],
            ),
            (
                "id,ratio (a;b),Note\n1,0.5,'n/a'\n2,0.7,'90s music\n",
                &[
                    "id",
                    "ratio (a;b)",
                    "Note",
                    "1",
                    "0.5",
                    "'n/a'",
                    "2",
                    "0.7",
                    "'90s music",
                ][..],
            ),
            (
                "Date,Time (hh:mm),Note\n2024-01-01,10:30,'tbd'\n2024-01-02,11:45,'tbd'\n",
                &[
                    "Date",
                    "Time (hh:mm)",
                    "Note",
                    "2024-01-01",
                    "10:30",
                    "'tbd'",
                    "2024-01-02",
                    "11:45",
                    "'tbd'",
                ][..],
            ),
            (
                "Product;Weight (kg, net);Note\nApple;0,2;'n/a'\nPear;0,35;'90s music\n",
                &[
                    "Product",
                    "Weight (kg, net)",
                    "Note",
                    "Apple",
                    "0,2",
                    "'n/a'",
                    "Pear",
                    "0,35",
                    "'90s music",
                ][..],
            ),
            (
                "Product;Weight (kg, net);Note\nApple;0,2;'tbd'\nPear;0,35;'tbd'\n",
                &[
                    "Product",
                    "Weight (kg, net)",
                    "Note",
                    "Apple",
                    "0,2",
                    "'tbd'",
                    "Pear",
                    "0,35",
                    "'tbd'",
                ][..],
            ),
            (
                "Product;Weight (kg, net);Note\nApple;0,2;\"a; b\"\nPear;0,35;c\n",
                &[
                    "Product",
                    "Weight (kg, net)",
                    "Note",
                    "Apple",
                    "0,2",
                    "a; b",
                    "Pear",
                    "0,35",
                    "c",
                ][..],
            ),
        ] {
            let json = convert(payload.as_bytes()).export_to_json_value();
            let cells: Vec<&str> = json["tables"][0]["data"]["table_cells"]
                .as_array()
                .unwrap()
                .iter()
                .map(|c| c["text"].as_str().unwrap())
                .collect();
            assert_eq!(cells, expected, "{payload:?}");
        }
    }

    #[test]
    fn converts_csv_to_table() {
        let doc = convert(b"name,age\nAlice,30\nBob,25\n");
        assert_eq!(
            doc.export_to_markdown(),
            "| name   |   age |\n|--------|-------|\n| Alice  |    30 |\n| Bob    |    25 |\n"
        );
    }

    /// docling#4260 (2.129): Python's strict reader rejects a closing quote
    /// followed by text and a quote left open at EOF; both are load errors
    /// here too, while an escaped quote and a quote inside an unquoted field
    /// still read.
    #[test]
    fn malformed_quoting_is_a_load_error() {
        let bad = |s: &str| {
            let src = SourceDocument::from_bytes("t.csv", InputFormat::Csv, s.as_bytes().to_vec());
            CsvBackend.convert(&src).is_err()
        };
        assert!(bad("a,\"b\"c,d\n"));
        assert!(bad("a,\"open\n"));
        assert!(!bad("a,\"x \"\"y\"\" z\",c\n"));
        assert!(!bad("a,b\"c,d\n"));
        assert!(!bad("\"a\",\"b\"\n\"c\",\"d\""));
    }

    #[test]
    fn handles_quoted_comma() {
        // The quoted field keeps its embedded comma instead of splitting.
        let doc = convert(b"a,b\n1,\"Lozano, Dr\"\n");
        let Node::Table(table) = &doc.nodes[0] else {
            panic!("expected a table");
        };
        assert_eq!(
            table.rows[1],
            vec!["1".to_string(), "Lozano, Dr".to_string()]
        );
    }

    #[test]
    fn sniffs_semicolon_delimiter() {
        let doc = convert(b"a;b;c\n1;2;3\n");
        let Node::Table(table) = &doc.nodes[0] else {
            panic!("expected a table");
        };
        assert_eq!(table.rows[0], vec!["a", "b", "c"]);
    }
}