kreuzberg 4.9.7

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 91+ formats and 248 programming languages via tree-sitter code intelligence with async/sync APIs.
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! JSON tree renderer for `InternalDocument`.
//!
//! Produces a heading-driven tree where headings create nested sections.
//! The output is a JSON object with a `title` (optional) and `body` array
//! of typed nodes (section, paragraph, table, code, formula, list, image, blockquote).

use serde::Serialize;

use crate::types::internal::{ElementKind, InternalDocument};

use super::common::{NestingKind, RenderState, get_language, handle_container_end, is_body_element, is_container_end};

// ============================================================================
// JSON Document Types
// ============================================================================

/// Top-level JSON document.
#[derive(Debug, Serialize)]
pub struct JsonDocument {
    /// Document title, if found.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Body content nodes.
    pub body: Vec<JsonNode>,
}

/// A node in the JSON document tree.
#[derive(Debug, Serialize)]
#[serde(tag = "type")]
pub enum JsonNode {
    /// A heading-delimited section containing nested content.
    #[serde(rename = "section")]
    Section {
        heading: String,
        level: u8,
        body: Vec<JsonNode>,
    },
    /// A text paragraph.
    #[serde(rename = "paragraph")]
    Paragraph { text: String },
    /// A table with headers and rows.
    #[serde(rename = "table")]
    Table {
        headers: Vec<String>,
        rows: Vec<Vec<String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        caption: Option<String>,
    },
    /// A code block with optional language.
    #[serde(rename = "code")]
    Code {
        text: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        language: Option<String>,
    },
    /// A mathematical formula.
    #[serde(rename = "formula")]
    Formula { text: String },
    /// An ordered or unordered list.
    #[serde(rename = "list")]
    List { ordered: bool, items: Vec<String> },
    /// An image reference.
    #[serde(rename = "image")]
    Image {
        #[serde(skip_serializing_if = "Option::is_none")]
        alt: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        src: Option<String>,
    },
    /// A blockquote containing nested content.
    #[serde(rename = "blockquote")]
    Blockquote { body: Vec<JsonNode> },
}

// ============================================================================
// Section Stack
// ============================================================================

/// An open section on the stack, accumulating child nodes.
struct OpenSection {
    heading: String,
    level: u8,
    body: Vec<JsonNode>,
}

// ============================================================================
// List Accumulator
// ============================================================================

/// Tracks an open list being accumulated from ListStart..ListEnd markers.
struct OpenList {
    ordered: bool,
    items: Vec<String>,
}

// ============================================================================
// Renderer
// ============================================================================

/// Render an `InternalDocument` as a JSON tree string.
///
/// Walks the flat element list and builds a heading-driven section tree.
/// Returns a JSON string (always valid JSON).
pub fn render_json(doc: &InternalDocument) -> String {
    let json_doc = build_json_document(doc);
    // serde_json::to_string should not fail on our types (no maps with non-string keys).
    serde_json::to_string(&json_doc).unwrap_or_else(|e| {
        tracing::error!(error = %e, "failed to serialize JSON document");
        r#"{"body":[]}"#.to_string()
    })
}

