Skip to main content

docling_core/
chunker.rs

1//! Document chunking for RAG pipelines — the Rust port of docling-core's
2//! `docling_core.transforms.chunker`.
3//!
4//! Two chunkers, matching docling's semantics output-for-output:
5//!
6//! * [`HierarchicalChunker`] walks the document tree and yields one chunk per
7//!   top-level item (paragraph, whole list, table, picture caption, …), each
8//!   carrying the heading path it sits under. Tables are serialized in
9//!   docling's *triplet* form (`row, column = value`), pictures contribute
10//!   their captions.
11//! * [`HybridChunker`] refines the hierarchical chunks with a tokenizer:
12//!   oversized chunks are split (at item boundaries first, then within the
13//!   text by docling's `semchunk` algorithm), and undersized neighbours that
14//!   share the same headings are merged back together.
15//!
16//! [`contextualize`] renders a chunk to the string an embedding model should
17//! see: the heading path plus the chunk text.
18//!
19//! Anything tokenizer-related is abstracted behind [`ChunkTokenizer`]; a
20//! HuggingFace `tokenizers` implementation ships behind the `chunking` cargo
21//! feature as [`HuggingFaceTokenizer`].
22
23use std::collections::BTreeMap;
24
25use crate::document::{DoclingDocument, Node, Table};
26
27/// What kind of document item a [`ChunkItem`] points at — only what the
28/// hybrid splitting logic needs to know.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum ChunkItemKind {
31    /// A text-ish item (paragraph, list item, code, formula, caption, …).
32    Text,
33    /// A table item (single-item oversized chunks re-split per line, repeating
34    /// docling's header handling).
35    Table,
36    /// A picture item.
37    Picture,
38}
39
40/// One document item contributing to a chunk — the analogue of an entry in
41/// docling's `DocMeta.doc_items`.
42#[derive(Debug, Clone, PartialEq)]
43pub struct ChunkItem {
44    /// The item's ref in [`DoclingDocument::export_to_json`] output
45    /// (`#/texts/12`, `#/tables/0`, `#/pictures/1`, …).
46    pub self_ref: String,
47    pub kind: ChunkItemKind,
48    /// The item serialized *standalone* (docling re-serializes individual
49    /// items when splitting an oversized multi-item chunk — e.g. a nested
50    /// list item flattens to `- text` with no indentation).
51    pub text: String,
52}
53
54/// One chunk — the analogue of docling's `DocChunk` (text + `DocMeta`).
55#[derive(Debug, Clone, PartialEq)]
56pub struct DocChunk {
57    /// The chunk body (markdown-flavoured, unescaped — same text docling puts
58    /// in `DocChunk.text`).
59    pub text: String,
60    /// The heading path above this chunk, outermost first (`DocMeta.headings`;
61    /// `None` when the chunk sits above any heading).
62    pub headings: Option<Vec<String>>,
63    /// The document items the chunk was built from (`DocMeta.doc_items`).
64    pub doc_items: Vec<ChunkItem>,
65}
66
67/// Render a chunk for embedding: the heading path, then the text, joined with
68/// newlines — docling's `BaseChunker.contextualize()`.
69pub fn contextualize(chunk: &DocChunk) -> String {
70    let mut parts: Vec<&str> = Vec::new();
71    if let Some(h) = &chunk.headings {
72        parts.extend(h.iter().map(String::as_str));
73    }
74    parts.push(&chunk.text);
75    parts.join("\n")
76}
77
78// ---------------------------------------------------------------------------
79// Hierarchical chunker
80// ---------------------------------------------------------------------------
81
82/// Structure-driven chunker: one chunk per document item, lists and inline
83/// groups kept whole, heading path tracked as metadata — docling-core's
84/// `HierarchicalChunker` with default parameters.
85#[derive(Debug, Clone, Default)]
86pub struct HierarchicalChunker;
87
88impl HierarchicalChunker {
89    /// Chunk the document.
90    pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
91        let mut chunks = Vec::new();
92        self.chunk_with(doc, &mut |c| {
93            chunks.push(c);
94            true
95        });
96        chunks
97    }
98
99    /// Stream the chunks: `sink` is called with each chunk as the document
100    /// walk produces it, so a consumer can process (embed, forward) chunks
101    /// without materializing the whole `Vec` first. A `false` return from
102    /// `sink` cancels the walk. [`Self::chunk`] is this with a collecting
103    /// sink — the chunks and their order are identical.
104    pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
105        let mut w = Walker {
106            alloc: Alloc::default(),
107            headings: BTreeMap::new(),
108            stopped: false,
109            sink,
110        };
111        w.walk(&doc.nodes);
112    }
113}
114
115/// Ref allocator mirroring the numbering `json.rs` gives every item, so
116/// `ChunkItem::self_ref` matches the document's JSON export.
117#[derive(Debug, Default)]
118struct Alloc {
119    texts: usize,
120    groups: usize,
121    tables: usize,
122    pictures: usize,
123    field_regions: usize,
124    field_items: usize,
125}
126
127impl Alloc {
128    fn text(&mut self) -> String {
129        let r = format!("#/texts/{}", self.texts);
130        self.texts += 1;
131        r
132    }
133    fn group(&mut self) -> String {
134        let r = format!("#/groups/{}", self.groups);
135        self.groups += 1;
136        r
137    }
138    fn table(&mut self) -> String {
139        let r = format!("#/tables/{}", self.tables);
140        self.tables += 1;
141        r
142    }
143    fn picture(&mut self) -> String {
144        let r = format!("#/pictures/{}", self.pictures);
145        self.pictures += 1;
146        r
147    }
148    fn field_region(&mut self) -> String {
149        let r = format!("#/field_regions/{}", self.field_regions);
150        self.field_regions += 1;
151        r
152    }
153    fn field_item(&mut self) -> String {
154        let r = format!("#/field_items/{}", self.field_items);
155        self.field_items += 1;
156        r
157    }
158}
159
160struct Walker<'s> {
161    alloc: Alloc,
162    /// Active heading per docling level (title = 0, `section_header` = its
163    /// `level`), pruned like docling's `heading_by_level`.
164    headings: BTreeMap<u8, String>,
165    /// Set once the sink refuses a chunk; the walk unwinds without emitting.
166    stopped: bool,
167    sink: &'s mut dyn FnMut(DocChunk) -> bool,
168}
169
170impl Walker<'_> {
171    fn emit(&mut self, text: String, doc_items: Vec<ChunkItem>) {
172        if self.stopped || text.is_empty() {
173            return;
174        }
175        let headings: Vec<String> = self.headings.values().cloned().collect();
176        self.stopped = !(self.sink)(DocChunk {
177            text,
178            headings: (!headings.is_empty()).then_some(headings),
179            doc_items,
180        });
181    }
182
183    /// Emit a text chunk whose doc items follow docling's inline granularity:
184    /// mixed inline content (a paragraph docling represents as an inline group)
185    /// contributes one item per span, plain text one item.
186    fn emit_inline(&mut self, md_text: &str, self_ref: String) {
187        self.emit_inline_with_runs(md_text, self_ref, &[]);
188    }
189
190    fn emit_inline_with_runs(
191        &mut self,
192        md_text: &str,
193        self_ref: String,
194        runs: &[crate::InlineRun],
195    ) {
196        let body = unescape_text(md_text);
197        if body.is_empty() {
198            return;
199        }
200        let segments: Vec<String> = inline_segments_tagged(md_text)
201            .into_iter()
202            .flat_map(|(text, is_plain)| {
203                if is_plain {
204                    if let Some(split) = split_plain_by_runs(&text, runs) {
205                        return split;
206                    }
207                }
208                vec![text]
209            })
210            .collect();
211        let items: Vec<ChunkItem> = if segments.len() <= 1 {
212            vec![ChunkItem {
213                self_ref,
214                kind: ChunkItemKind::Text,
215                text: body.clone(),
216            }]
217        } else {
218            segments
219                .into_iter()
220                .map(|text| ChunkItem {
221                    self_ref: self_ref.clone(),
222                    kind: ChunkItemKind::Text,
223                    text,
224                })
225                .collect()
226        };
227        self.emit(body, items);
228    }
229
230    fn set_heading(&mut self, doc_level: u8, text: String) {
231        self.headings.retain(|k, _| *k < doc_level);
232        self.headings.insert(doc_level, text);
233    }
234
235    fn walk(&mut self, nodes: &[Node]) {
236        let mut i = 0;
237        while i < nodes.len() {
238            if self.stopped {
239                return;
240            }
241            if matches!(nodes[i], Node::ListItem { .. }) {
242                let start = i;
243                i += 1;
244                loop {
245                    match nodes.get(i) {
246                        Some(Node::ListItem { .. }) => i += 1,
247                        // An empty paragraph between two list items is absorbed
248                        // into the run (mirrors json.rs / markdown.rs).
249                        Some(Node::Paragraph { text })
250                            if text.is_empty()
251                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
252                        {
253                            i += 1
254                        }
255                        _ => break,
256                    }
257                }
258                self.sibling_lists(&nodes[start..i]);
259            } else {
260                self.one(&nodes[i]);
261                i += 1;
262            }
263        }
264    }
265
266    /// Split a run of list items into sibling lists exactly like
267    /// `json.rs::add_sibling_lists`, chunking each list separately (docling
268    /// yields one chunk per `ListGroup`).
269    fn sibling_lists(&mut self, run: &[Node]) {
270        let base = level_of(&run[0]);
271        let mut seg = 0;
272        let mut prev: Option<(bool, u64)> = None;
273        for k in 0..run.len() {
274            let Node::ListItem {
275                ordered,
276                number,
277                first_in_list,
278                level,
279                ..
280            } = &run[k]
281            else {
282                continue;
283            };
284            if *level != base {
285                continue; // nested item — handled inside `list`
286            }
287            if k > seg {
288                if let Some((po, pn)) = prev {
289                    if *first_in_list || po != *ordered || (*ordered && *number != pn + 1) {
290                        self.list(&run[seg..k]);
291                        seg = k;
292                    }
293                }
294            }
295            prev = Some((*ordered, *number));
296        }
297        self.list(&run[seg..]);
298    }
299
300    /// One `ListGroup`: allocate refs in `json.rs::add_list` order (group,
301    /// then per top item its text ref followed by any nested groups) and emit
302    /// a single chunk whose text is the indented markdown list.
303    fn list(&mut self, items: &[Node]) {
304        self.alloc.group();
305        let mut chunk_items = Vec::new();
306        self.list_refs(items, &mut chunk_items);
307        let text = render_list(items);
308        self.emit(text, chunk_items);
309    }
310
311    /// Allocate refs for one list's items (and nested sibling lists), mirroring
312    /// `json.rs::add_list` / `add_sibling_lists` recursion, collecting the
313    /// non-furniture items in allocation (= document) order.
314    fn list_refs(&mut self, items: &[Node], out: &mut Vec<ChunkItem>) {
315        let base = level_of(&items[0]);
316        let mut i = 0;
317        while i < items.len() {
318            let Node::ListItem {
319                ordered,
320                number,
321                text,
322                level,
323                layer,
324                ..
325            } = &items[i]
326            else {
327                i += 1;
328                continue;
329            };
330            if *level > base {
331                i += 1;
332                continue;
333            }
334            let item_ref = self.alloc.text();
335            let mut j = i + 1;
336            while j < items.len() && level_of(&items[j]) > base {
337                j += 1;
338            }
339            let has_nested = j > i + 1;
340            if layer.is_none() {
341                let marker = if *ordered {
342                    format!("{number}.")
343                } else {
344                    "-".to_string()
345                };
346                // An item that carries both inline spans and a nested list is an
347                // empty list item wrapping an inline group in docling's model:
348                // its marker and each inline span are separate doc items.
349                // docling represents a list item whose content is not pure
350                // inline text (it carries a nested list or child pictures) as
351                // an empty item wrapping an inline group: its marker and each
352                // inline span become separate doc items.
353                // docling represents a list item whose content is not pure
354                // inline text (it carries a nested list or its own images) as
355                // an empty item wrapping an inline group: its marker and each
356                // inline span become separate doc items. The chunker's
357                // image placeholder is empty, so the markers are stripped from
358                // the text before segmentation.
359                let has_pics = text.contains("<!-- image -->");
360                let text = strip_image_markers(text);
361                let text = text.as_str();
362                let segments = inline_segments(text);
363                if (has_nested || has_pics) && segments.len() > 1 && text.contains("](") {
364                    out.push(ChunkItem {
365                        self_ref: item_ref.clone(),
366                        kind: ChunkItemKind::Text,
367                        text: format!("{marker} "),
368                    });
369                    for seg in segments {
370                        out.push(ChunkItem {
371                            self_ref: item_ref.clone(),
372                            kind: ChunkItemKind::Text,
373                            text: seg,
374                        });
375                    }
376                } else {
377                    out.push(ChunkItem {
378                        self_ref: item_ref.clone(),
379                        kind: ChunkItemKind::Text,
380                        text: format!("{marker} {}", unescape_text(text)),
381                    });
382                }
383            }
384            // nested items group under this one; each nested sibling list is a
385            // fresh group ref
386            if j > i + 1 {
387                self.nested_sibling_lists(&items[i + 1..j], out);
388            }
389            i = j;
390        }
391    }
392
393    fn nested_sibling_lists(&mut self, run: &[Node], out: &mut Vec<ChunkItem>) {
394        let base = level_of(&run[0]);
395        let mut seg = 0;
396        let mut prev: Option<(bool, u64)> = None;
397        for k in 0..run.len() {
398            let Node::ListItem {
399                ordered,
400                number,
401                first_in_list,
402                level,
403                ..
404            } = &run[k]
405            else {
406                continue;
407            };
408            if *level != base {
409                continue;
410            }
411            if k > seg {
412                if let Some((po, pn)) = prev {
413                    if *first_in_list || po != *ordered || (*ordered && *number != pn + 1) {
414                        self.alloc.group();
415                        self.list_refs(&run[seg..k], out);
416                        seg = k;
417                    }
418                }
419            }
420            prev = Some((*ordered, *number));
421        }
422        self.alloc.group();
423        self.list_refs(&run[seg..], out);
424    }
425
426    fn one(&mut self, node: &Node) {
427        match node {
428            Node::Heading { level, text } => {
429                let doc_level = if *level == 1 {
430                    0
431                } else {
432                    level.saturating_sub(1)
433                };
434                let self_ref = self.alloc.text();
435                // docling stores heading text unformatted: a heading that is one
436                // uniformly formatted span keeps its plain text; a *partially*
437                // formatted heading becomes an empty heading whose content is an
438                // inline group — which the chunker then yields as a chunk of its
439                // own (under the freshly-set empty heading).
440                let runs = crate::inline_runs_from_markdown(text);
441                if runs.len() <= 1 {
442                    let plain = runs
443                        .first()
444                        .map(|r| r.text.clone())
445                        .unwrap_or_else(|| text.clone());
446                    self.set_heading(doc_level, unescape_text(&plain));
447                } else {
448                    self.set_heading(doc_level, String::new());
449                    let body = unescape_text(text);
450                    self.emit(
451                        body.clone(),
452                        vec![ChunkItem {
453                            self_ref,
454                            kind: ChunkItemKind::Text,
455                            text: body,
456                        }],
457                    );
458                }
459            }
460            Node::Paragraph { text } => {
461                let t = text.trim();
462                let self_ref = self.alloc.text();
463                // A whole-paragraph display equation is a formula item; docling's
464                // chunk serializer re-wraps the raw latex in `$$…$$`.
465                if let Some(inner) = t
466                    .strip_prefix("$$")
467                    .and_then(|s| s.strip_suffix("$$"))
468                    .filter(|s| !s.is_empty())
469                {
470                    let body = format!("$${inner}$$");
471                    self.emit(
472                        body.clone(),
473                        vec![ChunkItem {
474                            self_ref,
475                            kind: ChunkItemKind::Text,
476                            text: body,
477                        }],
478                    );
479                    return;
480                }
481                self.emit_inline(text, self_ref);
482            }
483            Node::CheckboxItem { checked, text } => {
484                let self_ref = self.alloc.text();
485                let mark = if *checked { "- [x] " } else { "- [ ] " };
486                let body = format!("{mark}{}", unescape_text(text));
487                self.emit(
488                    body.clone(),
489                    vec![ChunkItem {
490                        self_ref,
491                        kind: ChunkItemKind::Text,
492                        text: body,
493                    }],
494                );
495            }
496            // An enriched display formula chunks like docling's formula item:
497            // the LaTeX is the chunk text.
498            Node::Formula { latex, .. } => {
499                let self_ref = self.alloc.text();
500                let body = format!("$${}$$", latex);
501                self.emit(
502                    body.clone(),
503                    vec![ChunkItem {
504                        self_ref,
505                        kind: ChunkItemKind::Text,
506                        text: body,
507                    }],
508                );
509            }
510            Node::Code { text, .. } => {
511                let self_ref = self.alloc.text();
512                let body = format!("```\n{}\n```", unescape_text(text));
513                self.emit(
514                    body.clone(),
515                    vec![ChunkItem {
516                        self_ref,
517                        kind: ChunkItemKind::Text,
518                        text: body,
519                    }],
520                );
521            }
522            Node::Table(t) => {
523                let self_ref = self.alloc.table();
524                let body = triplet_table_text(t);
525                self.emit(
526                    body.clone(),
527                    vec![ChunkItem {
528                        self_ref,
529                        kind: ChunkItemKind::Table,
530                        text: body,
531                    }],
532                );
533            }
534            Node::Picture { caption, .. } => {
535                let cap = caption.as_deref().filter(|c| !c.is_empty());
536                let cap_item = cap.map(|c| ChunkItem {
537                    self_ref: self.alloc.text(),
538                    kind: ChunkItemKind::Text,
539                    text: unescape_text(c),
540                });
541                self.alloc.picture();
542                // The picture itself serializes to the (empty) chunking image
543                // placeholder, and its caption is already consumed by the
544                // caption chunk — so only the caption text is emitted.
545                if let Some(cap_item) = cap_item {
546                    let body = cap_item.text.clone();
547                    self.emit(body, vec![cap_item]);
548                }
549            }
550            Node::Chart {
551                kind,
552                table,
553                caption,
554                ..
555            } => {
556                let cap = caption.as_deref().filter(|c| !c.is_empty());
557                let cap_item = cap.map(|c| ChunkItem {
558                    self_ref: self.alloc.text(),
559                    kind: ChunkItemKind::Text,
560                    text: unescape_text(c),
561                });
562                let pic_ref = self.alloc.picture();
563                // caption, humanized classification, then the chart's data grid
564                // as a (padded) markdown table — docling's picture serializer
565                // parts, joined with blank lines.
566                let mut parts: Vec<String> = Vec::new();
567                if let Some(ci) = &cap_item {
568                    parts.push(ci.text.clone());
569                }
570                parts.push(humanize_label(kind));
571                let grid = crate::markdown::render_table(table, false);
572                if !grid.is_empty() {
573                    parts.push(unescape_text(&grid));
574                }
575                let body = parts.join("\n\n");
576                // Re-serialized standalone (the hybrid window join), the picture
577                // carries its caption itself, while the caption *item* renders
578                // empty — docling's markdown serializer emits caption-label text
579                // only through the picture.
580                let pic_item = ChunkItem {
581                    self_ref: pic_ref,
582                    kind: ChunkItemKind::Picture,
583                    text: body.clone(),
584                };
585                let items = match cap_item {
586                    Some(mut ci) => {
587                        ci.text = String::new();
588                        vec![ci, pic_item]
589                    }
590                    None => vec![pic_item],
591                };
592                self.emit(body, items);
593            }
594            // A group on a non-body layer (a hidden spreadsheet sheet) carries
595            // no chunkable content, like every other non-body item.
596            Node::Group { layer: Some(_), .. } => {}
597            Node::Group { children, .. } => {
598                // A generic group is a structural container: docling recurses
599                // into it rather than chunking it whole.
600                self.alloc.group();
601                self.walk(children);
602            }
603            Node::FieldRegion { items } => {
604                // Each field part (marker / key / value) is its own text item,
605                // and docling chunks each one individually.
606                self.alloc.field_region();
607                for item in items {
608                    self.alloc.field_item();
609                    for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
610                        let self_ref = self.alloc.text();
611                        let body = unescape_text(part);
612                        self.emit(
613                            body.clone(),
614                            vec![ChunkItem {
615                                self_ref,
616                                kind: ChunkItemKind::Text,
617                                text: body,
618                            }],
619                        );
620                    }
621                }
622            }
623            Node::InlineGroup { md_text, runs, .. } => {
624                let self_ref = self.alloc.text();
625                self.emit_inline_with_runs(md_text, self_ref, runs);
626            }
627            Node::TextDump(text) => {
628                let self_ref = self.alloc.text();
629                let body = unescape_text(text);
630                self.emit(
631                    body.clone(),
632                    vec![ChunkItem {
633                        self_ref,
634                        kind: ChunkItemKind::Text,
635                        text: body,
636                    }],
637                );
638            }
639            // Layout provenance and comment annotations are transparent.
640            Node::Located { inner, .. } | Node::Commented { inner, .. } => self.one(inner),
641            // Non-body layers and doclang-only nodes don't reach the chunker
642            // (nor the JSON body).
643            Node::CommentSection { .. }
644            | Node::Furniture { .. }
645            | Node::PageFurniture { .. }
646            | Node::PageBreak
647            | Node::PageInfo { .. }
648            | Node::DoclangOnly(_) => {}
649            // Runs are grouped by `walk`; a stray single item (hand-built
650            // document, `Located` wrapper) still chunks instead of panicking.
651            Node::ListItem { .. } => self.sibling_lists(std::slice::from_ref(node)),
652        }
653    }
654}
655
656fn level_of(node: &Node) -> u8 {
657    match node {
658        Node::ListItem { level, .. } => *level,
659        _ => 0,
660    }
661}
662
663/// Render one sibling list as its markdown chunk text (indented items, same
664/// rules as the full markdown serializer's list rendering).
665fn render_list(items: &[Node]) -> String {
666    let mut lines: Vec<String> = Vec::new();
667    for item in items {
668        let Node::ListItem {
669            ordered,
670            number,
671            text,
672            level,
673            layer,
674            ..
675        } = item
676        else {
677            continue;
678        };
679        if layer.is_some() {
680            continue;
681        }
682        let indent = "    ".repeat(*level as usize);
683        let marker = if *ordered {
684            format!("{number}.")
685        } else {
686            "-".to_string()
687        };
688        lines.push(format!(
689            "{indent}{marker} {}",
690            unescape_text(&strip_image_markers(text))
691        ));
692    }
693    lines.join("\n")
694}
695
696/// Strip the Markdown image placeholders a list item's own images fold into
697/// its text (the chunking serializer's `image_placeholder` is empty, so
698/// docling's chunk text carries no marker), collapsing the newlines that
699/// carried them.
700fn strip_image_markers(text: &str) -> String {
701    if !text.contains("<!-- image -->") {
702        return text.to_string();
703    }
704    let cleaned: Vec<&str> = text
705        .split('\n')
706        .map(str::trim_end)
707        .filter(|l| *l != "<!-- image -->")
708        .collect();
709    cleaned.join("\n").trim_end().to_string()
710}
711
712/// docling-core's `_humanize_text`: underscores to spaces, first letter
713/// capitalized (`line_chart` → `Line chart`).
714fn humanize_label(label: &str) -> String {
715    let text = label.replace('_', " ");
716    let mut chars = text.chars();
717    match chars.next() {
718        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
719        None => text,
720    }
721}
722
723/// docling's `TripletTableSerializer` over `export_to_dataframe` semantics: the
724/// leading rows carrying column-header cells become the dataframe's column
725/// names (multiple header rows join per column with `.`; no header rows at all
726/// yield pandas' integer column names), the rest are data rows; the dataframe
727/// is then rendered as `row, column = value` sentences (with the header-only /
728/// single-column special cases and the plain-text flatten fallback).
729fn triplet_table_text(t: &Table) -> String {
730    let rows: Vec<Vec<String>> = t
731        .rows
732        .iter()
733        .enumerate()
734        .map(|(ri, r)| (0..r.len()).map(|ci| cell_chunk_text(t, ri, ci)).collect())
735        .collect();
736    let num_rows = rows.len();
737    let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
738    if num_rows == 0 || num_cols == 0 {
739        return String::new();
740    }
741    let cell = |r: usize, c: usize| -> &str {
742        rows.get(r)
743            .and_then(|row| row.get(c))
744            .map(String::as_str)
745            .unwrap_or("")
746    };
747
748    // The header block is the leading run of rows on which a column-header
749    // cell *starts* (docling-core#756): the grid replicates a spanning header
750    // into every row it covers, and the rows beneath it are data, not more
751    // header. Unlike the Markdown serializer there is no "no flags -> row 0"
752    // fallback here: pandas then gets integer column names.
753    let num_headers = {
754        let derived;
755        let cells: &[crate::TableCell] = match &t.cells {
756            Some(c) if !c.is_empty() => c,
757            _ => {
758                derived = t.derive_cells();
759                &derived
760            }
761        };
762        (0..num_rows)
763            .take_while(|&r| cells.iter().any(|c| c.column_header && c.start_row == r))
764            .count()
765    };
766
767    // Column names: header-row texts joined per column with '.', or the integer
768    // positions when there are no header rows.
769    let columns: Vec<String> = if num_headers > 0 {
770        (0..num_cols)
771            .map(|c| {
772                let mut name = String::new();
773                for r in 0..num_headers {
774                    if !name.is_empty() {
775                        name.push('.');
776                    }
777                    name.push_str(cell(r, c));
778                }
779                name
780            })
781            .collect()
782    } else {
783        (0..num_cols).map(|c| c.to_string()).collect()
784    };
785    let data_rows = num_headers..num_rows;
786    let n_data = data_rows.len();
787
788    // Header-only table: emit the header texts directly.
789    if n_data == 0 {
790        return columns
791            .iter()
792            .map(|s| s.trim())
793            .filter(|s| !s.is_empty())
794            .collect::<Vec<_>>()
795            .join(". ");
796    }
797
798    let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
799    let text = if num_cols == 1 {
800        // Single-column: the first data row is the column name, the rest are
801        // values (a single data row emits its cell text alone).
802        let col_name = data(0, 0).trim().to_string();
803        if n_data == 1 {
804            col_name
805        } else {
806            (1..n_data)
807                .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
808                .collect::<Vec<_>>()
809                .join(". ")
810        }
811    } else {
812        // Triplets over the dataframe with the column names copied as row 0.
813        let mut parts = Vec::new();
814        for r in 0..n_data {
815            for (c, col_name) in columns.iter().enumerate().skip(1) {
816                parts.push(format!(
817                    "{}, {} = {}",
818                    data(r, 0).trim(),
819                    col_name.trim(),
820                    data(r, c).trim()
821                ));
822            }
823        }
824        parts.join(". ")
825    };
826    if !text.is_empty() {
827        return text;
828    }
829
830    // Last-resort flatten: the data rows' non-blank cells joined with '. '
831    // (the header rows are the dataframe's columns, so they are not included).
832    (0..n_data)
833        .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
834        .map(|(r, c)| data(r, c).trim())
835        .filter(|s| !s.is_empty())
836        .collect::<Vec<_>>()
837        .join(". ")
838}
839
840/// Split a markdown-flavoured text into docling's inline-item granularity: a
841/// hyperlink / formatted span / inline formula is its own document item in
842/// docling's model, with plain text runs between them. Returns the standalone
843/// serialization of each item (`[text](url)`, `**bold**`, a formula re-wrapped
844/// as `$$latex$$`, plain text), or a single-element vector when the text is one
845/// uniform item. The single space docling's serializer inserts between inline
846/// items is stripped from the adjacent plain runs.
847fn inline_segments(md: &str) -> Vec<String> {
848    inline_segments_tagged(md)
849        .into_iter()
850        .map(|(t, _)| t)
851        .collect()
852}
853
854/// Like [`inline_segments`], with each segment tagged `true` when it came from
855/// plain (unmarked) text — those may still need splitting at run boundaries
856/// invisible in markdown (underline, soft breaks).
857fn inline_segments_tagged(md: &str) -> Vec<(String, bool)> {
858    let chars: Vec<char> = md.chars().collect();
859    let n = chars.len();
860    let find = |from: usize, pat: &str| -> Option<usize> {
861        let hay: String = chars[from..].iter().collect();
862        hay.find(pat).map(|p| from + hay[..p].chars().count())
863    };
864    let mut out: Vec<(String, bool)> = Vec::new();
865    let mut plain = String::new();
866    let mut after_span = false;
867
868    fn flush(
869        out: &mut Vec<(String, bool)>,
870        plain: &mut String,
871        before_span: bool,
872        after_span: bool,
873    ) {
874        let mut p = std::mem::take(plain);
875        if after_span {
876            if let Some(rest) = p.strip_prefix(' ') {
877                p = rest.to_string();
878            }
879        }
880        if before_span {
881            if let Some(rest) = p.strip_suffix(' ') {
882                p = rest.to_string();
883            }
884        }
885        if !p.is_empty() {
886            out.push((unescape_text(&p), true));
887        }
888    }
889
890    let mut i = 0;
891    while i < n {
892        let rest: String = chars[i..].iter().collect();
893        // A hyperlink span (not an image): the whole `[text](url)` is one item.
894        // The URL may itself contain balanced parentheses (`/Duck_(film)`),
895        // so the closing `)` is found by paren depth, not first match.
896        if chars[i] == '[' && !rest.starts_with("[](") {
897            // The label may itself contain balanced brackets (`[[ 1 ]](#ref)`
898            // has label `[ 1 ]`), but an *unbalanced* `[` means this bracket is
899            // plain text preceding a real link (`[ [*note*](url) ]`).
900            let balanced = |c: usize| {
901                let mut d = 0i32;
902                for &ch in &chars[i + 1..c] {
903                    match ch {
904                        '[' => d += 1,
905                        ']' => d -= 1,
906                        _ => {}
907                    }
908                }
909                d == 0
910            };
911            if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
912                let mut depth = 0usize;
913                let mut url_end = None;
914                for (k, &c) in chars.iter().enumerate().skip(close + 2) {
915                    match c {
916                        '(' => depth += 1,
917                        ')' => {
918                            if depth == 0 {
919                                url_end = Some(k);
920                                break;
921                            }
922                            depth -= 1;
923                        }
924                        _ => {}
925                    }
926                }
927                if let Some(endp) = url_end {
928                    flush(&mut out, &mut plain, true, after_span);
929                    out.push((
930                        unescape_text(&chars[i..=endp].iter().collect::<String>()),
931                        false,
932                    ));
933                    i = endp + 1;
934                    after_span = true;
935                    continue;
936                }
937            }
938        }
939        // A formatted span; longest markers first. An inline code span is a
940        // code item in docling's model, whose standalone form is a fenced block.
941        let mut matched = false;
942        for marker in ["***", "**", "*", "~~", "`"] {
943            if rest.starts_with(marker) {
944                let mlen = marker.chars().count();
945                if let Some(end) = find(i + mlen, marker) {
946                    // A whitespace-only span (`* *` from a literal asterisk in
947                    // running text next to a real italic) is not a docling run:
948                    // treat the marker as plain text.
949                    let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
950                    if end > i + mlen && !inner_blank {
951                        flush(&mut out, &mut plain, true, after_span);
952                        if marker == "`" {
953                            let inner: String = chars[i + 1..end].iter().collect();
954                            out.push((format!("```\n{}\n```", unescape_text(&inner)), false));
955                        } else {
956                            out.push((
957                                unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
958                                false,
959                            ));
960                        }
961                        i = end + mlen;
962                        after_span = true;
963                        matched = true;
964                    }
965                }
966                break;
967            }
968        }
969        if matched {
970            continue;
971        }
972        // A literal `$$` inside running text is not an inline formula: copy it
973        // through as plain characters.
974        if rest.starts_with("$$") {
975            plain.push_str("$$");
976            i += 2;
977            continue;
978        }
979        // An inline formula: standalone it re-serializes in display form.
980        if chars[i] == '$' {
981            if let Some(end) = find(i + 1, "$") {
982                if end > i + 1 {
983                    flush(&mut out, &mut plain, true, after_span);
984                    let latex: String = chars[i + 1..end].iter().collect();
985                    out.push((format!("$${latex}$$"), false));
986                    i = end + 1;
987                    after_span = true;
988                    continue;
989                }
990            }
991        }
992        plain.push(chars[i]);
993        i += 1;
994    }
995    flush(&mut out, &mut plain, false, after_span);
996    if out.is_empty() {
997        out.push((unescape_text(md), true));
998    }
999    out
1000}
1001
1002/// Split a plain markdown segment at run boundaries the markdown cannot show
1003/// (an underlined run, a `<sub>`/`<sup>` run): when a consecutive window of
1004/// two or more unmarked runs exactly covers the segment, each run is its own
1005/// document item.
1006fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1007    let target = segment.trim();
1008    if target.is_empty() {
1009        return None;
1010    }
1011    let plainish =
1012        |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1013    let fully_plain =
1014        |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1015    let unmarked: Vec<(&str, bool)> = runs
1016        .iter()
1017        .filter(|r| plainish(r))
1018        .map(|r| (r.text.as_str(), fully_plain(r)))
1019        .collect();
1020    for start in 0..unmarked.len() {
1021        let mut rest = target;
1022        let mut taken: Vec<(String, bool)> = Vec::new();
1023        for (t, fully) in &unmarked[start..] {
1024            let t = t.trim();
1025            if t.is_empty() {
1026                continue;
1027            }
1028            match rest.strip_prefix(t) {
1029                Some(r) => {
1030                    taken.push((unescape_text(t), *fully));
1031                    rest = r.trim_start();
1032                    if rest.is_empty() {
1033                        break;
1034                    }
1035                }
1036                None => break,
1037            }
1038        }
1039        if rest.is_empty() && taken.len() >= 2 {
1040            // Consecutive fully-plain pieces (no underline / sub / sup) are one
1041            // annotation in docling's model — `simplify_text_elements` merges
1042            // them joined with a space, so they never split between themselves.
1043            // Only an underline / sub / sup run is a genuine boundary.
1044            let mut merged: Vec<(String, bool)> = Vec::new();
1045            for (t, fully) in taken {
1046                match merged.last_mut() {
1047                    Some((last, true)) if fully => {
1048                        last.push(' ');
1049                        last.push_str(&t);
1050                    }
1051                    _ => merged.push((t, fully)),
1052                }
1053            }
1054            if merged.len() >= 2 {
1055                return Some(merged.into_iter().map(|(t, _)| t).collect());
1056            }
1057            return None;
1058        }
1059    }
1060    None
1061}
1062
1063/// A table cell's text for the triplet serializer. A *rich* cell (one carrying
1064/// block content) is re-serialized the way docling's chunking serializer sees
1065/// it: paragraphs joined with blank lines, a nested table as its own triplet
1066/// sentences, pictures as an empty placeholder. Plain cells use the flat text
1067/// with the markdown image placeholder stripped (the chunking serializer's
1068/// `image_placeholder` is empty).
1069fn cell_chunk_text(t: &Table, r: usize, c: usize) -> String {
1070    if let Some(blocks) = t
1071        .cell_blocks
1072        .as_ref()
1073        .and_then(|b| b.get(r))
1074        .and_then(|row| row.get(c))
1075        .filter(|b| !b.is_empty())
1076    {
1077        let mut parts: Vec<String> = Vec::new();
1078        for node in blocks.iter() {
1079            let part = block_chunk_text(node);
1080            if !part.is_empty() {
1081                parts.push(part);
1082            }
1083        }
1084        return parts.join("\n\n");
1085    }
1086    let flat = t
1087        .rows
1088        .get(r)
1089        .and_then(|row| row.get(c))
1090        .map(String::as_str)
1091        .unwrap_or("");
1092    unescape_text(flat)
1093        .replace("<!-- image -->", "")
1094        .trim()
1095        .to_string()
1096}
1097
1098/// One block of a rich cell, serialized for chunking.
1099fn block_chunk_text(node: &Node) -> String {
1100    match node {
1101        Node::Paragraph { text } => unescape_text(text),
1102        Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1103        Node::Code { text, .. } => format!("```\n{}\n```", unescape_text(text)),
1104        Node::Table(inner) => triplet_table_text(inner),
1105        Node::Picture { caption, .. } => caption
1106            .as_deref()
1107            .filter(|c| !c.is_empty())
1108            .map(unescape_text)
1109            .unwrap_or_default(),
1110        Node::ListItem {
1111            ordered,
1112            number,
1113            text,
1114            ..
1115        } => {
1116            let marker = if *ordered {
1117                format!("{number}.")
1118            } else {
1119                "-".to_string()
1120            };
1121            format!("{marker} {}", unescape_text(text))
1122        }
1123        Node::CheckboxItem { checked, text } => {
1124            let mark = if *checked { "- [x] " } else { "- [ ] " };
1125            format!("{mark}{}", unescape_text(text))
1126        }
1127        Node::Heading { text, .. } => unescape_text(text),
1128        Node::Located { inner, .. } | Node::Commented { inner, .. } => block_chunk_text(inner),
1129        Node::Group { layer: Some(_), .. } => String::new(),
1130        Node::Group { children, .. } => children
1131            .iter()
1132            .map(block_chunk_text)
1133            .filter(|s| !s.is_empty())
1134            .collect::<Vec<_>>()
1135            .join("\n"),
1136        _ => String::new(),
1137    }
1138}
1139
1140/// Reverse the model's baked markdown text escaping — same mapping as the JSON
1141/// exporter (docling chunks carry raw text).
1142fn unescape_text(s: &str) -> String {
1143    s.replace("&lt;", "<")
1144        .replace("&gt;", ">")
1145        .replace("&amp;", "&")
1146        .replace("\\_", "_")
1147}
1148
1149// ---------------------------------------------------------------------------
1150// Hybrid chunker
1151// ---------------------------------------------------------------------------
1152
1153/// Token counting for [`HybridChunker`] — docling's `BaseTokenizer`.
1154pub trait ChunkTokenizer {
1155    /// Number of tokens in `text` (no special tokens).
1156    fn count_tokens(&self, text: &str) -> usize;
1157    /// The chunk budget (docling's `max_tokens`, e.g. 256 for MiniLM).
1158    fn max_tokens(&self) -> usize;
1159}
1160
1161/// Tokenization-aware chunker on top of [`HierarchicalChunker`] — docling's
1162/// `HybridChunker` with default parameters (`merge_peers`,
1163/// `repeat_table_header` on; `omit_header_on_overflow` off).
1164pub struct HybridChunker<T: ChunkTokenizer> {
1165    tokenizer: T,
1166    merge_peers: bool,
1167}
1168
1169impl<T: ChunkTokenizer> HybridChunker<T> {
1170    pub fn new(tokenizer: T) -> Self {
1171        Self {
1172            tokenizer,
1173            merge_peers: true,
1174        }
1175    }
1176
1177    /// Disable merging of undersized same-heading neighbours.
1178    pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1179        self.merge_peers = merge_peers;
1180        self
1181    }
1182
1183    pub fn max_tokens(&self) -> usize {
1184        self.tokenizer.max_tokens()
1185    }
1186
1187    /// Chunk the document.
1188    pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1189        let mut chunks = Vec::new();
1190        self.chunk_with(doc, &mut |c| {
1191            chunks.push(c);
1192            true
1193        });
1194        chunks
1195    }
1196
1197    /// Stream the chunks: each hierarchical chunk is split against the token
1198    /// budget as the document walk produces it, and the peer merge flushes a
1199    /// merged chunk to `sink` as soon as its window closes (a chunk with
1200    /// different headings arrives, or the budget fills). A `false` return from
1201    /// `sink` cancels the chunking. [`Self::chunk`] is this with a collecting
1202    /// sink — the chunks and their order are identical.
1203    pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1204        let mut merger = PeerMerger::default();
1205        let mut alive = true;
1206        HierarchicalChunker.chunk_with(doc, &mut |c| {
1207            for split in self.split_by_doc_items(c) {
1208                for chunk in self.split_using_plain_text(split) {
1209                    if !alive {
1210                        return false;
1211                    }
1212                    alive = if self.merge_peers {
1213                        self.merge_push(&mut merger, chunk, sink)
1214                    } else {
1215                        sink(chunk)
1216                    };
1217                }
1218            }
1219            alive
1220        });
1221        if alive {
1222            self.merge_flush(&mut merger, sink);
1223        }
1224    }
1225
1226    fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1227        self.tokenizer.count_tokens(&contextualize(chunk))
1228    }
1229
1230    /// docling's `_make_chunk_from_doc_items`: single-item chunks keep their
1231    /// text; multi-item windows re-join the items' standalone serializations.
1232    fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1233        let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1234        let text = if chunk.doc_items.len() == 1 {
1235            chunk.text.clone()
1236        } else {
1237            doc_items
1238                .iter()
1239                .filter(|it| !it.text.is_empty())
1240                .map(|it| it.text.as_str())
1241                .collect::<Vec<_>>()
1242                .join("\n")
1243        };
1244        DocChunk {
1245            text,
1246            headings: chunk.headings.clone(),
1247            doc_items,
1248        }
1249    }
1250
1251    fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1252        if chunk.doc_items.is_empty() {
1253            return vec![chunk];
1254        }
1255        let max = self.max_tokens();
1256        let num_items = chunk.doc_items.len();
1257        let mut chunks = Vec::new();
1258        let mut window_start = 0usize;
1259        let mut window_end = 0usize; // inclusive
1260        while window_end < num_items {
1261            let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1262            if self.count_chunk_tokens(&new_chunk) <= max {
1263                if window_end < num_items - 1 {
1264                    window_end += 1;
1265                    continue;
1266                } else {
1267                    window_end = num_items; // last loop
1268                }
1269            } else if window_start == window_end {
1270                // One item that doesn't fit: keep it; the plain-text splitter
1271                // takes over.
1272                window_end += 1;
1273                window_start = window_end;
1274            } else {
1275                // The window without its last item fit; flush that and start a
1276                // new window at the current item.
1277                new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1278                window_start = window_end;
1279            }
1280            chunks.push(new_chunk);
1281        }
1282        chunks
1283    }
1284
1285    fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1286        let total = self.count_chunk_tokens(&chunk);
1287        let max = self.max_tokens();
1288        if total <= max {
1289            return vec![chunk];
1290        }
1291        let text_len = self.tokenizer.count_tokens(&chunk.text);
1292        let other_len = total - text_len;
1293        if other_len >= max {
1294            // Headings alone exceed the budget: drop them and retry.
1295            let stripped = DocChunk {
1296                headings: None,
1297                ..chunk
1298            };
1299            return self.split_using_plain_text(stripped);
1300        }
1301        let available = max - other_len;
1302
1303        let segments =
1304            if chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table {
1305                // Table: split line-based, repeating headers. The triplet
1306                // serializer has no header lines, so this is a line-preserving
1307                // split of the table text. (docling constructs the line chunker
1308                // with the *tokenizer's* max_tokens — the `max_tokens=available`
1309                // argument is silently dropped by pydantic — so the line budget is
1310                // the full window, not `available`.)
1311                let lines: Vec<String> = chunk
1312                    .text
1313                    .split('\n')
1314                    .filter(|l| !l.trim().is_empty())
1315                    .map(|l| l.to_string())
1316                    .collect();
1317                line_chunk_text(&lines, &self.tokenizer, max)
1318            } else {
1319                semchunk(&chunk.text, available, &self.tokenizer)
1320            };
1321        segments
1322            .into_iter()
1323            .map(|s| DocChunk {
1324                text: s,
1325                headings: chunk.headings.clone(),
1326                doc_items: chunk.doc_items.clone(),
1327            })
1328            .collect()
1329    }
1330
1331    /// One step of docling's `_merge_chunks_with_matching_metadata`, streamed:
1332    /// extend the window with `chunk` when its headings match the window's and
1333    /// the merged candidate stays within budget, otherwise flush the window to
1334    /// `sink` and start a new one at `chunk`. Returns `false` once the sink
1335    /// cancels.
1336    fn merge_push(
1337        &self,
1338        m: &mut PeerMerger,
1339        chunk: DocChunk,
1340        sink: &mut dyn FnMut(DocChunk) -> bool,
1341    ) -> bool {
1342        if m.window.is_empty() {
1343            m.window.push(chunk);
1344            return true;
1345        }
1346        let candidate = DocChunk {
1347            text: m
1348                .window
1349                .iter()
1350                .map(|c| c.text.as_str())
1351                .chain([chunk.text.as_str()])
1352                .collect::<Vec<_>>()
1353                .join("\n"),
1354            headings: m.window[0].headings.clone(),
1355            doc_items: m
1356                .window
1357                .iter()
1358                .flat_map(|c| c.doc_items.iter().cloned())
1359                .chain(chunk.doc_items.iter().cloned())
1360                .collect(),
1361        };
1362        if chunk.headings == m.window[0].headings
1363            && self.count_chunk_tokens(&candidate) <= self.max_tokens()
1364        {
1365            m.window.push(chunk);
1366            m.merged = Some(candidate);
1367            true
1368        } else {
1369            let alive = self.merge_flush(m, sink);
1370            m.window.push(chunk);
1371            alive
1372        }
1373    }
1374
1375    /// Flush the merge window: a single chunk passes through unchanged, a
1376    /// multi-chunk window emits its precomputed merge. Returns `false` once
1377    /// the sink cancels.
1378    fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
1379        let alive = if m.window.len() == 1 {
1380            sink(m.window.pop().expect("single-chunk window"))
1381        } else if !m.window.is_empty() {
1382            m.window.clear();
1383            sink(m.merged.take().expect("multi-chunk window has a merge"))
1384        } else {
1385            true
1386        };
1387        m.merged = None;
1388        alive
1389    }
1390}
1391
1392/// The in-flight peer-merge window of [`HybridChunker::chunk_with`].
1393#[derive(Default)]
1394struct PeerMerger {
1395    window: Vec<DocChunk>,
1396    merged: Option<DocChunk>,
1397}
1398
1399// ---------------------------------------------------------------------------
1400// Line-based token chunking (docling's LineBasedTokenChunker, empty prefix)
1401// ---------------------------------------------------------------------------
1402
1403/// Pack lines into chunks of at most `max_tokens`, splitting a line only when
1404/// it exceeds the budget on its own — docling's `LineBasedTokenChunker
1405/// .chunk_text` with an empty prefix (which is what the triplet table
1406/// serializer yields). Reproduces its exact output, including the `\n` it
1407/// prepends to a carried-over segment of an oversized line.
1408fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
1409    let mut chunks: Vec<String> = Vec::new();
1410    let mut current = String::new();
1411    let mut current_len = 0usize;
1412
1413    for line in lines {
1414        let mut remaining: Vec<char> = line.chars().collect();
1415        loop {
1416            let rem_str: String = remaining.iter().collect();
1417            let line_tokens = tok.count_tokens(&rem_str);
1418            let available = max_tokens.saturating_sub(current_len);
1419
1420            if line_tokens <= available {
1421                current.push_str(&rem_str);
1422                current_len += line_tokens;
1423                break;
1424            }
1425            if line_tokens <= max_tokens {
1426                chunks.push(std::mem::take(&mut current));
1427                current_len = 0;
1428                continue;
1429            }
1430            // Too large even for an empty chunk: split off what fits.
1431            let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
1432            let mut rest = rest;
1433            if take.is_empty() {
1434                if rest.is_empty() {
1435                    break;
1436                }
1437                take = rest[..1].iter().collect();
1438                rest = rest[1..].to_vec();
1439            }
1440            current.push('\n');
1441            current.push_str(&take);
1442            chunks.push(std::mem::take(&mut current));
1443            current_len = 0;
1444            remaining = rest;
1445        }
1446    }
1447    if !current.is_empty() {
1448        chunks.push(current);
1449    }
1450    chunks
1451}
1452
1453/// Binary-search the longest char-prefix of `text` within `token_limit`
1454/// tokens, preferring to break at the last ASCII space — docling's
1455/// `split_by_token_limit`.
1456fn split_by_token_limit<T: ChunkTokenizer>(
1457    text: &[char],
1458    token_limit: usize,
1459    tok: &T,
1460) -> (String, Vec<char>) {
1461    if token_limit == 0 || text.is_empty() {
1462        return (String::new(), text.to_vec());
1463    }
1464    let full: String = text.iter().collect();
1465    if tok.count_tokens(&full) <= token_limit {
1466        return (full, Vec::new());
1467    }
1468    let (mut lo, mut hi) = (0usize, text.len());
1469    let mut best: Option<usize> = None;
1470    while lo <= hi {
1471        let mid = (lo + hi) / 2;
1472        let head: String = text[..mid].iter().collect();
1473        if tok.count_tokens(&head) <= token_limit {
1474            best = Some(mid);
1475            lo = mid + 1;
1476        } else {
1477            if mid == 0 {
1478                break;
1479            }
1480            hi = mid - 1;
1481        }
1482    }
1483    let mut best_idx = match best {
1484        Some(b) if b > 0 => b,
1485        _ => return (String::new(), text.to_vec()),
1486    };
1487    // Snap back to the last space, if that leaves a non-empty head.
1488    if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
1489        if pos > 0 {
1490            best_idx = pos;
1491        }
1492    }
1493    (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
1494}
1495
1496// ---------------------------------------------------------------------------
1497// semchunk port (the plain-text splitter HybridChunker delegates to)
1498// ---------------------------------------------------------------------------
1499
1500/// Semantically meaningful non-whitespace splitters, most desirable first.
1501const NON_WS_SPLITTERS: &[&str] = &[
1502    ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
1503    "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
1504];
1505
1506/// Split `text` into chunks of at most `chunk_size` tokens using the most
1507/// semantically meaningful splitter available — the `semchunk` algorithm
1508/// docling's HybridChunker delegates plain-text splitting to.
1509pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
1510    let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
1511    let mut counter = |s: &str| -> usize {
1512        if let Some(n) = cache.get(s) {
1513            return *n;
1514        }
1515        let n = tok.count_tokens(s);
1516        cache.insert(s.to_string(), n);
1517        n
1518    };
1519    let chunks = semchunk_rec(text, chunk_size, &mut counter);
1520    // top-level: drop empty / all-whitespace chunks
1521    chunks
1522        .into_iter()
1523        .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
1524        .collect()
1525}
1526
1527/// One recursion level of semchunk: split, merge windows back up to size, and
1528/// recurse into oversized splits.
1529fn semchunk_rec(
1530    text: &str,
1531    chunk_size: usize,
1532    counter: &mut dyn FnMut(&str) -> usize,
1533) -> Vec<String> {
1534    let (splitter, splitter_is_ws, splits) = split_text(text);
1535
1536    let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
1537    let mut cum_lens = Vec::with_capacity(splits.len() + 1);
1538    cum_lens.push(0usize);
1539    for l in &split_lens {
1540        cum_lens.push(cum_lens.last().unwrap() + l);
1541    }
1542    let num_splits_plus_one = splits.len() + 1;
1543
1544    let mut chunks: Vec<String> = Vec::new();
1545    let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
1546
1547    for i in 0..splits.len() {
1548        if skips.contains(&i) {
1549            continue;
1550        }
1551        let split = &splits[i];
1552        if counter(split) > chunk_size {
1553            let inner = semchunk_rec(split, chunk_size, counter);
1554            chunks.extend(inner);
1555        } else {
1556            let (end, merged) = merge_splits(
1557                &splits,
1558                &cum_lens,
1559                chunk_size,
1560                &splitter,
1561                counter,
1562                i,
1563                num_splits_plus_one,
1564            );
1565            for j in (i + 1)..end {
1566                skips.insert(j);
1567            }
1568            chunks.push(merged);
1569        }
1570        // Re-attach a non-whitespace splitter to the last chunk (or emit it as
1571        // its own chunk if it doesn't fit).
1572        let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
1573        if !splitter_is_ws && !is_last {
1574            let with_splitter = format!(
1575                "{}{}",
1576                chunks.last().map(String::as_str).unwrap_or(""),
1577                splitter
1578            );
1579            if counter(&with_splitter) <= chunk_size {
1580                if let Some(last) = chunks.last_mut() {
1581                    *last = with_splitter;
1582                } else {
1583                    chunks.push(with_splitter);
1584                }
1585            } else {
1586                chunks.push(splitter.clone());
1587            }
1588        }
1589    }
1590    chunks
1591}
1592
1593/// docling/semchunk's `merge_splits`: extend the window with a cum-length-guided
1594/// binary search until the token budget is hit.
1595fn merge_splits(
1596    splits: &[String],
1597    cum_lens: &[usize],
1598    chunk_size: usize,
1599    splitter: &str,
1600    counter: &mut dyn FnMut(&str) -> usize,
1601    start: usize,
1602    high_init: usize,
1603) -> (usize, String) {
1604    let mut average = 0.2f64;
1605    let mut low = start;
1606    let mut high = high_init;
1607    let offset = cum_lens[start];
1608    let mut target = offset as f64 + (chunk_size as f64 * average);
1609
1610    while low < high {
1611        let i = bisect_left(cum_lens, target, low, high);
1612        let midpoint = i.min(high - 1);
1613        let joined = splits[start..midpoint.max(start)].join(splitter);
1614        let tokens = counter(&joined);
1615        let local_cum = cum_lens[midpoint] - offset;
1616        if local_cum > 0 && tokens > 0 {
1617            average = local_cum as f64 / tokens as f64;
1618            target = offset as f64 + (chunk_size as f64 * average);
1619        }
1620        if tokens > chunk_size {
1621            high = midpoint;
1622        } else {
1623            low = midpoint + 1;
1624        }
1625    }
1626    let end = low - 1;
1627    (end, splits[start..end.max(start)].join(splitter))
1628}
1629
1630fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
1631    while low < high {
1632        let mid = (low + high) / 2;
1633        if (sorted[mid] as f64) < target {
1634            low = mid + 1;
1635        } else {
1636            high = mid;
1637        }
1638    }
1639    low
1640}
1641
1642/// semchunk's `_split_text`: pick the most desirable splitter present.
1643fn split_text(text: &str) -> (String, bool, Vec<String>) {
1644    // Longest run of newlines/carriage returns.
1645    if text.contains('\n') || text.contains('\r') {
1646        let splitter = longest_run(text, |c| c == '\n' || c == '\r');
1647        return (splitter.clone(), true, split_on(text, &splitter));
1648    }
1649    // Longest run of tabs.
1650    if text.contains('\t') {
1651        let splitter = longest_run(text, |c| c == '\t');
1652        return (splitter.clone(), true, split_on(text, &splitter));
1653    }
1654    // Longest run of whitespace.
1655    if text.chars().any(char::is_whitespace) {
1656        let splitter = longest_run(text, char::is_whitespace);
1657        if splitter.chars().count() == 1 {
1658            // Prefer a whitespace char preceded by a semantic splitter.
1659            for preceder in NON_WS_SPLITTERS {
1660                if let Some((ws, parts)) = split_after_preceder(text, preceder) {
1661                    return (ws, true, parts);
1662                }
1663            }
1664        }
1665        return (splitter.clone(), true, split_on(text, &splitter));
1666    }
1667    // Most desirable semantic splitter present.
1668    for s in NON_WS_SPLITTERS {
1669        if text.contains(s) {
1670            return (s.to_string(), false, split_on(text, s));
1671        }
1672    }
1673    // No splitter at all: split into characters.
1674    (
1675        String::new(),
1676        true,
1677        text.chars().map(|c| c.to_string()).collect(),
1678    )
1679}
1680
1681/// The longest maximal run of chars matching `pred` (first one wins ties).
1682fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
1683    let mut best = String::new();
1684    let mut cur = String::new();
1685    for c in text.chars() {
1686        if pred(c) {
1687            cur.push(c);
1688        } else {
1689            if cur.chars().count() > best.chars().count() {
1690                best = cur.clone();
1691            }
1692            cur.clear();
1693        }
1694    }
1695    if cur.chars().count() > best.chars().count() {
1696        best = cur;
1697    }
1698    best
1699}
1700
1701fn split_on(text: &str, splitter: &str) -> Vec<String> {
1702    text.split(splitter).map(str::to_string).collect()
1703}
1704
1705/// Python: `re.search(rf'{p}(\s)', text)` → the first whitespace char preceded
1706/// by `p`; then `re.split(rf'(?<={p}){s}', text)` — split at every occurrence
1707/// of that whitespace char immediately preceded by `p`.
1708fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
1709    let chars: Vec<char> = text.chars().collect();
1710    let p: Vec<char> = preceder.chars().collect();
1711    let mut ws: Option<char> = None;
1712    for i in p.len()..chars.len() {
1713        if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
1714            ws = Some(chars[i]);
1715            break;
1716        }
1717    }
1718    let ws = ws?;
1719    let mut parts = Vec::new();
1720    let mut cur = String::new();
1721    let mut i = 0usize;
1722    while i < chars.len() {
1723        if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
1724            parts.push(std::mem::take(&mut cur));
1725            i += 1;
1726            continue;
1727        }
1728        cur.push(chars[i]);
1729        i += 1;
1730    }
1731    parts.push(cur);
1732    Some((ws.to_string(), parts))
1733}
1734
1735// ---------------------------------------------------------------------------
1736// HuggingFace tokenizer (feature `chunking`)
1737// ---------------------------------------------------------------------------
1738
1739#[cfg(feature = "chunking")]
1740mod hf {
1741    use super::ChunkTokenizer;
1742
1743    /// Where `scripts/install/download_dependencies.sh` puts the hybrid
1744    /// chunker's default tokenizer (all-MiniLM-L6-v2's `tokenizer.json`),
1745    /// relative to the process's working directory — the same convention as
1746    /// the `.models/` ONNX files.
1747    pub const DEFAULT_TOKENIZER_PATH: &str = ".models/chunk/tokenizer.json";
1748
1749    /// Resolve the tokenizer path for the hybrid chunker: an explicit path
1750    /// wins; otherwise fall back to [`DEFAULT_TOKENIZER_PATH`] when it exists
1751    /// on disk. Errors with the download instructions when neither is
1752    /// available.
1753    pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
1754        if let Some(p) = explicit {
1755            return Ok(p.to_string());
1756        }
1757        let resolved = crate::assets::resolve(DEFAULT_TOKENIZER_PATH);
1758        if std::path::Path::new(&resolved).exists() {
1759            return Ok(resolved);
1760        }
1761        Err(format!(
1762            "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
1763             {DEFAULT_TOKENIZER_PATH} does not exist — run \
1764             scripts/install/download_dependencies.sh (or pass an explicit path)"
1765        ))
1766    }
1767
1768    /// [`ChunkTokenizer`] backed by a HuggingFace `tokenizer.json` — the Rust
1769    /// analogue of docling's `HuggingFaceTokenizer` (whose default is
1770    /// `sentence-transformers/all-MiniLM-L6-v2` with `max_tokens` 256).
1771    pub struct HuggingFaceTokenizer {
1772        tok: tokenizers::Tokenizer,
1773        max_tokens: usize,
1774    }
1775
1776    impl HuggingFaceTokenizer {
1777        /// Load the tokenizer from an explicit path, or from
1778        /// [`DEFAULT_TOKENIZER_PATH`] when `path` is `None` (see
1779        /// [`resolve_tokenizer_path`]).
1780        pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
1781            Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
1782        }
1783
1784        /// Load a `tokenizer.json`. `max_tokens` is the chunk budget (docling
1785        /// resolves it from the model's `sentence_bert_config.json`; for the
1786        /// default MiniLM model that is 256).
1787        pub fn from_file(
1788            path: impl AsRef<std::path::Path>,
1789            max_tokens: usize,
1790        ) -> Result<Self, String> {
1791            let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
1792                .map_err(|e| format!("failed to load tokenizer: {e}"))?;
1793            // Counting must see the full text (docling tokenizes without
1794            // truncation, padding, or special tokens — MiniLM's tokenizer.json
1795            // ships with fixed-length padding enabled, which would make every
1796            // short string count as the padded length).
1797            let _ = tok.with_truncation(None);
1798            tok.with_padding(None);
1799            Ok(Self { tok, max_tokens })
1800        }
1801    }
1802
1803    impl ChunkTokenizer for HuggingFaceTokenizer {
1804        fn count_tokens(&self, text: &str) -> usize {
1805            self.tok
1806                .encode(text, false)
1807                .map(|e| e.get_tokens().len())
1808                .unwrap_or(0)
1809        }
1810        fn max_tokens(&self) -> usize {
1811            self.max_tokens
1812        }
1813    }
1814}
1815
1816#[cfg(feature = "chunking")]
1817pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
1818
1819// ---------------------------------------------------------------------------
1820// Window chunker (feature `chunking`) — docling-rag's Markdown window chunker
1821// ---------------------------------------------------------------------------
1822
1823#[cfg(feature = "chunking")]
1824mod window {
1825    use super::DocChunk;
1826    use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
1827
1828    /// A contiguous run of body text under a heading path.
1829    #[derive(Debug, Clone, Default)]
1830    pub struct Section {
1831        /// The heading stack in effect for this section, outermost first
1832        /// (e.g. `["Guide", "Setup"]`). Empty for pre-heading / body-only text.
1833        pub heading_path: Vec<String>,
1834        /// The plain words of the section body, markup stripped.
1835        pub words: Vec<String>,
1836    }
1837
1838    impl Section {
1839        /// The heading path rendered as a single context line, e.g.
1840        /// `# Guide > Setup`. Empty string when there is no heading.
1841        pub fn heading_context(&self) -> String {
1842            if self.heading_path.is_empty() {
1843                String::new()
1844            } else {
1845                format!("# {}", self.heading_path.join(" > "))
1846            }
1847        }
1848    }
1849
1850    fn level_index(level: HeadingLevel) -> usize {
1851        match level {
1852            HeadingLevel::H1 => 1,
1853            HeadingLevel::H2 => 2,
1854            HeadingLevel::H3 => 3,
1855            HeadingLevel::H4 => 4,
1856            HeadingLevel::H5 => 5,
1857            HeadingLevel::H6 => 6,
1858        }
1859    }
1860
1861    /// Parse Markdown into heading-bounded sections. A new section starts at
1862    /// every heading; the heading path is maintained as a stack keyed by
1863    /// heading level.
1864    pub fn parse_sections(markdown: &str) -> Vec<Section> {
1865        parse_sections_with_stack(markdown, Vec::new()).0
1866    }
1867
1868    /// [`parse_sections`] with an explicit initial heading stack, returning the
1869    /// final stack — lets a streaming caller carry heading context across
1870    /// pieces. `heading_stack[i]` holds the current heading text at level `i+1`
1871    /// (may be empty when a level was skipped).
1872    pub fn parse_sections_with_stack(
1873        markdown: &str,
1874        initial_stack: Vec<String>,
1875    ) -> (Vec<Section>, Vec<String>) {
1876        let mut heading_stack: Vec<String> = initial_stack;
1877        let mut sections: Vec<Section> = Vec::new();
1878        // Text before the first heading of this piece continues the carried-over
1879        // section, so it keeps the heading path in effect at the split point.
1880        let mut current = Section {
1881            heading_path: heading_stack
1882                .iter()
1883                .filter(|h| !h.is_empty())
1884                .cloned()
1885                .collect(),
1886            words: Vec::new(),
1887        };
1888
1889        let mut in_heading = false;
1890        let mut heading_level = 0usize;
1891        let mut heading_buf = String::new();
1892
1893        let push_words = |section: &mut Section, text: &str| {
1894            for w in text.split_whitespace() {
1895                section.words.push(w.to_string());
1896            }
1897        };
1898
1899        let flush = |sections: &mut Vec<Section>, section: &mut Section| {
1900            if !section.words.is_empty() {
1901                sections.push(std::mem::take(section));
1902            } else {
1903                *section = Section::default();
1904            }
1905        };
1906
1907        for event in Parser::new(markdown) {
1908            match event {
1909                Event::Start(Tag::Heading { level, .. }) => {
1910                    in_heading = true;
1911                    heading_level = level_index(level);
1912                    heading_buf.clear();
1913                }
1914                Event::End(TagEnd::Heading(_)) => {
1915                    in_heading = false;
1916                    // Update the heading stack: set this level, drop anything deeper.
1917                    let idx = heading_level.saturating_sub(1);
1918                    if heading_stack.len() <= idx {
1919                        heading_stack.resize(idx + 1, String::new());
1920                    } else {
1921                        heading_stack.truncate(idx + 1);
1922                    }
1923                    heading_stack[idx] = heading_buf.trim().to_string();
1924                    // A heading begins a new section.
1925                    flush(&mut sections, &mut current);
1926                    current.heading_path = heading_stack
1927                        .iter()
1928                        .filter(|h| !h.is_empty())
1929                        .cloned()
1930                        .collect();
1931                }
1932                Event::Text(t) | Event::Code(t) => {
1933                    if in_heading {
1934                        if !heading_buf.is_empty() {
1935                            heading_buf.push(' ');
1936                        }
1937                        heading_buf.push_str(&t);
1938                    } else {
1939                        push_words(&mut current, &t);
1940                    }
1941                }
1942                // Treat hard/soft breaks and rules as whitespace (words already split).
1943                Event::SoftBreak | Event::HardBreak | Event::Rule => {}
1944                _ => {}
1945            }
1946        }
1947        flush(&mut sections, &mut current);
1948        (sections, heading_stack)
1949    }
1950
1951    /// docling-rag's Markdown **window chunker**: the document is split into
1952    /// heading-bounded [`Section`]s of plain words (markup stripped), and a
1953    /// fixed-size window of [`Self::max_words`] words slides over each section
1954    /// with [`Self::overlap`] fractional overlap. A chunk never crosses a
1955    /// heading boundary; [`Self::contextualize`] prefixes the heading path.
1956    #[derive(Debug, Clone)]
1957    pub struct WindowChunker {
1958        /// Window size in words (docling-rag's default 300).
1959        pub max_words: usize,
1960        /// Fractional overlap between consecutive windows (default 0.05 = 5%).
1961        pub overlap: f32,
1962    }
1963
1964    impl Default for WindowChunker {
1965        fn default() -> Self {
1966            WindowChunker {
1967                max_words: 300,
1968                overlap: 0.05,
1969            }
1970        }
1971    }
1972
1973    impl WindowChunker {
1974        pub fn new(max_words: usize, overlap: f32) -> Self {
1975            WindowChunker { max_words, overlap }
1976        }
1977
1978        /// The window size, kept ≥ 1.
1979        fn word_budget(&self) -> usize {
1980            self.max_words.max(1)
1981        }
1982
1983        /// Number of words carried from one window into the next; capped so
1984        /// the window always advances.
1985        fn overlap_words(&self, budget: usize) -> usize {
1986            let o = (budget as f32 * self.overlap).round() as usize;
1987            o.min(budget.saturating_sub(1))
1988        }
1989
1990        /// Chunk a Markdown document.
1991        pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
1992            let mut chunks = Vec::new();
1993            self.chunk_with(markdown, &mut |c| {
1994                chunks.push(c);
1995                true
1996            });
1997            chunks
1998        }
1999
2000        /// Stream the chunks: `sink` receives each window as it is cut, and a
2001        /// `false` return cancels. [`Self::chunk`] is this with a collecting
2002        /// sink — the chunks and their order are identical.
2003        pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2004            let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2005            for section in &sections {
2006                if !self.pack_section(section, sink) {
2007                    return;
2008                }
2009            }
2010        }
2011
2012        /// Slide the window over one completed section, feeding each chunk to
2013        /// `sink`. Returns `false` once the sink cancels — exposed so a
2014        /// streaming caller (docling-rag) can pack sections as they complete.
2015        pub fn pack_section(
2016            &self,
2017            section: &Section,
2018            sink: &mut dyn FnMut(DocChunk) -> bool,
2019        ) -> bool {
2020            let words = &section.words;
2021            if words.is_empty() {
2022                return true;
2023            }
2024            let budget = self.word_budget();
2025            let step = budget - self.overlap_words(budget); // ≥ 1 by construction
2026            let mut start = 0;
2027            loop {
2028                let end = (start + budget).min(words.len());
2029                let chunk = DocChunk {
2030                    text: words[start..end].join(" "),
2031                    headings: (!section.heading_path.is_empty())
2032                        .then(|| section.heading_path.clone()),
2033                    doc_items: Vec::new(),
2034                };
2035                if !sink(chunk) {
2036                    return false;
2037                }
2038                if end >= words.len() {
2039                    return true;
2040                }
2041                start += step;
2042            }
2043        }
2044
2045        /// Render a window chunk for embedding — docling-rag's rendering: the
2046        /// heading path as a `# Outer > Inner` context line, a blank line,
2047        /// then the body (just the body above any heading). Note this differs
2048        /// from the docling chunkers' [`contextualize`](super::contextualize),
2049        /// matching docling-rag instead.
2050        pub fn contextualize(chunk: &DocChunk) -> String {
2051            match &chunk.headings {
2052                Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2053                _ => chunk.text.clone(),
2054            }
2055        }
2056    }
2057
2058    #[cfg(test)]
2059    mod tests {
2060        use super::*;
2061
2062        #[test]
2063        fn splits_on_headings_and_tracks_path() {
2064            let md = "\
2065intro words
2066# Chapter 1
2067para one
2068## Section 1.1
2069para two
2070# Chapter 2
2071para three";
2072            let secs = parse_sections(md);
2073            // pre-heading intro, Chapter 1, Section 1.1, Chapter 2.
2074            assert_eq!(secs.len(), 4);
2075            assert!(secs[0].heading_path.is_empty());
2076            assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2077            assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2078            // A deeper heading is dropped when we return to H1.
2079            assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2080        }
2081
2082        #[test]
2083        fn strips_markup_to_plain_words() {
2084            let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2085            let secs = parse_sections(md);
2086            let words = &secs[0].words;
2087            assert!(words.contains(&"bold".to_string()));
2088            assert!(words.contains(&"code".to_string()));
2089            assert!(words.contains(&"link".to_string()));
2090            // No markdown punctuation survives as its own token.
2091            assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2092        }
2093
2094        #[test]
2095        fn windows_overlap_and_never_cross_headings() {
2096            let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2097            let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2098            let chunker = WindowChunker::new(10, 0.2); // step 8, overlap 2
2099            let chunks = chunker.chunk(&md);
2100            // Section A: 25 words → windows [0..10), [8..18), [16..25).
2101            let a: Vec<_> = chunks
2102                .iter()
2103                .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2104                .collect();
2105            assert_eq!(a.len(), 3);
2106            assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2107            assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2108            assert!(a[2].text.ends_with(" w24"));
2109            // Section B stays its own chunk; nothing crosses the heading.
2110            let b: Vec<_> = chunks
2111                .iter()
2112                .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2113                .collect();
2114            assert_eq!(b.len(), 1);
2115            assert_eq!(b[0].text, "short tail");
2116            assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2117        }
2118
2119        #[test]
2120        fn sink_false_cancels_the_window_walk() {
2121            let md = format!(
2122                "# A\n\n{}\n",
2123                (0..50)
2124                    .map(|i| format!("w{i}"))
2125                    .collect::<Vec<_>>()
2126                    .join(" ")
2127            );
2128            let chunker = WindowChunker::new(10, 0.0);
2129            let mut n = 0;
2130            chunker.chunk_with(&md, &mut |_| {
2131                n += 1;
2132                false
2133            });
2134            assert_eq!(n, 1);
2135        }
2136    }
2137}
2138
2139#[cfg(feature = "chunking")]
2140pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2141
2142#[cfg(test)]
2143mod tests {
2144    use super::*;
2145
2146    /// A whitespace "tokenizer" for algorithm tests.
2147    struct WordTok(usize);
2148    impl ChunkTokenizer for WordTok {
2149        fn count_tokens(&self, text: &str) -> usize {
2150            text.split_whitespace().count()
2151        }
2152        fn max_tokens(&self) -> usize {
2153            self.0
2154        }
2155    }
2156
2157    fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2158        let mut d = DoclingDocument::new("t");
2159        for n in nodes {
2160            d.push(n);
2161        }
2162        d
2163    }
2164
2165    #[test]
2166    fn hierarchical_headings_and_items() {
2167        let doc = doc_with(vec![
2168            Node::Heading {
2169                level: 1,
2170                text: "Title".into(),
2171            },
2172            Node::Paragraph {
2173                text: "Intro".into(),
2174            },
2175            Node::Heading {
2176                level: 2,
2177                text: "Sec".into(),
2178            },
2179            Node::Paragraph {
2180                text: "Body".into(),
2181            },
2182        ]);
2183        let chunks = HierarchicalChunker.chunk(&doc);
2184        assert_eq!(chunks.len(), 2);
2185        assert_eq!(chunks[0].text, "Intro");
2186        assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2187        assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2188        assert_eq!(
2189            chunks[1].headings.as_deref(),
2190            Some(&["Title".into(), "Sec".into()][..])
2191        );
2192        assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
2193    }
2194
2195    #[test]
2196    fn heading_shadowing_prunes_deeper_levels() {
2197        let doc = doc_with(vec![
2198            Node::Heading {
2199                level: 2,
2200                text: "A".into(),
2201            },
2202            Node::Heading {
2203                level: 3,
2204                text: "A.1".into(),
2205            },
2206            Node::Heading {
2207                level: 2,
2208                text: "B".into(),
2209            },
2210            Node::Paragraph { text: "p".into() },
2211        ]);
2212        let chunks = HierarchicalChunker.chunk(&doc);
2213        assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
2214    }
2215
2216    #[test]
2217    fn triplet_table() {
2218        let t = Table {
2219            rows: vec![
2220                vec!["".into(), "Col1".into()],
2221                vec!["Row1".into(), "v".into()],
2222            ],
2223            ..Default::default()
2224        };
2225        assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
2226        // Single-column: row 0 is the dataframe header, the first data row
2227        // becomes the column name, the rest the values.
2228        let single = Table {
2229            rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
2230            ..Default::default()
2231        };
2232        assert_eq!(triplet_table_text(&single), "a = b");
2233    }
2234
2235    #[test]
2236    fn hybrid_merges_small_peers_and_splits_large() {
2237        let doc = doc_with(vec![
2238            Node::Heading {
2239                level: 2,
2240                text: "S".into(),
2241            },
2242            Node::Paragraph { text: "a b".into() },
2243            Node::Paragraph { text: "c d".into() },
2244        ]);
2245        let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2246        assert_eq!(chunks.len(), 1, "peers under one heading merge");
2247        assert_eq!(chunks[0].text, "a b\nc d");
2248
2249        let long = "w ".repeat(40).trim().to_string();
2250        let doc = doc_with(vec![Node::Paragraph { text: long }]);
2251        let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2252        assert!(chunks.len() > 1, "oversized paragraph splits");
2253        for c in &chunks {
2254            assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
2255        }
2256    }
2257
2258    #[test]
2259    fn semchunk_prefers_newlines_then_sentences() {
2260        let tok = WordTok(4);
2261        let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
2262        assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
2263    }
2264}