/// Build the `JsonDocument` from an `InternalDocument`.
fn build_json_document(doc: &InternalDocument) -> JsonDocument {
    let mut title: Option<String> = None;
    let mut section_stack: Vec<OpenSection> = Vec::new();
    let mut root_body: Vec<JsonNode> = Vec::new();
    let mut state = RenderState::default();
    let mut open_list: Option<OpenList> = None;
    let mut open_blockquote: Option<Vec<JsonNode>> = None;

    for elem in &doc.elements {
        if !is_body_element(elem) {
            continue;
        }

        if is_container_end(elem) {
            // Flush list/blockquote if ending
            match elem.kind {
                ElementKind::ListEnd => {
                    if let Some(list) = open_list.take() {
                        let node = JsonNode::List {
                            ordered: list.ordered,
                            items: list.items,
                        };
                        push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
                    }
                }
                ElementKind::QuoteEnd => {
                    if let Some(bq_body) = open_blockquote.take() {
                        let node = JsonNode::Blockquote { body: bq_body };
                        push_to_current(&mut root_body, &mut section_stack, &mut None, node);
                    }
                }
                _ => {}
            }
            handle_container_end(&elem.kind, &mut state);
            continue;
        }

        match elem.kind {
            ElementKind::Title => {
                if title.is_none() && !elem.text.is_empty() {
                    title = Some(elem.text.clone());
                }
            }

            ElementKind::Heading { level } => {
                // Flush any open list before starting a new section.
                flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);

                // Close sections at same or deeper level.
                close_sections_to_level(&mut section_stack, &mut root_body, level);

                // Open a new section.
                section_stack.push(OpenSection {
                    heading: elem.text.clone(),
                    level,
                    body: Vec::new(),
                });
            }

            ElementKind::Paragraph => {
                if elem.text.is_empty() {
                    continue;
                }
                // If inside an open list (orphan list items without markers), skip.
                let node = JsonNode::Paragraph {
                    text: elem.text.clone(),
                };
                push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
            }

            ElementKind::ListStart { ordered } => {
                // Flush any prior list.
                flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);
                state.push_container(NestingKind::List { ordered, item_count: 0 }, elem.depth);
                open_list = Some(OpenList {
                    ordered,
                    items: Vec::new(),
                });
            }

            ElementKind::ListItem { ordered } => {
                if let Some(ref mut list) = open_list {
                    list.items.push(elem.text.clone());
                } else {
                    // Orphan list item without ListStart — create an inline list node.
                    let node = JsonNode::List {
                        ordered,
                        items: vec![elem.text.clone()],
                    };
                    push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
                }
            }

            ElementKind::Code => {
                flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);
                let language = get_language(elem).map(|s| s.to_string());
                let node = JsonNode::Code {
                    text: elem.text.clone(),
                    language,
                };
                push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
            }

            ElementKind::Formula => {
                flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);
                let node = JsonNode::Formula {
                    text: elem.text.clone(),
                };
                push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
            }

            ElementKind::Table { table_index } => {
                flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);
                if let Some(table) = doc.tables.get(table_index as usize) {
                    let (headers, rows) = if table.cells.is_empty() {
                        (Vec::new(), Vec::new())
                    } else {
                        let headers = table.cells[0].clone();
                        let rows = table.cells[1..].to_vec();
                        (headers, rows)
                    };
                    let node = JsonNode::Table {
                        headers,
                        rows,
                        caption: None,
                    };
                    push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
                }
            }

            ElementKind::Image { image_index } => {
                flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);
                let image = doc.images.get(image_index as usize);
                let alt = image.and_then(|img| img.description.clone());
                let src = image.and_then(|img| {
                    if !img.data.is_empty() {
                        Some(format!("image_{}.{}", image_index, img.format))
                    } else {
                        img.source_path.clone()
                    }
                });
                let node = JsonNode::Image { alt, src };
                push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
            }

            ElementKind::QuoteStart => {
                flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);
                state.push_container(NestingKind::BlockQuote, elem.depth);
                open_blockquote = Some(Vec::new());
            }

            ElementKind::OcrText { .. } => {
                if !elem.text.is_empty() {
                    let node = JsonNode::Paragraph {
                        text: elem.text.clone(),
                    };
                    push_to_current(&mut root_body, &mut section_stack, &mut open_blockquote, node);
                }
            }

            // Container end markers, page breaks, footnotes, etc. — skip.
            ElementKind::ListEnd
            | ElementKind::QuoteEnd
            | ElementKind::GroupStart
            | ElementKind::GroupEnd
            | ElementKind::PageBreak
            | ElementKind::FootnoteDefinition
            | ElementKind::FootnoteRef
            | ElementKind::Citation
            | ElementKind::Slide { .. }
            | ElementKind::DefinitionTerm
            | ElementKind::DefinitionDescription
            | ElementKind::Admonition
            | ElementKind::RawBlock
            | ElementKind::MetadataBlock => {}
        }
    }

    // Flush any remaining open list.
    flush_list(&mut open_list, &mut root_body, &mut section_stack, &mut open_blockquote);

    // Flush any remaining open blockquote.
    if let Some(bq_body) = open_blockquote.take() {
        let node = JsonNode::Blockquote { body: bq_body };
        push_to_current(&mut root_body, &mut section_stack, &mut None, node);
    }

    // Close all remaining open sections.
    close_sections_to_level(&mut section_stack, &mut root_body, 0);

    JsonDocument { title, body: root_body }
}

/// Push a node to the current target (innermost open section, or root body).
fn push_to_current(
    root_body: &mut Vec<JsonNode>,
    section_stack: &mut [OpenSection],
    open_blockquote: &mut Option<Vec<JsonNode>>,
    node: JsonNode,
) {
    // If inside a blockquote, push there.
    if let Some(bq) = open_blockquote {
        bq.push(node);
        return;
    }
    // Otherwise, push to innermost open section or root.
    if let Some(section) = section_stack.last_mut() {
        section.body.push(node);
    } else {
        root_body.push(node);
    }
}

/// Close all open sections whose level >= `target_level`.
/// Wraps each closed section as a `JsonNode::Section` and appends to its parent.
fn close_sections_to_level(section_stack: &mut Vec<OpenSection>, root_body: &mut Vec<JsonNode>, target_level: u8) {
    while let Some(top) = section_stack.last() {
        if top.level >= target_level {
            let section = section_stack.pop().expect("checked non-empty");
            let node = JsonNode::Section {
                heading: section.heading,
                level: section.level,
                body: section.body,
            };
            // Append to parent section or root.
            if let Some(parent) = section_stack.last_mut() {
                parent.body.push(node);
            } else {
                root_body.push(node);
            }
        } else {
            break;
        }
    }
}

/// Flush an open list accumulator into the current target.
fn flush_list(
    open_list: &mut Option<OpenList>,
    root_body: &mut Vec<JsonNode>,
    section_stack: &mut [OpenSection],
    open_blockquote: &mut Option<Vec<JsonNode>>,
) {
    if let Some(list) = open_list.take() {
        let node = JsonNode::List {
            ordered: list.ordered,
            items: list.items,
        };
        push_to_current(root_body, section_stack, open_blockquote, node);
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::internal_builder::InternalDocumentBuilder;

    #[test]
    fn test_empty_document() {
        let b = InternalDocumentBuilder::new("test");
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(parsed.get("title").is_none() || parsed["title"].is_null());
        assert_eq!(parsed["body"], serde_json::json!([]));
    }

    #[test]
    fn test_single_paragraph() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_paragraph("Hello world", vec![], None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["body"].as_array().unwrap().len(), 1);
        assert_eq!(parsed["body"][0]["type"], "paragraph");
        assert_eq!(parsed["body"][0]["text"], "Hello world");
    }

    #[test]
    fn test_heading_creates_section() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_heading(1, "Chapter 1", None, None);
        b.push_paragraph("Chapter content", vec![], None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["body"].as_array().unwrap().len(), 1);
        let section = &parsed["body"][0];
        assert_eq!(section["type"], "section");
        assert_eq!(section["heading"], "Chapter 1");
        assert_eq!(section["level"], 1);
        assert_eq!(section["body"][0]["type"], "paragraph");
        assert_eq!(section["body"][0]["text"], "Chapter content");
    }

    #[test]
    fn test_nested_sections() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_heading(1, "Chapter 1", None, None);
        b.push_paragraph("Intro", vec![], None, None);
        b.push_heading(2, "Section 1.1", None, None);
        b.push_paragraph("Sub content", vec![], None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let section = &parsed["body"][0];
        assert_eq!(section["type"], "section");
        assert_eq!(section["heading"], "Chapter 1");
        assert_eq!(section["level"], 1);
        // Body should have: paragraph "Intro" and a nested section
        assert_eq!(section["body"].as_array().unwrap().len(), 2);
        assert_eq!(section["body"][0]["type"], "paragraph");
        let sub_section = &section["body"][1];
        assert_eq!(sub_section["type"], "section");
        assert_eq!(sub_section["heading"], "Section 1.1");
        assert_eq!(sub_section["level"], 2);
        assert_eq!(sub_section["body"][0]["text"], "Sub content");
    }

    #[test]
    fn test_table_in_json() {
        let mut b = InternalDocumentBuilder::new("test");
        let cells = vec![
            vec!["A".to_string(), "B".to_string()],
            vec!["1".to_string(), "2".to_string()],
            vec!["3".to_string(), "4".to_string()],
        ];
        b.push_table_from_cells(&cells, None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let table = &parsed["body"][0];
        assert_eq!(table["type"], "table");
        assert_eq!(table["headers"], serde_json::json!(["A", "B"]));
        assert_eq!(table["rows"], serde_json::json!([["1", "2"], ["3", "4"]]));
    }

    #[test]
    fn test_code_block() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_code("print('hello')", Some("python"), None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let code = &parsed["body"][0];
        assert_eq!(code["type"], "code");
        assert_eq!(code["text"], "print('hello')");
        assert_eq!(code["language"], "python");
    }

    #[test]
    fn test_code_block_no_language() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_code("some code", None, None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let code = &parsed["body"][0];
        assert_eq!(code["type"], "code");
        assert_eq!(code["text"], "some code");
        // language should be absent (skip_serializing_if)
        assert!(code.get("language").is_none() || code["language"].is_null());
    }

    #[test]
    fn test_list() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_list(false);
        b.push_list_item("Item 1", false, vec![], None, None);
        b.push_list_item("Item 2", false, vec![], None, None);
        b.end_list();
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let list = &parsed["body"][0];
        assert_eq!(list["type"], "list");
        assert_eq!(list["ordered"], false);
        assert_eq!(list["items"], serde_json::json!(["Item 1", "Item 2"]));
    }

    #[test]
    fn test_ordered_list() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_list(true);
        b.push_list_item("First", true, vec![], None, None);
        b.push_list_item("Second", true, vec![], None, None);
        b.end_list();
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let list = &parsed["body"][0];
        assert_eq!(list["type"], "list");
        assert_eq!(list["ordered"], true);
        assert_eq!(list["items"], serde_json::json!(["First", "Second"]));
    }

    #[test]
    fn test_formula() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_formula("E = mc^2", None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let formula = &parsed["body"][0];
        assert_eq!(formula["type"], "formula");
        assert_eq!(formula["text"], "E = mc^2");
    }

    #[test]
    fn test_title_from_title_element() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_title("My Document", None, None);
        b.push_paragraph("Content", vec![], None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["title"], "My Document");
        // Title should not appear as a body node.
        assert_eq!(parsed["body"].as_array().unwrap().len(), 1);
        assert_eq!(parsed["body"][0]["type"], "paragraph");
    }

    #[test]
    fn test_blockquote() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_quote_start();
        b.push_paragraph("Quoted text", vec![], None, None);
        b.push_quote_end();
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        let bq = &parsed["body"][0];
        assert_eq!(bq["type"], "blockquote");
        assert_eq!(bq["body"][0]["type"], "paragraph");
        assert_eq!(bq["body"][0]["text"], "Quoted text");
    }

    #[test]
    fn test_sibling_sections() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_heading(1, "Chapter 1", None, None);
        b.push_paragraph("Content 1", vec![], None, None);
        b.push_heading(1, "Chapter 2", None, None);
        b.push_paragraph("Content 2", vec![], None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["body"].as_array().unwrap().len(), 2);
        assert_eq!(parsed["body"][0]["heading"], "Chapter 1");
        assert_eq!(parsed["body"][1]["heading"], "Chapter 2");
    }

    #[test]
    fn test_valid_json_output() {
        let mut b = InternalDocumentBuilder::new("test");
        b.push_title("Test", None, None);
        b.push_heading(1, "H1", None, None);
        b.push_paragraph("Para", vec![], None, None);
        b.push_heading(2, "H2", None, None);
        b.push_code("code", Some("rust"), None, None);
        b.push_formula("x^2", None, None);
        let doc = b.build();
        let json_str = render_json(&doc);
        // Must be valid JSON.
        let result: Result<serde_json::Value, _> = serde_json::from_str(&json_str);
        assert!(result.is_ok(), "JSON output is not valid: {}", json_str);
    }
}