1use std::collections::{BTreeMap, VecDeque};
25
26use crate::document::{DoclingDocument, Node, Table};
27
28mod markdown_table;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum TableFormat {
35 #[default]
38 Triplet,
39 Markdown,
44}
45
46impl TableFormat {
47 pub fn from_markdown_flag(markdown: bool) -> Self {
49 if markdown {
50 Self::Markdown
51 } else {
52 Self::Triplet
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum ChunkItemKind {
61 Text,
63 Table,
66 Picture,
68}
69
70#[derive(Debug, Clone, PartialEq)]
73pub struct ChunkItem {
74 pub self_ref: String,
77 pub kind: ChunkItemKind,
78 pub text: String,
82}
83
84#[derive(Debug, Clone, PartialEq)]
86pub struct DocChunk {
87 pub text: String,
90 pub headings: Option<Vec<String>>,
93 pub doc_items: Vec<ChunkItem>,
95}
96
97pub fn contextualize(chunk: &DocChunk) -> String {
100 let mut parts: Vec<&str> = Vec::new();
101 if let Some(h) = &chunk.headings {
102 parts.extend(h.iter().map(String::as_str));
103 }
104 parts.push(&chunk.text);
105 parts.join("\n")
106}
107
108#[derive(Debug, Clone, Default)]
116pub struct HierarchicalChunker;
117
118impl HierarchicalChunker {
119 pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
121 let mut chunks = Vec::new();
122 self.chunk_with(doc, &mut |c| {
123 chunks.push(c);
124 true
125 });
126 chunks
127 }
128
129 pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
141 self.chunk_with_format(doc, TableFormat::Triplet, sink);
142 }
143
144 pub fn chunk_as(&self, doc: &DoclingDocument, tables: TableFormat) -> Vec<DocChunk> {
148 let mut chunks = Vec::new();
149 self.chunk_with_format(doc, tables, &mut |c| {
150 chunks.push(c);
151 true
152 });
153 chunks
154 }
155
156 pub fn chunk_with_format(
158 &self,
159 doc: &DoclingDocument,
160 tables: TableFormat,
161 sink: &mut dyn FnMut(DocChunk) -> bool,
162 ) {
163 let mut mapper = RefMapper::new(&doc.export_to_json_value());
164 Self::walk_nodes(doc, tables, &mut |c| sink(mapper.remap(c)));
165 }
166
167 fn walk_nodes(
170 doc: &DoclingDocument,
171 tables: TableFormat,
172 sink: &mut dyn FnMut(DocChunk) -> bool,
173 ) {
174 let strip = crate::fallback::any_marks();
176 let mut sink = |mut c: DocChunk| {
177 if strip {
178 c.text = crate::fallback::strip_owned(std::mem::take(&mut c.text));
179 for h in c.headings.iter_mut().flatten() {
180 *h = crate::fallback::strip_owned(std::mem::take(h));
181 }
182 for it in &mut c.doc_items {
183 it.text = crate::fallback::strip_owned(std::mem::take(&mut it.text));
184 }
185 }
186 sink(c)
187 };
188 let mut w = Walker {
189 tables,
190 alloc: Alloc::default(),
191 headings: BTreeMap::new(),
192 stopped: false,
193 sink: &mut sink,
194 };
195 w.walk(&doc.nodes);
196 }
197}
198
199struct RefMapper {
221 order: Vec<(String, ChunkItemKind, String)>,
223 marked: Vec<Option<String>>,
226 taken: Vec<bool>,
227 low: usize,
229 last: usize,
231 seen: std::collections::HashMap<(String, ChunkItemKind, String), Vec<usize>>,
232}
233
234impl RefMapper {
235 const WINDOW: usize = 64;
236 const NEAR: usize = 16;
237 const MIN_CONTAINED: usize = 4;
238
239 fn new(doc: &serde_json::Value) -> Self {
240 use serde_json::Value;
241 let mut index: std::collections::HashMap<&str, &Value> = std::collections::HashMap::new();
242 for key in [
243 "texts",
244 "tables",
245 "pictures",
246 "groups",
247 "field_regions",
248 "field_items",
249 "key_value_items",
250 "form_items",
251 ] {
252 for it in doc.get(key).and_then(Value::as_array).into_iter().flatten() {
253 if let Some(r) = it.get("self_ref").and_then(Value::as_str) {
254 index.insert(r, it);
255 }
256 }
257 }
258 let children = |v: &Value| -> Vec<String> {
259 v.get("children")
260 .and_then(Value::as_array)
261 .into_iter()
262 .flatten()
263 .filter_map(|c| c.get("$ref").or_else(|| c.get("cref")))
264 .filter_map(Value::as_str)
265 .map(str::to_string)
266 .collect()
267 };
268 let mut order = Vec::new();
269 let mut marked: Vec<Option<String>> = Vec::new();
270 let mut stack: Vec<std::vec::IntoIter<String>> = doc
271 .get("body")
272 .map(|b| vec![children(b).into_iter()])
273 .unwrap_or_default();
274 let mut visited = std::collections::HashSet::new();
277 while let Some(top) = stack.last_mut() {
278 let Some(r) = top.next() else {
279 stack.pop();
280 continue;
281 };
282 let Some(it) = index.get(r.as_str()).copied() else {
283 continue;
284 };
285 if !visited.insert(r.clone()) {
286 continue;
287 }
288 let text_of = |it: &Value| norm(it.get("text").and_then(Value::as_str).unwrap_or(""));
289 if r.starts_with("#/texts/") {
290 let marker = it.get("marker").and_then(Value::as_str).unwrap_or("");
291 while marked.len() < order.len() {
292 marked.push(None);
293 }
294 marked
295 .push((!marker.is_empty()).then(|| norm(&format!("{marker} {}", text_of(it)))));
296 order.push((r, ChunkItemKind::Text, text_of(it)));
297 } else if r.starts_with("#/tables/") || r.starts_with("#/pictures/") {
298 let refs = |key: &str| -> Vec<String> {
302 it.get(key)
303 .and_then(Value::as_array)
304 .into_iter()
305 .flatten()
306 .filter_map(|c| c.get("$ref").and_then(Value::as_str))
307 .map(str::to_string)
308 .collect()
309 };
310 let mut sat = |order: &mut Vec<(String, ChunkItemKind, String)>, key: &str| {
311 for c in refs(key) {
312 if let Some(t) = index.get(c.as_str()) {
313 if visited.insert(c.clone()) {
314 order.push((c, ChunkItemKind::Text, text_of(t)));
315 }
316 }
317 }
318 };
319 sat(&mut order, "captions");
320 let kind = if r.starts_with("#/tables/") {
321 ChunkItemKind::Table
322 } else {
323 ChunkItemKind::Picture
324 };
325 order.push((r, kind, String::new()));
326 sat(&mut order, "footnotes");
327 continue;
328 }
329 stack.push(children(it).into_iter());
330 }
331 let n = order.len();
332 marked.resize(n, None);
333 RefMapper {
334 order,
335 marked,
336 taken: vec![false; n],
337 low: 0,
338 last: 0,
339 seen: std::collections::HashMap::new(),
340 }
341 }
342
343 fn near(&self, lo: usize, hi: usize, used: &[usize], kind: ChunkItemKind) -> Vec<usize> {
346 let last = self.last.max(lo).min(hi);
347 (last..hi)
348 .chain((lo..last).rev())
349 .filter(|&i| !self.taken[i] && !used.contains(&i) && self.order[i].1 == kind)
350 .collect()
351 }
352
353 fn find(
354 &self,
355 (lo, hi): (usize, usize),
356 used: &[usize],
357 kind: ChunkItemKind,
358 text: &str,
359 ) -> Option<usize> {
360 if kind != ChunkItemKind::Text {
361 return self.near(lo, hi, used, kind).first().copied();
362 }
363 let plain = plain(text);
364 if let Some(i) = self
365 .near(lo, hi, used, kind)
366 .into_iter()
367 .find(|&i| self.matches(i, text, &plain))
368 {
369 return Some(i);
370 }
371 let near_lo = lo.max(self.last.saturating_sub(Self::NEAR));
375 let near_hi = hi.min(self.last + Self::NEAR);
376 if near_lo >= near_hi {
377 return None;
378 }
379 self.near(near_lo, near_hi, used, kind)
380 .into_iter()
381 .find(|&i| {
382 let t = &self.order[i].2;
383 t.chars().count() >= Self::MIN_CONTAINED && text.contains(t.as_str())
384 })
385 }
386
387 fn matches(&self, i: usize, text: &str, plain: &str) -> bool {
389 let t = &self.order[i].2;
390 t == text || t == plain || self.marked[i].as_deref().is_some_and(|m| m == plain)
391 }
392
393 fn find_far(&self, used: &[usize], kind: ChunkItemKind, text: &str) -> Option<usize> {
398 const FAR_CONTAINED: usize = 16;
399 const FAR: usize = 4096;
402 if kind != ChunkItemKind::Text || text.chars().count() < FAR_CONTAINED {
403 return None;
404 }
405 let plain = plain(text);
406 let free = |i: &usize| !self.taken[*i] && !used.contains(i) && self.order[*i].1 == kind;
407 let end = self.order.len().min(self.last + FAR);
408 let far = || (self.last..end).filter(free);
409 far().find(|&i| self.matches(i, text, &plain)).or_else(|| {
410 far().find(|&i| {
411 let t = &self.order[i].2;
412 t.chars().count() >= FAR_CONTAINED && text.contains(t.as_str())
413 })
414 })
415 }
416
417 fn part_of(&self, lo: usize, hi: usize, text: &str) -> Option<usize> {
422 let piece = plain(text);
423 if piece.chars().count() < 2 * Self::MIN_CONTAINED {
424 return None;
425 }
426 let contains = |i: usize| {
427 self.order[i].1 == ChunkItemKind::Text && self.order[i].2.contains(piece.as_str())
428 };
429 if let Some(prev) = self.last.checked_sub(1).filter(|&p| contains(p)) {
430 return Some(prev);
431 }
432 let near_lo = lo.max(self.last.saturating_sub(Self::NEAR));
433 let near_hi = hi.min(self.last + Self::NEAR);
434 (near_lo..near_hi).find(|&i| !self.taken[i] && contains(i))
435 }
436
437 fn runs_after(&self, hit: usize, hi: usize, used: &[usize], text: &str) -> Vec<usize> {
440 let first = &self.order[hit].2;
441 let mut pos = text.find(first.as_str()).map_or(0, |p| p + first.len());
442 let mut extra = Vec::new();
443 let mut j = hit + 1;
444 while j < hi
445 && !self.taken[j]
446 && !used.contains(&j)
447 && self.order[j].1 == ChunkItemKind::Text
448 {
449 let t = &self.order[j].2;
450 let Some(at) = (!t.is_empty())
451 .then(|| text.get(pos..).and_then(|rest| rest.find(t.as_str())))
452 .flatten()
453 else {
454 break;
455 };
456 extra.push(j);
457 pos += at + t.len();
458 j += 1;
459 }
460 extra
461 }
462
463 fn remap(&mut self, mut chunk: DocChunk) -> DocChunk {
464 let n = chunk.doc_items.len();
465 let lo = self.low.max(self.last.saturating_sub(Self::WINDOW));
466 let hi = self.order.len().min(self.last + Self::WINDOW + n);
467 let mut used: Vec<usize> = Vec::new();
468 let mut items = Vec::with_capacity(n);
469 for item in std::mem::take(&mut chunk.doc_items) {
470 let text = norm(&item.text);
471 let key = (item.self_ref.clone(), item.kind, text.clone());
472 let mut runs = self
473 .seen
474 .get(&key)
475 .filter(|r| !r.iter().any(|h| used.contains(h)))
476 .cloned();
477 if runs.is_none() && lo < hi {
478 let hit = self
479 .find((lo, hi), &used, item.kind, &text)
480 .or_else(|| self.find_far(&used, item.kind, &text));
481 if let Some(hit) = hit {
482 let mut r = vec![hit];
483 if item.kind == ChunkItemKind::Text && !self.matches(hit, &text, &plain(&text))
484 {
485 r.extend(self.runs_after(hit, hi, &used, &text));
486 }
487 self.seen.insert(key, r.clone());
488 runs = Some(r);
489 } else if item.kind == ChunkItemKind::Text {
490 runs = self.part_of(lo, hi, &text).map(|h| vec![h]);
491 }
492 }
493 let Some(runs) = runs else {
494 crate::debug_log!(
495 "chunker: no JSON item for {} ({:?}) in [{lo}, {hi}), last {}",
496 item.self_ref,
497 text.chars().take(60).collect::<String>(),
498 self.last
499 );
500 continue;
501 };
502 for (k, &h) in runs.iter().enumerate() {
503 if items
504 .iter()
505 .any(|i: &ChunkItem| i.self_ref == self.order[h].0)
506 {
507 continue; }
509 used.push(h);
510 self.taken[h] = true;
511 self.last = self.last.max(h + 1);
512 items.push(ChunkItem {
515 self_ref: self.order[h].0.clone(),
516 kind: item.kind,
517 text: if k == 0 {
518 item.text.clone()
519 } else {
520 self.order[h].2.clone()
521 },
522 });
523 }
524 }
525 while self.low < self.taken.len() && self.taken[self.low] {
526 self.low += 1;
527 }
528 chunk.doc_items = items;
529 chunk
530 }
531}
532
533fn norm(text: &str) -> String {
536 crate::doclang_xml::decode_entities(text)
537 .replace('\\', "")
538 .split_whitespace()
539 .collect::<Vec<_>>()
540 .join(" ")
541}
542
543fn plain(md: &str) -> String {
547 use std::sync::OnceLock;
548 static LINK: OnceLock<regex::Regex> = OnceLock::new();
549 static PREFIX: OnceLock<regex::Regex> = OnceLock::new();
550 let link = LINK.get_or_init(|| regex::Regex::new(r"!?\[([^\]]*)\]\([^)]*\)").expect("static"));
551 let prefix = PREFIX.get_or_init(|| {
552 regex::Regex::new(r"^(#{1,6}(\s+|$)|[-*+](\s+\[[ xX]\])?(\s+|$)|\d+[.)](\s+|$))")
553 .expect("static")
554 });
555 let mut text = link.replace_all(md, "$1").into_owned();
556 for marker in ["**", "~~", "`", "*"] {
557 text = text.replace(marker, "");
558 }
559 let text = prefix.replace(&text, "");
560 let text = text.trim();
562 let text = text
563 .strip_prefix("$$")
564 .and_then(|t| t.strip_suffix("$$"))
565 .or_else(|| text.strip_prefix('$').and_then(|t| t.strip_suffix('$')))
566 .unwrap_or(text);
567 text.trim().to_string()
568}
569
570#[derive(Debug, Default)]
573struct Alloc {
574 texts: usize,
575 groups: usize,
576 tables: usize,
577 pictures: usize,
578 field_regions: usize,
579 field_items: usize,
580}
581
582impl Alloc {
583 fn text(&mut self) -> String {
584 let r = format!("#/texts/{}", self.texts);
585 self.texts += 1;
586 r
587 }
588 fn group(&mut self) -> String {
589 let r = format!("#/groups/{}", self.groups);
590 self.groups += 1;
591 r
592 }
593 fn table(&mut self) -> String {
594 let r = format!("#/tables/{}", self.tables);
595 self.tables += 1;
596 r
597 }
598 fn picture(&mut self) -> String {
599 let r = format!("#/pictures/{}", self.pictures);
600 self.pictures += 1;
601 r
602 }
603 fn field_region(&mut self) -> String {
604 let r = format!("#/field_regions/{}", self.field_regions);
605 self.field_regions += 1;
606 r
607 }
608 fn field_item(&mut self) -> String {
609 let r = format!("#/field_items/{}", self.field_items);
610 self.field_items += 1;
611 r
612 }
613}
614
615struct Walker<'s> {
616 tables: TableFormat,
618 alloc: Alloc,
619 headings: BTreeMap<u8, String>,
622 stopped: bool,
624 sink: &'s mut dyn FnMut(DocChunk) -> bool,
625}
626
627impl Walker<'_> {
628 fn emit(&mut self, text: String, doc_items: Vec<ChunkItem>) {
629 if self.stopped || text.is_empty() {
630 return;
631 }
632 let headings: Vec<String> = self.headings.values().cloned().collect();
633 self.stopped = !(self.sink)(DocChunk {
634 text,
635 headings: (!headings.is_empty()).then_some(headings),
636 doc_items,
637 });
638 }
639
640 fn emit_inline(&mut self, md_text: &str, self_ref: String) {
644 self.emit_inline_with_runs(md_text, self_ref, &[]);
645 }
646
647 fn emit_inline_with_runs(
648 &mut self,
649 md_text: &str,
650 self_ref: String,
651 runs: &[crate::InlineRun],
652 ) {
653 let body = unescape_text(md_text);
654 if body.is_empty() {
655 return;
656 }
657 let segments: Vec<String> = inline_segments_tagged(md_text, runs)
658 .into_iter()
659 .flat_map(|(text, is_plain)| {
660 if is_plain {
661 if let Some(split) = split_plain_by_runs(&text, runs) {
662 return split;
663 }
664 }
665 vec![text]
666 })
667 .collect();
668 let items: Vec<ChunkItem> = if segments.len() <= 1 {
669 vec![ChunkItem {
670 self_ref,
671 kind: ChunkItemKind::Text,
672 text: body.clone(),
673 }]
674 } else {
675 segments
676 .into_iter()
677 .map(|text| ChunkItem {
678 self_ref: self_ref.clone(),
679 kind: ChunkItemKind::Text,
680 text,
681 })
682 .collect()
683 };
684 self.emit(body, items);
685 }
686
687 fn set_heading(&mut self, doc_level: u8, text: String) {
688 self.headings.retain(|k, _| *k < doc_level);
689 self.headings.insert(doc_level, text);
690 }
691
692 fn walk(&mut self, nodes: &[Node]) {
693 let mut i = 0;
694 while i < nodes.len() {
695 if self.stopped {
696 return;
697 }
698 if matches!(nodes[i], Node::ListItem { .. }) {
699 let start = i;
700 i += 1;
701 loop {
702 match nodes.get(i) {
703 Some(Node::ListItem { .. }) => i += 1,
704 Some(Node::Paragraph { text })
707 if text.is_empty()
708 && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
709 {
710 i += 1
711 }
712 _ => break,
713 }
714 }
715 self.sibling_lists(&nodes[start..i]);
716 } else {
717 self.one(&nodes[i]);
718 i += 1;
719 }
720 }
721 }
722
723 fn sibling_lists(&mut self, run: &[Node]) {
727 let base = level_of(&run[0]);
728 let mut seg = 0;
729 for k in 0..run.len() {
730 let Node::ListItem {
731 first_in_list,
732 level,
733 ..
734 } = &run[k]
735 else {
736 continue;
737 };
738 if *level != base {
739 continue; }
741 if k > seg && *first_in_list {
743 self.list(&run[seg..k]);
744 seg = k;
745 }
746 }
747 self.list(&run[seg..]);
748 }
749
750 fn list(&mut self, items: &[Node]) {
754 self.alloc.group();
755 let mut chunk_items = Vec::new();
756 self.list_refs(items, &mut chunk_items);
757 let text = render_list(items);
758 self.emit(text, chunk_items);
759 }
760
761 fn list_refs(&mut self, items: &[Node], out: &mut Vec<ChunkItem>) {
765 let base = level_of(&items[0]);
766 let mut i = 0;
767 while i < items.len() {
768 let Node::ListItem {
769 ordered,
770 number,
771 text,
772 level,
773 layer,
774 ..
775 } = &items[i]
776 else {
777 i += 1;
778 continue;
779 };
780 if *level > base {
781 i += 1;
782 continue;
783 }
784 let item_ref = self.alloc.text();
785 let mut j = i + 1;
786 while j < items.len() && level_of(&items[j]) > base {
787 j += 1;
788 }
789 let has_nested = j > i + 1;
790 if layer.is_none() {
791 let marker = if *ordered {
792 format!("{number}.")
793 } else {
794 "-".to_string()
795 };
796 let has_pics = text.contains("<!-- image -->");
810 let text = strip_image_markers(text);
811 let text = text.as_str();
812 let segments = inline_segments(text);
813 if (has_nested || has_pics) && segments.len() > 1 && text.contains("](") {
814 out.push(ChunkItem {
815 self_ref: item_ref.clone(),
816 kind: ChunkItemKind::Text,
817 text: format!("{marker} "),
818 });
819 for seg in segments {
820 out.push(ChunkItem {
821 self_ref: item_ref.clone(),
822 kind: ChunkItemKind::Text,
823 text: seg,
824 });
825 }
826 } else {
827 out.push(ChunkItem {
828 self_ref: item_ref.clone(),
829 kind: ChunkItemKind::Text,
830 text: format!("{marker} {}", unescape_text(text)),
831 });
832 }
833 }
834 if j > i + 1 {
837 self.nested_sibling_lists(&items[i + 1..j], out);
838 }
839 i = j;
840 }
841 }
842
843 fn nested_sibling_lists(&mut self, run: &[Node], out: &mut Vec<ChunkItem>) {
844 let base = level_of(&run[0]);
845 let mut seg = 0;
846 for k in 0..run.len() {
847 let Node::ListItem {
848 first_in_list,
849 level,
850 ..
851 } = &run[k]
852 else {
853 continue;
854 };
855 if *level != base {
856 continue;
857 }
858 if k > seg && *first_in_list {
859 self.alloc.group();
860 self.list_refs(&run[seg..k], out);
861 seg = k;
862 }
863 }
864 self.alloc.group();
865 self.list_refs(&run[seg..], out);
866 }
867
868 fn one(&mut self, node: &Node) {
869 match node {
870 Node::Heading { level, text } => {
871 let doc_level = if *level == 1 {
872 0
873 } else {
874 level.saturating_sub(1)
875 };
876 self.alloc.text();
877 let runs = crate::inline_runs_from_markdown(text);
884 let heading = if runs.len() <= 1 {
885 runs.first()
886 .map(|r| r.text.clone())
887 .unwrap_or_else(|| text.clone())
888 } else {
889 text.clone()
890 };
891 self.set_heading(doc_level, unescape_text(&heading));
892 }
893 Node::Paragraph { text } | Node::ListText { text, .. } => {
894 let t = text.trim();
895 let self_ref = self.alloc.text();
896 if let Some(inner) = t
899 .strip_prefix("$$")
900 .and_then(|s| s.strip_suffix("$$"))
901 .filter(|s| !s.is_empty())
902 {
903 let body = format!("$${inner}$$");
904 self.emit(
905 body.clone(),
906 vec![ChunkItem {
907 self_ref,
908 kind: ChunkItemKind::Text,
909 text: body,
910 }],
911 );
912 return;
913 }
914 self.emit_inline(text, self_ref);
915 }
916 Node::Caption { text, .. } => {
919 let self_ref = self.alloc.text();
920 self.emit_inline(text, self_ref);
921 }
922 Node::LabeledText { .. } => self.one(&node.labeled_as_paragraph()),
923 Node::CheckboxItem { checked, text } => {
924 let self_ref = self.alloc.text();
925 let mark = if *checked { "- [x] " } else { "- [ ] " };
926 let body = format!("{mark}{}", unescape_text(text));
927 self.emit(
928 body.clone(),
929 vec![ChunkItem {
930 self_ref,
931 kind: ChunkItemKind::Text,
932 text: body,
933 }],
934 );
935 }
936 Node::Formula { latex, orig, .. } => {
939 let self_ref = self.alloc.text();
941 let body = if !latex.is_empty() {
945 format!("$${}$$", latex)
946 } else if !orig.is_empty() {
947 crate::markdown::FORMULA_NOT_DECODED.to_string()
948 } else {
949 return;
950 };
951 self.emit(
952 body.clone(),
953 vec![ChunkItem {
954 self_ref,
955 kind: ChunkItemKind::Text,
956 text: body,
957 }],
958 );
959 }
960 Node::Code { text, .. } => {
961 let self_ref = self.alloc.text();
962 let body = crate::markdown::code_fence("", &unescape_text(text));
963 self.emit(
964 body.clone(),
965 vec![ChunkItem {
966 self_ref,
967 kind: ChunkItemKind::Text,
968 text: body,
969 }],
970 );
971 }
972 Node::Table(t) => {
973 let mut items = Vec::new();
979 let mut parts = Vec::new();
980 if let Some(cap) = t.caption.as_deref().filter(|c| !c.is_empty()) {
981 let text = unescape_text(cap);
982 parts.push(text.clone());
983 items.push(ChunkItem {
984 self_ref: self.alloc.text(),
985 kind: ChunkItemKind::Text,
986 text,
987 });
988 }
989 let self_ref = self.alloc.table();
990 let body = match self.tables {
991 TableFormat::Triplet => triplet_table_text(t),
992 TableFormat::Markdown => markdown_table_text(t),
993 };
994 items.push(ChunkItem {
995 self_ref,
996 kind: ChunkItemKind::Table,
997 text: body.clone(),
998 });
999 parts.push(body);
1003 for note in t.footnotes.iter().filter(|n| !n.is_empty()) {
1004 let text = unescape_text(note);
1005 parts.push(text.clone());
1006 items.push(ChunkItem {
1007 self_ref: self.alloc.text(),
1008 kind: ChunkItemKind::Text,
1009 text,
1010 });
1011 }
1012 let body = parts
1013 .into_iter()
1014 .filter(|p| !p.is_empty())
1015 .collect::<Vec<_>>()
1016 .join("\n\n");
1017 self.emit(body, items);
1018 }
1019 Node::Picture {
1020 caption,
1021 description,
1022 ..
1023 } => {
1024 let cap = caption.as_deref().filter(|c| !c.is_empty());
1025 let cap_item = cap.map(|c| ChunkItem {
1026 self_ref: self.alloc.text(),
1027 kind: ChunkItemKind::Text,
1028 text: unescape_text(c),
1029 });
1030 let pic_ref = self.alloc.picture();
1031 let desc = description
1039 .as_ref()
1040 .map(|d| d.text.as_str())
1041 .filter(|t| !t.is_empty());
1042 match (cap_item, desc) {
1043 (Some(cap_item), None) => {
1044 let body = cap_item.text.clone();
1045 self.emit(body, vec![cap_item]);
1046 }
1047 (Some(cap_item), Some(desc)) => {
1048 let body = format!("{}\n\n{desc}", cap_item.text);
1049 let pic_item = ChunkItem {
1050 self_ref: pic_ref,
1051 kind: ChunkItemKind::Picture,
1052 text: desc.to_string(),
1053 };
1054 self.emit(body, vec![cap_item, pic_item]);
1055 }
1056 (None, Some(desc)) => {
1057 let pic_item = ChunkItem {
1058 self_ref: pic_ref,
1059 kind: ChunkItemKind::Picture,
1060 text: desc.to_string(),
1061 };
1062 self.emit(desc.to_string(), vec![pic_item]);
1063 }
1064 (None, None) => {}
1065 }
1066 }
1067 Node::Chart {
1068 kind,
1069 table,
1070 caption,
1071 ..
1072 } => {
1073 let cap = caption.as_deref().filter(|c| !c.is_empty());
1074 let cap_item = cap.map(|c| ChunkItem {
1075 self_ref: self.alloc.text(),
1076 kind: ChunkItemKind::Text,
1077 text: unescape_text(c),
1078 });
1079 let pic_ref = self.alloc.picture();
1080 let mut parts: Vec<String> = Vec::new();
1084 if let Some(ci) = &cap_item {
1085 parts.push(ci.text.clone());
1086 }
1087 parts.push(humanize_label(kind));
1088 let grid = crate::markdown::render_table(table, false);
1089 if !grid.is_empty() {
1090 parts.push(unescape_text(&grid));
1091 }
1092 let body = parts.join("\n\n");
1093 let pic_item = ChunkItem {
1098 self_ref: pic_ref,
1099 kind: ChunkItemKind::Picture,
1100 text: body.clone(),
1101 };
1102 let items = match cap_item {
1103 Some(mut ci) => {
1104 ci.text = String::new();
1105 vec![ci, pic_item]
1106 }
1107 None => vec![pic_item],
1108 };
1109 self.emit(body, items);
1110 }
1111 Node::Group { layer: Some(_), .. } => {}
1114 Node::Group { children, .. } => {
1115 self.alloc.group();
1118 self.walk(children);
1119 }
1120 Node::KeyValueGraph { .. } => {}
1122 Node::FieldRegion { items } => {
1123 self.alloc.field_region();
1126 for item in items {
1127 self.alloc.field_item();
1128 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1129 let self_ref = self.alloc.text();
1130 let body = unescape_text(part);
1131 self.emit(
1132 body.clone(),
1133 vec![ChunkItem {
1134 self_ref,
1135 kind: ChunkItemKind::Text,
1136 text: body,
1137 }],
1138 );
1139 }
1140 }
1141 }
1142 Node::InlineGroup { md_text, runs, .. } => {
1143 let self_ref = self.alloc.text();
1144 self.emit_inline_with_runs(md_text, self_ref, runs);
1145 }
1146 Node::TextDump(text) => {
1147 let self_ref = self.alloc.text();
1148 let body = unescape_text(text);
1149 self.emit(
1150 body.clone(),
1151 vec![ChunkItem {
1152 self_ref,
1153 kind: ChunkItemKind::Text,
1154 text: body,
1155 }],
1156 );
1157 }
1158 Node::Located { inner, .. }
1160 | Node::Prov { inner, .. }
1161 | Node::Track { inner, .. }
1162 | Node::ScriptText { inner, .. }
1163 | Node::Commented { inner, .. } => self.one(inner),
1164 Node::PageFurniture { .. } | Node::FurnitureText { .. } => {
1168 self.alloc.text();
1169 }
1170 Node::PictureChildren(children) => {
1176 for child in children {
1177 match child {
1178 Node::PageFurniture { .. } => self.one(child),
1181 Node::ListItem { .. } => {
1182 self.alloc.group();
1183 self.alloc.text();
1184 }
1185 _ => {
1186 self.alloc.text();
1187 }
1188 }
1189 }
1190 }
1191 Node::CommentSection { .. }
1194 | Node::Furniture { .. }
1195 | Node::PageBreak
1196 | Node::PageInfo { .. }
1197 | Node::ProvContinuation { .. }
1198 | Node::Anchor { .. }
1199 | Node::DoclangOnly(_) => {}
1200 Node::ListItem { .. } => self.sibling_lists(std::slice::from_ref(node)),
1203 }
1204 }
1205}
1206
1207fn level_of(node: &Node) -> u8 {
1208 match node {
1209 Node::ListItem { level, .. } => *level,
1210 _ => 0,
1211 }
1212}
1213
1214fn render_list(items: &[Node]) -> String {
1217 let mut lines: Vec<String> = Vec::new();
1218 for item in items {
1219 let Node::ListItem {
1220 ordered,
1221 number,
1222 text,
1223 level,
1224 layer,
1225 ..
1226 } = item
1227 else {
1228 continue;
1229 };
1230 if layer.is_some() {
1231 continue;
1232 }
1233 let indent = " ".repeat(*level as usize);
1234 let marker = if *ordered {
1235 format!("{number}.")
1236 } else {
1237 "-".to_string()
1238 };
1239 lines.push(format!(
1240 "{indent}{marker} {}",
1241 unescape_text(&strip_image_markers(text))
1242 ));
1243 }
1244 lines.join("\n")
1245}
1246
1247fn strip_image_markers(text: &str) -> String {
1252 if !text.contains("<!-- image -->") {
1253 return text.to_string();
1254 }
1255 let cleaned: Vec<&str> = text
1256 .split('\n')
1257 .map(str::trim_end)
1258 .filter(|l| *l != "<!-- image -->")
1259 .collect();
1260 cleaned.join("\n").trim_end().to_string()
1261}
1262
1263fn humanize_label(label: &str) -> String {
1266 let text = label.replace('_', " ");
1267 let mut chars = text.chars();
1268 match chars.next() {
1269 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1270 None => text,
1271 }
1272}
1273
1274fn triplet_table_text(t: &Table) -> String {
1281 let anchors = t.span_anchors();
1282 let rows: Vec<Vec<String>> = t
1283 .rows
1284 .iter()
1285 .enumerate()
1286 .map(|(ri, r)| {
1287 (0..r.len())
1288 .map(|ci| cell_chunk_text(t, &anchors, ri, ci, TableFormat::Triplet))
1289 .collect()
1290 })
1291 .collect();
1292 let num_rows = rows.len();
1293 let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
1294 if num_rows == 0 || num_cols == 0 {
1295 return String::new();
1296 }
1297 let cell = |r: usize, c: usize| -> &str {
1298 rows.get(r)
1299 .and_then(|row| row.get(c))
1300 .map(String::as_str)
1301 .unwrap_or("")
1302 };
1303
1304 let num_headers = t.column_header_row_count().min(num_rows);
1308
1309 let columns: Vec<String> = if num_headers > 0 {
1312 (0..num_cols)
1313 .map(|c| {
1314 let mut name = String::new();
1315 for r in 0..num_headers {
1316 if !name.is_empty() {
1317 name.push('.');
1318 }
1319 name.push_str(cell(r, c));
1320 }
1321 name
1322 })
1323 .collect()
1324 } else {
1325 (0..num_cols).map(|c| c.to_string()).collect()
1326 };
1327 let data_rows = num_headers..num_rows;
1328 let n_data = data_rows.len();
1329
1330 if n_data == 0 {
1332 return columns
1333 .iter()
1334 .map(|s| s.trim())
1335 .filter(|s| !s.is_empty())
1336 .collect::<Vec<_>>()
1337 .join(". ");
1338 }
1339
1340 let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
1341 let text = if num_cols == 1 {
1342 let col_name = data(0, 0).trim().to_string();
1345 if n_data == 1 {
1346 col_name
1347 } else {
1348 (1..n_data)
1349 .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
1350 .collect::<Vec<_>>()
1351 .join(". ")
1352 }
1353 } else {
1354 let mut parts = Vec::new();
1356 for r in 0..n_data {
1357 for (c, col_name) in columns.iter().enumerate().skip(1) {
1358 parts.push(format!(
1359 "{}, {} = {}",
1360 data(r, 0).trim(),
1361 col_name.trim(),
1362 data(r, c).trim()
1363 ));
1364 }
1365 }
1366 parts.join(". ")
1367 };
1368 if !text.is_empty() {
1369 return text;
1370 }
1371
1372 (0..n_data)
1375 .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
1376 .map(|(r, c)| data(r, c).trim())
1377 .filter(|s| !s.is_empty())
1378 .collect::<Vec<_>>()
1379 .join(". ")
1380}
1381
1382fn markdown_table_text(t: &Table) -> String {
1390 let anchors = t.span_anchors();
1391 let mut grid = t.clone();
1392 grid.cell_blocks = None;
1393 for (ri, row) in grid.rows.iter_mut().enumerate() {
1394 for (ci, cell) in row.iter_mut().enumerate() {
1395 *cell = crate::fallback::strip_owned(cell_chunk_text(
1398 t,
1399 &anchors,
1400 ri,
1401 ci,
1402 TableFormat::Markdown,
1403 ));
1404 }
1405 }
1406 crate::markdown::render_table(&grid, false)
1407}
1408
1409fn inline_segments(md: &str) -> Vec<String> {
1417 inline_segments_tagged(md, &[])
1418 .into_iter()
1419 .map(|(t, _)| t)
1420 .collect()
1421}
1422
1423fn inline_segments_tagged(md: &str, runs: &[crate::InlineRun]) -> Vec<(String, bool)> {
1435 let formula_runs: Vec<&str> = runs
1436 .iter()
1437 .filter(|r| r.formula)
1438 .map(|r| r.text.trim())
1439 .collect();
1440 let chars: Vec<char> = md.chars().collect();
1441 let n = chars.len();
1442 let find = |from: usize, pat: &str| -> Option<usize> {
1443 let hay: String = chars[from..].iter().collect();
1444 hay.find(pat).map(|p| from + hay[..p].chars().count())
1445 };
1446 let mut out: Vec<(String, bool)> = Vec::new();
1447 let mut plain = String::new();
1448 let mut after_span = false;
1449
1450 fn flush(
1451 out: &mut Vec<(String, bool)>,
1452 plain: &mut String,
1453 before_span: bool,
1454 after_span: bool,
1455 ) {
1456 let mut p = std::mem::take(plain);
1457 if after_span {
1458 if let Some(rest) = p.strip_prefix(' ') {
1459 p = rest.to_string();
1460 }
1461 }
1462 if before_span {
1463 if let Some(rest) = p.strip_suffix(' ') {
1464 p = rest.to_string();
1465 }
1466 }
1467 if !p.is_empty() {
1468 out.push((unescape_text(&p), true));
1469 }
1470 }
1471
1472 let mut i = 0;
1473 while i < n {
1474 let rest: String = chars[i..].iter().collect();
1475 if chars[i] == '[' && !rest.starts_with("[](") {
1479 let balanced = |c: usize| {
1483 let mut d = 0i32;
1484 for &ch in &chars[i + 1..c] {
1485 match ch {
1486 '[' => d += 1,
1487 ']' => d -= 1,
1488 _ => {}
1489 }
1490 }
1491 d == 0
1492 };
1493 if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
1494 let mut depth = 0usize;
1495 let mut url_end = None;
1496 for (k, &c) in chars.iter().enumerate().skip(close + 2) {
1497 match c {
1498 '(' => depth += 1,
1499 ')' => {
1500 if depth == 0 {
1501 url_end = Some(k);
1502 break;
1503 }
1504 depth -= 1;
1505 }
1506 _ => {}
1507 }
1508 }
1509 if let Some(endp) = url_end {
1510 let url: String = chars[close + 2..endp].iter().collect();
1513 if !crate::hyperlink::is_safe_hyperlink(&url) {
1514 plain.extend(&chars[i + 1..close]);
1515 i = endp + 1;
1516 continue;
1517 }
1518 flush(&mut out, &mut plain, true, after_span);
1519 out.push((
1520 unescape_text(&chars[i..=endp].iter().collect::<String>()),
1521 false,
1522 ));
1523 i = endp + 1;
1524 after_span = true;
1525 continue;
1526 }
1527 }
1528 }
1529 if chars[i] == '`' {
1533 if let Some((s, e, after)) = crate::markdown::code_span_bounds(&chars, i) {
1534 if e > s && !chars[s..e].iter().all(|c| c.is_whitespace()) {
1535 flush(&mut out, &mut plain, true, after_span);
1536 let inner: String = chars[s..e].iter().collect();
1537 out.push((
1538 crate::markdown::code_fence("", &unescape_text(&inner)),
1539 false,
1540 ));
1541 i = after;
1542 after_span = true;
1543 continue;
1544 }
1545 }
1546 }
1547 let mut matched = false;
1549 for marker in ["***", "**", "*", "~~"] {
1550 if rest.starts_with(marker) {
1551 let mlen = marker.chars().count();
1552 if let Some(end) = find(i + mlen, marker) {
1553 let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
1557 if end > i + mlen && !inner_blank {
1558 flush(&mut out, &mut plain, true, after_span);
1559 out.push((
1560 unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
1561 false,
1562 ));
1563 i = end + mlen;
1564 after_span = true;
1565 matched = true;
1566 }
1567 }
1568 break;
1569 }
1570 }
1571 if matched {
1572 continue;
1573 }
1574 if rest.starts_with("$$") {
1577 plain.push_str("$$");
1578 i += 2;
1579 continue;
1580 }
1581 if chars[i] == '$' {
1583 let end = if formula_runs.is_empty() {
1584 dollar_math_closer(&chars, i)
1585 } else {
1586 find(i + 1, "$").filter(|&end| {
1587 let latex: String = chars[i + 1..end].iter().collect();
1588 formula_runs.contains(&latex.trim())
1589 })
1590 };
1591 if let Some(end) = end {
1592 if end > i + 1 {
1593 flush(&mut out, &mut plain, true, after_span);
1594 let latex: String = chars[i + 1..end].iter().collect();
1595 out.push((format!("$${latex}$$"), false));
1596 i = end + 1;
1597 after_span = true;
1598 continue;
1599 }
1600 }
1601 }
1602 plain.push(chars[i]);
1603 i += 1;
1604 }
1605 flush(&mut out, &mut plain, false, after_span);
1606 if out.is_empty() {
1607 out.push((unescape_text(md), true));
1608 }
1609 out
1610}
1611
1612fn dollar_math_closer(chars: &[char], open: usize) -> Option<usize> {
1619 let first = *chars.get(open + 1)?;
1620 if first.is_whitespace() || first == '$' {
1621 return None;
1622 }
1623 let end = open + 1 + chars[open + 1..].iter().position(|&c| c == '$')?;
1624 let before_ok = !chars[end - 1].is_whitespace();
1625 let after_ok = !chars.get(end + 1).is_some_and(|c| c.is_ascii_digit());
1626 (before_ok && after_ok).then_some(end)
1627}
1628
1629fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1634 let target = segment.trim();
1635 if target.is_empty() {
1636 return None;
1637 }
1638 let plainish =
1639 |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1640 let fully_plain =
1641 |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1642 let unmarked: Vec<(&str, bool)> = runs
1643 .iter()
1644 .filter(|r| plainish(r))
1645 .map(|r| (r.text.as_str(), fully_plain(r)))
1646 .collect();
1647 for start in 0..unmarked.len() {
1648 let mut rest = target;
1649 let mut taken: Vec<(String, bool)> = Vec::new();
1650 for (t, fully) in &unmarked[start..] {
1651 let t = t.trim();
1652 if t.is_empty() {
1653 continue;
1654 }
1655 match rest.strip_prefix(t) {
1656 Some(r) => {
1657 taken.push((unescape_text(t), *fully));
1658 rest = r.trim_start();
1659 if rest.is_empty() {
1660 break;
1661 }
1662 }
1663 None => break,
1664 }
1665 }
1666 if rest.is_empty() && taken.len() >= 2 {
1667 let mut merged: Vec<(String, bool)> = Vec::new();
1672 for (t, fully) in taken {
1673 match merged.last_mut() {
1674 Some((last, true)) if fully => {
1675 last.push(' ');
1676 last.push_str(&t);
1677 }
1678 _ => merged.push((t, fully)),
1679 }
1680 }
1681 if merged.len() >= 2 {
1682 return Some(merged.into_iter().map(|(t, _)| t).collect());
1683 }
1684 return None;
1685 }
1686 }
1687 None
1688}
1689
1690fn cell_chunk_text(
1697 t: &Table,
1698 anchors: &[Vec<(usize, usize)>],
1699 r: usize,
1700 c: usize,
1701 tables: TableFormat,
1702) -> String {
1703 let (ar, ac) = anchors
1706 .get(r)
1707 .and_then(|row| row.get(c))
1708 .copied()
1709 .unwrap_or((r, c));
1710 if let Some(blocks) = t
1711 .cell_blocks
1712 .as_ref()
1713 .and_then(|b| b.get(ar))
1714 .and_then(|row| row.get(ac))
1715 .filter(|b| !b.is_empty())
1716 {
1717 let mut parts: Vec<String> = Vec::new();
1718 for node in blocks.iter() {
1719 let part = block_chunk_text(node, tables);
1720 if !part.is_empty() {
1721 parts.push(part);
1722 }
1723 }
1724 return parts.join("\n\n");
1725 }
1726 let flat = t
1727 .rows
1728 .get(r)
1729 .and_then(|row| row.get(c))
1730 .map(String::as_str)
1731 .unwrap_or("");
1732 unescape_text(flat)
1733 .replace("<!-- image -->", "")
1734 .trim()
1735 .to_string()
1736}
1737
1738fn block_chunk_text(node: &Node, tables: TableFormat) -> String {
1740 match node {
1741 Node::Paragraph { text } | Node::ListText { text, .. } => unescape_text(text),
1742 Node::LabeledText { .. } => block_chunk_text(&node.labeled_as_paragraph(), tables),
1743 Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1744 Node::Code { text, .. } => crate::markdown::code_fence("", &unescape_text(text)),
1745 Node::Table(inner) => match tables {
1746 TableFormat::Triplet => triplet_table_text(inner),
1747 TableFormat::Markdown => markdown_table_text(inner),
1748 },
1749 Node::Picture { caption, .. } => caption
1750 .as_deref()
1751 .filter(|c| !c.is_empty())
1752 .map(unescape_text)
1753 .unwrap_or_default(),
1754 Node::ListItem {
1755 ordered,
1756 number,
1757 text,
1758 ..
1759 } => {
1760 let marker = if *ordered {
1761 format!("{number}.")
1762 } else {
1763 "-".to_string()
1764 };
1765 format!("{marker} {}", unescape_text(text))
1766 }
1767 Node::CheckboxItem { checked, text } => {
1768 let mark = if *checked { "- [x] " } else { "- [ ] " };
1769 format!("{mark}{}", unescape_text(text))
1770 }
1771 Node::Heading { text, .. } => unescape_text(text),
1772 Node::Located { inner, .. }
1773 | Node::Prov { inner, .. }
1774 | Node::Track { inner, .. }
1775 | Node::ScriptText { inner, .. }
1776 | Node::Commented { inner, .. } => block_chunk_text(inner, tables),
1777 Node::Group { layer: Some(_), .. } => String::new(),
1778 Node::Group { children, .. } => children
1779 .iter()
1780 .map(|n| block_chunk_text(n, tables))
1781 .filter(|s| !s.is_empty())
1782 .collect::<Vec<_>>()
1783 .join("\n"),
1784 _ => String::new(),
1785 }
1786}
1787
1788fn unescape_text(s: &str) -> String {
1791 s.replace("<", "<")
1792 .replace(">", ">")
1793 .replace("&", "&")
1794 .replace("\\_", "_")
1795}
1796
1797pub trait ChunkTokenizer {
1803 fn count_tokens(&self, text: &str) -> usize;
1805 fn max_tokens(&self) -> usize;
1807}
1808
1809pub struct HybridChunker<T: ChunkTokenizer> {
1813 tokenizer: T,
1814 merge_peers: bool,
1815 tables: TableFormat,
1816}
1817
1818impl<T: ChunkTokenizer> HybridChunker<T> {
1819 pub fn new(tokenizer: T) -> Self {
1820 Self {
1821 tokenizer,
1822 merge_peers: true,
1823 tables: TableFormat::Triplet,
1824 }
1825 }
1826
1827 pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1829 self.merge_peers = merge_peers;
1830 self
1831 }
1832
1833 pub fn with_table_format(mut self, tables: TableFormat) -> Self {
1838 self.tables = tables;
1839 self
1840 }
1841
1842 pub fn max_tokens(&self) -> usize {
1843 self.tokenizer.max_tokens()
1844 }
1845
1846 pub fn tokenizer(&self) -> &T {
1850 &self.tokenizer
1851 }
1852
1853 pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1855 let mut chunks = Vec::new();
1856 self.chunk_with(doc, &mut |c| {
1857 chunks.push(c);
1858 true
1859 });
1860 chunks
1861 }
1862
1863 pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1870 let mut mapper = RefMapper::new(&doc.export_to_json_value());
1873 let sink = &mut |c: DocChunk| sink(mapper.remap(c));
1874 let mut merger = PeerMerger::default();
1875 let mut alive = true;
1876 HierarchicalChunker::walk_nodes(doc, self.tables, &mut |c| {
1877 for split in self.split_by_doc_items(c) {
1878 for chunk in self.split_using_plain_text(split) {
1879 if !alive {
1880 return false;
1881 }
1882 alive = if self.merge_peers {
1883 self.merge_push(&mut merger, chunk, sink)
1884 } else {
1885 sink(chunk)
1886 };
1887 }
1888 }
1889 alive
1890 });
1891 if alive {
1892 self.merge_flush(&mut merger, sink);
1893 }
1894 }
1895
1896 fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1897 self.tokenizer.count_tokens(&contextualize(chunk))
1898 }
1899
1900 fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1903 let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1904 let text = if chunk.doc_items.len() == 1 {
1905 chunk.text.clone()
1906 } else {
1907 doc_items
1908 .iter()
1909 .filter(|it| !it.text.is_empty())
1910 .map(|it| it.text.as_str())
1911 .collect::<Vec<_>>()
1912 .join("\n")
1913 };
1914 DocChunk {
1915 text,
1916 headings: chunk.headings.clone(),
1917 doc_items,
1918 }
1919 }
1920
1921 fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1922 if chunk.doc_items.is_empty() {
1923 return vec![chunk];
1924 }
1925 let max = self.max_tokens();
1926 let num_items = chunk.doc_items.len();
1927 let mut chunks = Vec::new();
1928 let mut window_start = 0usize;
1929 let mut window_end = 0usize; while window_end < num_items {
1931 let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1932 if self.count_chunk_tokens(&new_chunk) <= max {
1933 if window_end < num_items - 1 {
1934 window_end += 1;
1935 continue;
1936 } else {
1937 window_end = num_items; }
1939 } else if window_start == window_end {
1940 window_end += 1;
1943 window_start = window_end;
1944 } else {
1945 new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1948 window_start = window_end;
1949 }
1950 chunks.push(new_chunk);
1951 }
1952 chunks
1953 }
1954
1955 fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1956 let total = self.count_chunk_tokens(&chunk);
1957 let max = self.max_tokens();
1958 if total <= max {
1959 return vec![chunk];
1960 }
1961 let text_len = self.tokenizer.count_tokens(&chunk.text);
1962 let other_len = total - text_len;
1963 if other_len >= max {
1964 let stripped = DocChunk {
1966 headings: None,
1967 ..chunk
1968 };
1969 return self.split_using_plain_text(stripped);
1970 }
1971 let available = max - other_len;
1972
1973 let make = |segments: Vec<String>| -> Vec<DocChunk> {
1974 segments
1975 .into_iter()
1976 .map(|s| DocChunk {
1977 text: s,
1978 headings: chunk.headings.clone(),
1979 doc_items: chunk.doc_items.clone(),
1980 })
1981 .collect()
1982 };
1983 let one_table =
1984 chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table;
1985 if one_table && self.tables == TableFormat::Markdown {
1986 let mut budget = available;
1991 while budget > 0 {
1992 let pieces = make(markdown_table::segment(
1993 &chunk.text,
1994 budget,
1995 &self.tokenizer,
1996 ));
1997 let overflow = pieces
1998 .iter()
1999 .map(|p| self.count_chunk_tokens(p).saturating_sub(max))
2000 .max()
2001 .unwrap_or(0);
2002 if overflow == 0 {
2003 return pieces;
2004 }
2005 budget = budget.saturating_sub(overflow);
2006 }
2007 if chunk.headings.is_some() {
2009 return self.split_using_plain_text(DocChunk {
2010 headings: None,
2011 ..chunk
2012 });
2013 }
2014 return make(markdown_table::segment(&chunk.text, max, &self.tokenizer));
2015 }
2016 if one_table {
2017 let lines: Vec<String> = chunk
2027 .text
2028 .split('\n')
2029 .filter(|l| !l.trim().is_empty())
2030 .map(|l| l.to_string())
2031 .collect();
2032 let mut budget = available;
2033 loop {
2034 let pieces = make(line_chunk_text(&lines, &self.tokenizer, budget));
2035 let overflow = pieces
2036 .iter()
2037 .map(|p| self.count_chunk_tokens(p).saturating_sub(max))
2038 .max()
2039 .unwrap_or(0);
2040 if overflow == 0 || budget <= overflow {
2041 return pieces;
2042 }
2043 budget -= overflow;
2044 }
2045 }
2046 make(semchunk(&chunk.text, available, &self.tokenizer))
2047 }
2048
2049 fn merge_push(
2064 &self,
2065 m: &mut PeerMerger,
2066 chunk: DocChunk,
2067 sink: &mut dyn FnMut(DocChunk) -> bool,
2068 ) -> bool {
2069 self.merge_feed(m, VecDeque::from([(chunk, None)]), sink)
2070 }
2071
2072 fn merge_feed(
2075 &self,
2076 m: &mut PeerMerger,
2077 mut pending: VecDeque<(DocChunk, Option<usize>)>,
2078 sink: &mut dyn FnMut(DocChunk) -> bool,
2079 ) -> bool {
2080 while let Some((chunk, tokens)) = pending.pop_front() {
2081 let tokens = tokens.unwrap_or_else(|| self.tokenizer.count_tokens(&chunk.text));
2082 if let Err(chunk) = self.merge_extend(m, chunk, tokens) {
2083 let (alive, rest) = self.merge_close(m, sink);
2084 if !alive {
2085 return false;
2086 }
2087 pending.push_front((chunk, Some(tokens)));
2088 for item in rest.into_iter().rev() {
2089 pending.push_front(item);
2090 }
2091 }
2092 }
2093 true
2094 }
2095
2096 fn merge_extend(
2099 &self,
2100 m: &mut PeerMerger,
2101 chunk: DocChunk,
2102 tokens: usize,
2103 ) -> Result<(), DocChunk> {
2104 let max = self.max_tokens() as i64;
2105 if m.window.is_empty() {
2106 m.overhead = self.count_chunk_tokens(&chunk) as i64 - tokens as i64;
2109 m.running = tokens as i64;
2110 m.window.push((chunk, tokens));
2111 return Ok(());
2112 }
2113 if chunk.headings != m.window[0].0.headings {
2114 return Err(chunk);
2115 }
2116 let delim = *m.delim.get_or_insert_with(|| {
2117 let t = &self.tokenizer;
2119 t.count_tokens("a\nb") as i64 - t.count_tokens("a") as i64 - t.count_tokens("b") as i64
2120 });
2121 m.running += tokens as i64 + delim;
2122 if m.running + m.overhead > max {
2123 let exact = self.count_chunk_tokens(&merged_chunk(
2124 m.window.iter().map(|(c, _)| c).chain([&chunk]),
2125 )) as i64;
2126 if exact > max {
2127 return Err(chunk);
2128 }
2129 m.running = exact - m.overhead;
2131 }
2132 m.window.push((chunk, tokens));
2133 Ok(())
2134 }
2135
2136 fn merge_close(
2140 &self,
2141 m: &mut PeerMerger,
2142 sink: &mut dyn FnMut(DocChunk) -> bool,
2143 ) -> (bool, Vec<(DocChunk, Option<usize>)>) {
2144 if m.window.is_empty() {
2145 return (true, Vec::new());
2146 }
2147 let max = self.max_tokens();
2148 let mut fit = m.window.len() - 1;
2149 while fit > 0
2150 && self.count_chunk_tokens(&merged_chunk(m.window[..=fit].iter().map(|(c, _)| c))) > max
2151 {
2152 fit -= 1;
2153 }
2154 let rest = m
2155 .window
2156 .split_off(fit + 1)
2157 .into_iter()
2158 .map(|(c, t)| (c, Some(t)))
2159 .collect();
2160 let out = if m.window.len() == 1 {
2161 m.window.pop().expect("single-chunk window").0
2162 } else {
2163 let merged = merged_chunk(m.window.iter().map(|(c, _)| c));
2164 m.window.clear();
2165 merged
2166 };
2167 (sink(out), rest)
2168 }
2169
2170 fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
2173 while !m.window.is_empty() {
2174 let (alive, rest) = self.merge_close(m, sink);
2175 if !alive || !self.merge_feed(m, rest.into(), sink) {
2176 return false;
2177 }
2178 }
2179 true
2180 }
2181}
2182
2183fn merged_chunk<'a>(chunks: impl Iterator<Item = &'a DocChunk> + Clone) -> DocChunk {
2186 let mut first = chunks.clone();
2187 DocChunk {
2188 text: chunks
2189 .clone()
2190 .map(|c| c.text.as_str())
2191 .collect::<Vec<_>>()
2192 .join("\n"),
2193 headings: first.next().and_then(|c| c.headings.clone()),
2194 doc_items: chunks.flat_map(|c| c.doc_items.iter().cloned()).collect(),
2195 }
2196}
2197
2198#[derive(Default)]
2203struct PeerMerger {
2204 window: Vec<(DocChunk, usize)>,
2205 running: i64,
2206 overhead: i64,
2207 delim: Option<i64>,
2208}
2209
2210fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
2220 let mut chunks: Vec<String> = Vec::new();
2221 let mut current = String::new();
2222 let mut current_len = 0usize;
2223
2224 for line in lines {
2225 let mut remaining: Vec<char> = line.chars().collect();
2226 loop {
2227 let rem_str: String = remaining.iter().collect();
2228 let line_tokens = tok.count_tokens(&rem_str);
2229 let available = max_tokens.saturating_sub(current_len);
2230
2231 if line_tokens <= available {
2232 current.push_str(&rem_str);
2233 current_len += line_tokens;
2234 break;
2235 }
2236 if line_tokens <= max_tokens {
2237 chunks.push(std::mem::take(&mut current));
2238 current_len = 0;
2239 continue;
2240 }
2241 let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
2243 let mut rest = rest;
2244 if take.is_empty() {
2245 if rest.is_empty() {
2246 break;
2247 }
2248 take = rest[..1].iter().collect();
2249 rest = rest[1..].to_vec();
2250 }
2251 current.push('\n');
2252 current.push_str(&take);
2253 chunks.push(std::mem::take(&mut current));
2254 current_len = 0;
2255 remaining = rest;
2256 }
2257 }
2258 if !current.is_empty() {
2259 chunks.push(current);
2260 }
2261 chunks
2262}
2263
2264fn split_by_token_limit<T: ChunkTokenizer>(
2268 text: &[char],
2269 token_limit: usize,
2270 tok: &T,
2271) -> (String, Vec<char>) {
2272 if token_limit == 0 || text.is_empty() {
2273 return (String::new(), text.to_vec());
2274 }
2275 let full: String = text.iter().collect();
2276 if tok.count_tokens(&full) <= token_limit {
2277 return (full, Vec::new());
2278 }
2279 let (mut lo, mut hi) = (0usize, text.len());
2280 let mut best: Option<usize> = None;
2281 while lo <= hi {
2282 let mid = (lo + hi) / 2;
2283 let head: String = text[..mid].iter().collect();
2284 if tok.count_tokens(&head) <= token_limit {
2285 best = Some(mid);
2286 lo = mid + 1;
2287 } else {
2288 if mid == 0 {
2289 break;
2290 }
2291 hi = mid - 1;
2292 }
2293 }
2294 let mut best_idx = match best {
2295 Some(b) if b > 0 => b,
2296 _ => return (String::new(), text.to_vec()),
2297 };
2298 if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
2300 if pos > 0 {
2301 best_idx = pos;
2302 }
2303 }
2304 (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
2305}
2306
2307const NON_WS_SPLITTERS: &[&str] = &[
2313 ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
2314 "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
2315];
2316
2317pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
2321 let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
2322 let mut counter = |s: &str| -> usize {
2323 if let Some(n) = cache.get(s) {
2324 return *n;
2325 }
2326 let n = tok.count_tokens(s);
2327 cache.insert(s.to_string(), n);
2328 n
2329 };
2330 let chunks = semchunk_rec(text, chunk_size, &mut counter);
2331 chunks
2333 .into_iter()
2334 .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
2335 .collect()
2336}
2337
2338fn semchunk_rec(
2341 text: &str,
2342 chunk_size: usize,
2343 counter: &mut dyn FnMut(&str) -> usize,
2344) -> Vec<String> {
2345 let (splitter, splitter_is_ws, splits) = split_text(text);
2346
2347 let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
2348 let mut cum_lens = Vec::with_capacity(splits.len() + 1);
2349 cum_lens.push(0usize);
2350 for l in &split_lens {
2351 cum_lens.push(cum_lens.last().unwrap() + l);
2352 }
2353 let num_splits_plus_one = splits.len() + 1;
2354
2355 let mut chunks: Vec<String> = Vec::new();
2356 let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
2357
2358 for i in 0..splits.len() {
2359 if skips.contains(&i) {
2360 continue;
2361 }
2362 let split = &splits[i];
2363 if counter(split) > chunk_size {
2364 let inner = semchunk_rec(split, chunk_size, counter);
2365 chunks.extend(inner);
2366 } else {
2367 let (end, merged) = merge_splits(
2368 &splits,
2369 &cum_lens,
2370 chunk_size,
2371 &splitter,
2372 counter,
2373 i,
2374 num_splits_plus_one,
2375 );
2376 for j in (i + 1)..end {
2377 skips.insert(j);
2378 }
2379 chunks.push(merged);
2380 }
2381 let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
2384 if !splitter_is_ws && !is_last {
2385 let with_splitter = format!(
2386 "{}{}",
2387 chunks.last().map(String::as_str).unwrap_or(""),
2388 splitter
2389 );
2390 if counter(&with_splitter) <= chunk_size {
2391 if let Some(last) = chunks.last_mut() {
2392 *last = with_splitter;
2393 } else {
2394 chunks.push(with_splitter);
2395 }
2396 } else {
2397 chunks.push(splitter.clone());
2398 }
2399 }
2400 }
2401 chunks
2402}
2403
2404fn merge_splits(
2407 splits: &[String],
2408 cum_lens: &[usize],
2409 chunk_size: usize,
2410 splitter: &str,
2411 counter: &mut dyn FnMut(&str) -> usize,
2412 start: usize,
2413 high_init: usize,
2414) -> (usize, String) {
2415 let mut average = 0.2f64;
2416 let mut low = start;
2417 let mut high = high_init;
2418 let offset = cum_lens[start];
2419 let mut target = offset as f64 + (chunk_size as f64 * average);
2420
2421 while low < high {
2422 let i = bisect_left(cum_lens, target, low, high);
2423 let midpoint = i.min(high - 1);
2424 let joined = splits[start..midpoint.max(start)].join(splitter);
2425 let tokens = counter(&joined);
2426 let local_cum = cum_lens[midpoint] - offset;
2427 if local_cum > 0 && tokens > 0 {
2428 average = local_cum as f64 / tokens as f64;
2429 target = offset as f64 + (chunk_size as f64 * average);
2430 }
2431 if tokens > chunk_size {
2432 high = midpoint;
2433 } else {
2434 low = midpoint + 1;
2435 }
2436 }
2437 let end = low - 1;
2438 (end, splits[start..end.max(start)].join(splitter))
2439}
2440
2441fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
2442 while low < high {
2443 let mid = (low + high) / 2;
2444 if (sorted[mid] as f64) < target {
2445 low = mid + 1;
2446 } else {
2447 high = mid;
2448 }
2449 }
2450 low
2451}
2452
2453fn split_text(text: &str) -> (String, bool, Vec<String>) {
2455 if text.contains('\n') || text.contains('\r') {
2457 let splitter = longest_run(text, |c| c == '\n' || c == '\r');
2458 return (splitter.clone(), true, split_on(text, &splitter));
2459 }
2460 if text.contains('\t') {
2462 let splitter = longest_run(text, |c| c == '\t');
2463 return (splitter.clone(), true, split_on(text, &splitter));
2464 }
2465 if text.chars().any(char::is_whitespace) {
2467 let splitter = longest_run(text, char::is_whitespace);
2468 if splitter.chars().count() == 1 {
2469 for preceder in NON_WS_SPLITTERS {
2471 if let Some((ws, parts)) = split_after_preceder(text, preceder) {
2472 return (ws, true, parts);
2473 }
2474 }
2475 }
2476 return (splitter.clone(), true, split_on(text, &splitter));
2477 }
2478 for s in NON_WS_SPLITTERS {
2480 if text.contains(s) {
2481 return (s.to_string(), false, split_on(text, s));
2482 }
2483 }
2484 (
2486 String::new(),
2487 true,
2488 text.chars().map(|c| c.to_string()).collect(),
2489 )
2490}
2491
2492fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
2494 let mut best = String::new();
2495 let mut cur = String::new();
2496 for c in text.chars() {
2497 if pred(c) {
2498 cur.push(c);
2499 } else {
2500 if cur.chars().count() > best.chars().count() {
2501 best = cur.clone();
2502 }
2503 cur.clear();
2504 }
2505 }
2506 if cur.chars().count() > best.chars().count() {
2507 best = cur;
2508 }
2509 best
2510}
2511
2512fn split_on(text: &str, splitter: &str) -> Vec<String> {
2513 text.split(splitter).map(str::to_string).collect()
2514}
2515
2516fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
2520 let chars: Vec<char> = text.chars().collect();
2521 let p: Vec<char> = preceder.chars().collect();
2522 let mut ws: Option<char> = None;
2523 for i in p.len()..chars.len() {
2524 if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
2525 ws = Some(chars[i]);
2526 break;
2527 }
2528 }
2529 let ws = ws?;
2530 let mut parts = Vec::new();
2531 let mut cur = String::new();
2532 let mut i = 0usize;
2533 while i < chars.len() {
2534 if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
2535 parts.push(std::mem::take(&mut cur));
2536 i += 1;
2537 continue;
2538 }
2539 cur.push(chars[i]);
2540 i += 1;
2541 }
2542 parts.push(cur);
2543 Some((ws.to_string(), parts))
2544}
2545
2546#[cfg(feature = "chunking")]
2551mod hf {
2552 use super::ChunkTokenizer;
2553
2554 pub const DEFAULT_TOKENIZER_PATH: &str = ".models/chunk/tokenizer.json";
2559
2560 pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
2565 if let Some(p) = explicit {
2566 return Ok(p.to_string());
2567 }
2568 let resolved = crate::assets::resolve(DEFAULT_TOKENIZER_PATH);
2569 if std::path::Path::new(&resolved).exists() {
2570 return Ok(resolved);
2571 }
2572 Err(format!(
2573 "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
2574 {DEFAULT_TOKENIZER_PATH} does not exist — run \
2575 scripts/install/download_dependencies.sh (or pass an explicit path)"
2576 ))
2577 }
2578
2579 pub struct HuggingFaceTokenizer {
2583 tok: tokenizers::Tokenizer,
2584 max_tokens: usize,
2585 }
2586
2587 impl HuggingFaceTokenizer {
2588 pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
2592 Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
2593 }
2594
2595 pub fn from_file(
2599 path: impl AsRef<std::path::Path>,
2600 max_tokens: usize,
2601 ) -> Result<Self, String> {
2602 let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
2603 .map_err(|e| format!("failed to load tokenizer: {e}"))?;
2604 let _ = tok.with_truncation(None);
2609 tok.with_padding(None);
2610 Ok(Self { tok, max_tokens })
2611 }
2612 }
2613
2614 impl ChunkTokenizer for HuggingFaceTokenizer {
2615 fn count_tokens(&self, text: &str) -> usize {
2616 self.tok
2617 .encode(text, false)
2618 .map(|e| e.get_tokens().len())
2619 .unwrap_or(0)
2620 }
2621 fn max_tokens(&self) -> usize {
2622 self.max_tokens
2623 }
2624 }
2625}
2626
2627#[cfg(feature = "chunking")]
2628pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
2629
2630#[cfg(feature = "chunking")]
2635mod window {
2636 use super::DocChunk;
2637 use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
2638
2639 #[derive(Debug, Clone, Default)]
2641 pub struct Section {
2642 pub heading_path: Vec<String>,
2645 pub words: Vec<String>,
2647 }
2648
2649 impl Section {
2650 pub fn heading_context(&self) -> String {
2653 if self.heading_path.is_empty() {
2654 String::new()
2655 } else {
2656 format!("# {}", self.heading_path.join(" > "))
2657 }
2658 }
2659 }
2660
2661 fn level_index(level: HeadingLevel) -> usize {
2662 match level {
2663 HeadingLevel::H1 => 1,
2664 HeadingLevel::H2 => 2,
2665 HeadingLevel::H3 => 3,
2666 HeadingLevel::H4 => 4,
2667 HeadingLevel::H5 => 5,
2668 HeadingLevel::H6 => 6,
2669 }
2670 }
2671
2672 pub fn parse_sections(markdown: &str) -> Vec<Section> {
2676 parse_sections_with_stack(markdown, Vec::new()).0
2677 }
2678
2679 pub fn parse_sections_with_stack(
2684 markdown: &str,
2685 initial_stack: Vec<String>,
2686 ) -> (Vec<Section>, Vec<String>) {
2687 let mut heading_stack: Vec<String> = initial_stack;
2688 let mut sections: Vec<Section> = Vec::new();
2689 let mut current = Section {
2692 heading_path: heading_stack
2693 .iter()
2694 .filter(|h| !h.is_empty())
2695 .cloned()
2696 .collect(),
2697 words: Vec::new(),
2698 };
2699
2700 let mut in_heading = false;
2701 let mut heading_level = 0usize;
2702 let mut heading_buf = String::new();
2703
2704 let push_words = |section: &mut Section, text: &str| {
2705 for w in text.split_whitespace() {
2706 section.words.push(w.to_string());
2707 }
2708 };
2709
2710 let flush = |sections: &mut Vec<Section>, section: &mut Section| {
2711 if !section.words.is_empty() {
2712 sections.push(std::mem::take(section));
2713 } else {
2714 *section = Section::default();
2715 }
2716 };
2717
2718 for event in Parser::new(markdown) {
2719 match event {
2720 Event::Start(Tag::Heading { level, .. }) => {
2721 in_heading = true;
2722 heading_level = level_index(level);
2723 heading_buf.clear();
2724 }
2725 Event::End(TagEnd::Heading(_)) => {
2726 in_heading = false;
2727 let idx = heading_level.saturating_sub(1);
2729 if heading_stack.len() <= idx {
2730 heading_stack.resize(idx + 1, String::new());
2731 } else {
2732 heading_stack.truncate(idx + 1);
2733 }
2734 heading_stack[idx] = heading_buf.trim().to_string();
2735 flush(&mut sections, &mut current);
2737 current.heading_path = heading_stack
2738 .iter()
2739 .filter(|h| !h.is_empty())
2740 .cloned()
2741 .collect();
2742 }
2743 Event::Text(t) | Event::Code(t) => {
2744 if in_heading {
2745 if !heading_buf.is_empty() {
2746 heading_buf.push(' ');
2747 }
2748 heading_buf.push_str(&t);
2749 } else {
2750 push_words(&mut current, &t);
2751 }
2752 }
2753 Event::SoftBreak | Event::HardBreak | Event::Rule => {}
2755 _ => {}
2756 }
2757 }
2758 flush(&mut sections, &mut current);
2759 (sections, heading_stack)
2760 }
2761
2762 #[derive(Debug, Clone)]
2768 pub struct WindowChunker {
2769 pub max_words: usize,
2771 pub overlap: f32,
2773 }
2774
2775 impl Default for WindowChunker {
2776 fn default() -> Self {
2777 WindowChunker {
2778 max_words: 300,
2779 overlap: 0.05,
2780 }
2781 }
2782 }
2783
2784 impl WindowChunker {
2785 pub fn new(max_words: usize, overlap: f32) -> Self {
2786 WindowChunker { max_words, overlap }
2787 }
2788
2789 fn word_budget(&self) -> usize {
2791 self.max_words.max(1)
2792 }
2793
2794 fn overlap_words(&self, budget: usize) -> usize {
2797 let o = (budget as f32 * self.overlap).round() as usize;
2798 o.min(budget.saturating_sub(1))
2799 }
2800
2801 pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
2803 let mut chunks = Vec::new();
2804 self.chunk_with(markdown, &mut |c| {
2805 chunks.push(c);
2806 true
2807 });
2808 chunks
2809 }
2810
2811 pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2815 let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2816 for section in §ions {
2817 if !self.pack_section(section, sink) {
2818 return;
2819 }
2820 }
2821 }
2822
2823 pub fn pack_section(
2827 &self,
2828 section: &Section,
2829 sink: &mut dyn FnMut(DocChunk) -> bool,
2830 ) -> bool {
2831 let words = §ion.words;
2832 if words.is_empty() {
2833 return true;
2834 }
2835 let budget = self.word_budget();
2836 let step = budget - self.overlap_words(budget); let mut start = 0;
2838 loop {
2839 let end = (start + budget).min(words.len());
2840 let chunk = DocChunk {
2841 text: words[start..end].join(" "),
2842 headings: (!section.heading_path.is_empty())
2843 .then(|| section.heading_path.clone()),
2844 doc_items: Vec::new(),
2845 };
2846 if !sink(chunk) {
2847 return false;
2848 }
2849 if end >= words.len() {
2850 return true;
2851 }
2852 start += step;
2853 }
2854 }
2855
2856 pub fn contextualize(chunk: &DocChunk) -> String {
2862 match &chunk.headings {
2863 Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2864 _ => chunk.text.clone(),
2865 }
2866 }
2867 }
2868
2869 #[cfg(test)]
2870 mod tests {
2871 use super::*;
2872
2873 #[test]
2874 fn splits_on_headings_and_tracks_path() {
2875 let md = "\
2876intro words
2877# Chapter 1
2878para one
2879## Section 1.1
2880para two
2881# Chapter 2
2882para three";
2883 let secs = parse_sections(md);
2884 assert_eq!(secs.len(), 4);
2886 assert!(secs[0].heading_path.is_empty());
2887 assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2888 assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2889 assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2891 }
2892
2893 #[test]
2894 fn strips_markup_to_plain_words() {
2895 let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2896 let secs = parse_sections(md);
2897 let words = &secs[0].words;
2898 assert!(words.contains(&"bold".to_string()));
2899 assert!(words.contains(&"code".to_string()));
2900 assert!(words.contains(&"link".to_string()));
2901 assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2903 }
2904
2905 #[test]
2906 fn windows_overlap_and_never_cross_headings() {
2907 let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2908 let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2909 let chunker = WindowChunker::new(10, 0.2); let chunks = chunker.chunk(&md);
2911 let a: Vec<_> = chunks
2913 .iter()
2914 .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2915 .collect();
2916 assert_eq!(a.len(), 3);
2917 assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2918 assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2919 assert!(a[2].text.ends_with(" w24"));
2920 let b: Vec<_> = chunks
2922 .iter()
2923 .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2924 .collect();
2925 assert_eq!(b.len(), 1);
2926 assert_eq!(b[0].text, "short tail");
2927 assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2928 }
2929
2930 #[test]
2931 fn sink_false_cancels_the_window_walk() {
2932 let md = format!(
2933 "# A\n\n{}\n",
2934 (0..50)
2935 .map(|i| format!("w{i}"))
2936 .collect::<Vec<_>>()
2937 .join(" ")
2938 );
2939 let chunker = WindowChunker::new(10, 0.0);
2940 let mut n = 0;
2941 chunker.chunk_with(&md, &mut |_| {
2942 n += 1;
2943 false
2944 });
2945 assert_eq!(n, 1);
2946 }
2947 }
2948}
2949
2950#[cfg(feature = "chunking")]
2951pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2952
2953#[cfg(test)]
2954mod tests {
2955 use super::*;
2956
2957 struct WordTok(usize);
2959 impl ChunkTokenizer for WordTok {
2960 fn count_tokens(&self, text: &str) -> usize {
2961 text.split_whitespace().count()
2962 }
2963 fn max_tokens(&self) -> usize {
2964 self.0
2965 }
2966 }
2967
2968 fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2969 let mut d = DoclingDocument::new("t");
2970 for n in nodes {
2971 d.push(n);
2972 }
2973 d
2974 }
2975
2976 #[test]
2977 fn hierarchical_headings_and_items() {
2978 let doc = doc_with(vec![
2979 Node::Heading {
2980 level: 1,
2981 text: "Title".into(),
2982 },
2983 Node::Paragraph {
2984 text: "Intro".into(),
2985 },
2986 Node::Heading {
2987 level: 2,
2988 text: "Sec".into(),
2989 },
2990 Node::Paragraph {
2991 text: "Body".into(),
2992 },
2993 ]);
2994 let chunks = HierarchicalChunker.chunk(&doc);
2995 assert_eq!(chunks.len(), 2);
2996 assert_eq!(chunks[0].text, "Intro");
2997 assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2998 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2999 assert_eq!(
3000 chunks[1].headings.as_deref(),
3001 Some(&["Title".into(), "Sec".into()][..])
3002 );
3003 assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
3004 }
3005
3006 #[test]
3009 fn page_furniture_keeps_refs_aligned_with_json() {
3010 let doc = doc_with(vec![
3011 Node::Paragraph {
3012 text: "Before".into(),
3013 },
3014 Node::PageFurniture {
3015 footer: true,
3016 location: [0, 490, 100, 512],
3017 text: "1.10.2".into(),
3018 },
3019 Node::Paragraph {
3020 text: "After".into(),
3021 },
3022 ]);
3023 let chunks = HierarchicalChunker.chunk(&doc);
3024 assert_eq!(chunks.len(), 2);
3025 assert_eq!(chunks[1].text, "After");
3026 let json: serde_json::Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3027 assert_eq!(json["texts"][2]["text"], "After");
3028 assert_eq!(chunks[1].doc_items[0].self_ref, "#/texts/2");
3029 }
3030
3031 #[test]
3035 fn captioned_table_keeps_the_text_refs_aligned() {
3036 let table = Table {
3037 rows: vec![
3038 vec!["Year".into(), "Revenue".into()],
3039 vec!["2024".into(), "10".into()],
3040 ],
3041 caption: Some("Table 1: Revenue".into()),
3042 ..Table::default()
3043 };
3044 let doc = doc_with(vec![
3045 Node::Table(table.clone()),
3046 Node::Paragraph {
3047 text: "Revenue grew in 2024.".into(),
3048 },
3049 Node::Table(table),
3050 Node::Paragraph {
3051 text: "Costs were flat.".into(),
3052 },
3053 ]);
3054 let chunks = HierarchicalChunker.chunk(&doc);
3055 assert_eq!(chunks[0].text, "Table 1: Revenue\n\n2024, Revenue = 10");
3056 let refs: Vec<Vec<&str>> = chunks
3057 .iter()
3058 .map(|c| c.doc_items.iter().map(|i| i.self_ref.as_str()).collect())
3059 .collect();
3060 assert_eq!(
3061 refs,
3062 [
3063 vec!["#/texts/0", "#/tables/0"],
3064 vec!["#/texts/1"],
3065 vec!["#/texts/2", "#/tables/1"],
3066 vec!["#/texts/3"],
3067 ]
3068 );
3069 let json = doc.export_to_json_value();
3070 assert_eq!(json["texts"][1]["text"], "Revenue grew in 2024.");
3071 assert_eq!(json["texts"][3]["text"], "Costs were flat.");
3072 }
3073
3074 #[test]
3078 fn refs_follow_an_item_tree() {
3079 use crate::tree::{ItemTree, TreeKind};
3080 let text = |label: &str, t: &str| TreeKind::Text {
3081 label: label.into(),
3082 text: t.into(),
3083 orig: None,
3084 formatting: None,
3085 hyperlink: None,
3086 level: None,
3087 list: None,
3088 };
3089 let mut doc = doc_with(vec![
3090 Node::Paragraph {
3091 text: "Lead **bold** tail".into(),
3092 },
3093 Node::Paragraph {
3094 text: "Second.".into(),
3095 },
3096 ]);
3097 let mut t = ItemTree {
3098 inline_whitespace: true,
3099 ..Default::default()
3100 };
3101 t.add(
3102 None,
3103 Some(crate::ContentLayer::Furniture),
3104 text("title", "Page"),
3105 );
3106 let g = t.add(
3107 None,
3108 None,
3109 TreeKind::Group {
3110 label: "inline".into(),
3111 name: "group".into(),
3112 },
3113 );
3114 t.add(Some(g), None, text("text", "Lead "));
3115 t.add(Some(g), None, text("text", "bold"));
3116 t.add(Some(g), None, text("text", " tail"));
3117 t.add(None, None, text("text", "Second."));
3118 doc.tree = Some(t);
3119 let refs: Vec<Vec<String>> = HierarchicalChunker
3120 .chunk(&doc)
3121 .iter()
3122 .map(|c| c.doc_items.iter().map(|i| i.self_ref.clone()).collect())
3123 .collect();
3124 assert_eq!(
3125 refs,
3126 [
3127 vec![
3128 "#/texts/1".to_string(),
3129 "#/texts/2".into(),
3130 "#/texts/3".into()
3131 ],
3132 vec!["#/texts/4".to_string()],
3133 ]
3134 );
3135 }
3136
3137 #[test]
3141 fn picture_children_are_not_chunked_but_keep_refs_aligned() {
3142 let doc = doc_with(vec![
3143 Node::Picture {
3144 caption: None,
3145 caption_href: None,
3146 image: None,
3147 classification: None,
3148 description: None,
3149 caption_parent: crate::CaptionParent::Item,
3150 caption_location: None,
3151 },
3152 Node::PictureChildren(vec![
3153 Node::Paragraph {
3154 text: "axis label".into(),
3155 },
3156 Node::ListItem {
3157 ordered: false,
3158 number: 0,
3159 first_in_list: true,
3160 text: "callout".into(),
3161 level: 0,
3162 marker: None,
3163 location: None,
3164 split: None,
3165 dclx: None,
3166 href: None,
3167 layer: None,
3168 },
3169 ]),
3170 Node::Paragraph {
3171 text: "Body".into(),
3172 },
3173 ]);
3174 let chunks = HierarchicalChunker.chunk(&doc);
3175 assert_eq!(chunks.len(), 1);
3176 assert_eq!(chunks[0].text, "Body");
3177 let json = doc.export_to_json_value();
3178 assert_eq!(json["texts"][2]["text"], "Body");
3179 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/2");
3180 }
3181
3182 #[test]
3183 fn heading_shadowing_prunes_deeper_levels() {
3184 let doc = doc_with(vec![
3185 Node::Heading {
3186 level: 2,
3187 text: "A".into(),
3188 },
3189 Node::Heading {
3190 level: 3,
3191 text: "A.1".into(),
3192 },
3193 Node::Heading {
3194 level: 2,
3195 text: "B".into(),
3196 },
3197 Node::Paragraph { text: "p".into() },
3198 ]);
3199 let chunks = HierarchicalChunker.chunk(&doc);
3200 assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
3201 }
3202
3203 #[test]
3208 fn rich_heading_is_the_heading_context() {
3209 for body in [Some("Body."), None] {
3210 let mut nodes = vec![Node::Heading {
3211 level: 1,
3212 text: "Hello **bold** world".into(),
3213 }];
3214 if let Some(b) = body {
3215 nodes.push(Node::Paragraph { text: b.into() });
3216 }
3217 let doc = doc_with(nodes);
3218 for chunks in [
3219 HierarchicalChunker.chunk(&doc),
3220 HybridChunker::new(WordTok(64)).chunk(&doc),
3221 ] {
3222 let got: Vec<_> = chunks
3223 .iter()
3224 .map(|c| (c.text.as_str(), c.headings.clone()))
3225 .collect();
3226 let want: Vec<_> = body
3227 .map(|b| (b, Some(vec!["Hello **bold** world".to_string()])))
3228 .into_iter()
3229 .collect();
3230 assert_eq!(got, want);
3231 }
3232 }
3233 }
3234
3235 #[test]
3240 fn rich_heading_shadowed_by_a_sibling() {
3241 let doc = doc_with(vec![
3242 Node::Heading {
3243 level: 1,
3244 text: "Energy *E* here".into(),
3245 },
3246 Node::Heading {
3247 level: 1,
3248 text: "Next".into(),
3249 },
3250 Node::Paragraph {
3251 text: "Body.".into(),
3252 },
3253 ]);
3254 let chunks = HierarchicalChunker.chunk(&doc);
3255 assert_eq!(chunks.len(), 1);
3256 assert_eq!(chunks[0].text, "Body.");
3257 assert_eq!(chunks[0].headings.as_deref(), Some(&["Next".into()][..]));
3258 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/2");
3259 }
3260
3261 #[test]
3264 fn split_table_pieces_fit_with_headings() {
3265 let rows: Vec<Vec<String>> = std::iter::once(vec!["".to_string(), "A".into(), "B".into()])
3266 .chain((0..40).map(|i| vec![format!("R{i}"), format!("{i}"), format!("v{i}")]))
3267 .collect();
3268 let doc = doc_with(vec![
3269 Node::Heading {
3270 level: 1,
3271 text: "one two three four five six".into(),
3272 },
3273 Node::Table(Table {
3274 rows,
3275 ..Default::default()
3276 }),
3277 ]);
3278 let h = HybridChunker::new(WordTok(20));
3279 let chunks = h.chunk(&doc);
3280 assert!(chunks.len() > 1);
3281 for c in &chunks {
3282 assert!(
3283 h.count_chunk_tokens(c) <= 20,
3284 "over budget: {}",
3285 h.count_chunk_tokens(c)
3286 );
3287 }
3288 }
3289
3290 #[test]
3291 fn triplet_table() {
3292 let t = Table {
3293 rows: vec![
3294 vec!["".into(), "Col1".into()],
3295 vec!["Row1".into(), "v".into()],
3296 ],
3297 ..Default::default()
3298 };
3299 assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
3300 let single = Table {
3303 rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
3304 ..Default::default()
3305 };
3306 assert_eq!(triplet_table_text(&single), "a = b");
3307 }
3308
3309 #[test]
3313 fn markdown_tables_match_docling_serve() {
3314 let doc = doc_with(vec![
3315 Node::Heading {
3316 level: 1,
3317 text: "Plans".into(),
3318 },
3319 Node::Table(Table {
3320 rows: vec![
3321 vec!["Plan".into(), "Price".into(), "Seats".into()],
3322 vec!["Pro".into(), "$49".into(), "5".into()],
3323 vec!["Team".into(), "$99".into(), "20".into()],
3324 ],
3325 ..Default::default()
3326 }),
3327 ]);
3328 let want = "Plans\n| Plan | Price | Seats |\n|--------|---------|---------|\n\
3329 | Pro | $49 | 5 |\n| Team | $99 | 20 |";
3330 let md = HierarchicalChunker.chunk_as(&doc, TableFormat::Markdown);
3331 assert_eq!(md.len(), 1);
3332 assert_eq!(contextualize(&md[0]), want);
3333 assert_eq!(md[0].doc_items[0].kind, ChunkItemKind::Table);
3334 assert_eq!(md[0].doc_items[0].text, md[0].text);
3335 let hybrid = HybridChunker::new(WordTok(512)).with_table_format(TableFormat::Markdown);
3336 assert_eq!(contextualize(&hybrid.chunk(&doc)[0]), want);
3337 let triplets =
3340 "Plans\nPro, Price = $49. Pro, Seats = 5. Team, Price = $99. Team, Seats = 20";
3341 assert_eq!(
3342 contextualize(&HybridChunker::new(WordTok(512)).chunk(&doc)[0]),
3343 triplets
3344 );
3345 assert_eq!(contextualize(&HierarchicalChunker.chunk(&doc)[0]), triplets);
3346 assert_eq!(
3347 HierarchicalChunker.chunk_as(&doc, TableFormat::Triplet),
3348 HierarchicalChunker.chunk(&doc)
3349 );
3350 }
3351
3352 #[test]
3356 fn markdown_table_split_repeats_the_header() {
3357 let mut rows = vec![vec!["Name".to_string(), "Score".to_string()]];
3358 for i in 0..20 {
3359 rows.push(vec![format!("n{i}"), format!("{i}")]);
3360 }
3361 let doc = doc_with(vec![Node::Table(Table {
3362 rows,
3363 ..Default::default()
3364 })]);
3365 let hybrid = HybridChunker::new(WordTok(40)).with_table_format(TableFormat::Markdown);
3366 let chunks = hybrid.chunk(&doc);
3367 assert!(chunks.len() > 1, "{chunks:?}");
3368 let mut seen = Vec::new();
3369 for c in &chunks {
3370 assert!(WordTok(40).count_tokens(&contextualize(c)) <= 40, "{c:?}");
3371 let lines: Vec<&str> = c.text.lines().collect();
3372 assert!(lines[0].starts_with("| Name"), "{c:?}");
3373 assert!(lines[1].starts_with("|---"), "{c:?}");
3374 for l in &lines[2..] {
3375 seen.push(l.split('|').nth(1).unwrap().trim().to_string());
3376 }
3377 }
3378 let want: Vec<String> = (0..20).map(|i| format!("n{i}")).collect();
3380 assert_eq!(seen, want);
3381 }
3382
3383 #[test]
3387 fn markdown_table_too_wide_splits_by_columns() {
3388 let header: Vec<String> = (0..6).map(|c| format!("h{c}")).collect();
3389 let row: Vec<String> = (0..6).map(|c| format!("a{c} b{c} c{c}")).collect();
3390 let doc = doc_with(vec![Node::Table(Table {
3391 rows: vec![header, row],
3392 ..Default::default()
3393 })]);
3394 let hybrid = HybridChunker::new(WordTok(24))
3395 .with_table_format(TableFormat::Markdown)
3396 .with_merge_peers(false);
3397 let chunks = hybrid.chunk(&doc);
3398 assert!(chunks.len() > 1, "{chunks:?}");
3399 let mut cols = Vec::new();
3400 for c in &chunks {
3401 assert!(WordTok(24).count_tokens(&contextualize(c)) <= 24, "{c:?}");
3402 let lines: Vec<&str> = c.text.trim_end().lines().collect();
3403 assert_eq!(lines.len(), 3, "{c:?}");
3404 let heads: Vec<&str> = lines[0]
3405 .trim_matches('|')
3406 .split('|')
3407 .map(str::trim)
3408 .collect();
3409 let cells: Vec<&str> = lines[2]
3410 .trim_matches('|')
3411 .split('|')
3412 .map(str::trim)
3413 .collect();
3414 assert_eq!(heads.len(), cells.len());
3415 assert!(lines[1].starts_with("| - |"));
3416 for (h, v) in heads.iter().zip(&cells) {
3417 let i = &h[1..];
3418 assert_eq!(*v, format!("a{i} b{i} c{i}"));
3419 cols.push(i.to_string());
3420 }
3421 }
3422 assert_eq!(cols, (0..6).map(|c| c.to_string()).collect::<Vec<_>>());
3423 }
3424
3425 #[test]
3428 fn markdown_table_cells_escape_pipes() {
3429 let t = Table {
3430 rows: vec![
3431 vec!["k".into(), "v".into()],
3432 vec!["a|b".into(), "x_y".into()],
3433 ],
3434 ..Default::default()
3435 };
3436 assert_eq!(
3437 markdown_table_text(&t),
3438 "| k | v |\n|----------|-----|\n| a|b | x_y |"
3439 );
3440 }
3441
3442 fn quadratic_merge<T: ChunkTokenizer>(
3446 h: &HybridChunker<T>,
3447 chunks: Vec<DocChunk>,
3448 ) -> Vec<DocChunk> {
3449 let mut out = Vec::new();
3450 let mut window: Vec<DocChunk> = Vec::new();
3451 let flush = |window: &mut Vec<DocChunk>, out: &mut Vec<DocChunk>| match window.len() {
3452 0 => {}
3453 1 => out.push(window.pop().unwrap()),
3454 _ => {
3455 out.push(merged_chunk(window.iter()));
3456 window.clear();
3457 }
3458 };
3459 for chunk in chunks {
3460 if window.is_empty() {
3461 window.push(chunk);
3462 continue;
3463 }
3464 let candidate = merged_chunk(window.iter().chain([&chunk]));
3465 if chunk.headings == window[0].headings
3466 && h.count_chunk_tokens(&candidate) <= h.max_tokens()
3467 {
3468 window.push(chunk);
3469 } else {
3470 flush(&mut window, &mut out);
3471 window.push(chunk);
3472 }
3473 }
3474 flush(&mut window, &mut out);
3475 out
3476 }
3477
3478 fn linear_merge<T: ChunkTokenizer>(
3479 h: &HybridChunker<T>,
3480 chunks: Vec<DocChunk>,
3481 ) -> Vec<DocChunk> {
3482 let mut out = Vec::new();
3483 let mut sink = |c| {
3484 out.push(c);
3485 true
3486 };
3487 let mut m = PeerMerger::default();
3488 for c in chunks {
3489 assert!(h.merge_push(&mut m, c, &mut sink));
3490 }
3491 assert!(h.merge_flush(&mut m, &mut sink));
3492 out
3493 }
3494
3495 struct QuadCharTok(usize);
3500 impl ChunkTokenizer for QuadCharTok {
3501 fn count_tokens(&self, text: &str) -> usize {
3502 text.chars().count().div_ceil(4)
3503 }
3504 fn max_tokens(&self) -> usize {
3505 self.0
3506 }
3507 }
3508
3509 fn random_chunks(seed: u64, n: usize) -> Vec<DocChunk> {
3512 let mut state = seed;
3513 let mut next = move |m: u64| {
3514 state = state
3515 .wrapping_mul(6364136223846793005)
3516 .wrapping_add(1442695040888963407);
3517 (state >> 33) % m
3518 };
3519 let headings = [
3520 None,
3521 Some(vec!["A".to_string()]),
3522 Some(vec!["A".into(), "B".into()]),
3523 ];
3524 let mut current = 0;
3525 (0..n)
3526 .map(|i| {
3527 if next(4) == 0 {
3528 current = next(3) as usize;
3529 }
3530 let words = 1 + next(12) as usize;
3531 let text = (0..words)
3532 .map(|w| ["x", "lorem", "ipsum", "dolor", "sit"][(w + i) % 5])
3533 .collect::<Vec<_>>()
3534 .join(" ");
3535 DocChunk {
3536 text,
3537 headings: headings[current].clone(),
3538 doc_items: vec![ChunkItem {
3539 self_ref: format!("#/texts/{i}"),
3540 kind: ChunkItemKind::Text,
3541 text: String::new(),
3542 }],
3543 }
3544 })
3545 .collect()
3546 }
3547
3548 #[test]
3552 fn linear_peer_merge_matches_the_quadratic_one() {
3553 for seed in 0..40 {
3554 let chunks = random_chunks(seed, 60);
3555 for max in [3, 8, 16, 40, 200] {
3556 let h = HybridChunker::new(WordTok(max));
3557 assert_eq!(
3558 linear_merge(&h, chunks.clone()),
3559 quadratic_merge(&h, chunks.clone()),
3560 "words, seed {seed}, max {max}"
3561 );
3562 let h = HybridChunker::new(QuadCharTok(max));
3563 assert_eq!(
3564 linear_merge(&h, chunks.clone()),
3565 quadratic_merge(&h, chunks.clone()),
3566 "chars/4, seed {seed}, max {max}"
3567 );
3568 }
3569 }
3570 }
3571
3572 #[test]
3576 #[ignore]
3577 fn peer_merge_bench() {
3578 let chunks: Vec<DocChunk> = (0..10_000)
3579 .map(|i| DocChunk {
3580 text: format!("Paragraph number {i} is short."),
3581 headings: Some(vec!["Section".into()]),
3582 doc_items: Vec::new(),
3583 })
3584 .collect();
3585 let h = HybridChunker::new(WordTok(8192));
3586 let t = std::time::Instant::now();
3587 let fast = linear_merge(&h, chunks.clone());
3588 let linear = t.elapsed();
3589 let t = std::time::Instant::now();
3590 let slow = quadratic_merge(&h, chunks);
3591 let quadratic = t.elapsed();
3592 assert_eq!(fast, slow);
3593 println!(
3594 "linear {linear:?}, quadratic {quadratic:?}, {} chunks",
3595 fast.len()
3596 );
3597 }
3598
3599 fn cell_table(
3602 num_rows: usize,
3603 num_cols: usize,
3604 cells: &[(&str, usize, usize, usize, bool)],
3605 ) -> Table {
3606 let mut rows = vec![vec![String::new(); num_cols]; num_rows];
3607 for &(text, r, c, span, _) in cells {
3608 for row in rows.iter_mut().skip(r).take(span) {
3609 row[c] = text.into();
3610 }
3611 }
3612 Table {
3613 rows,
3614 cells: Some(
3615 cells
3616 .iter()
3617 .map(|&(text, r, c, span, ched)| crate::TableCell {
3618 text: text.into(),
3619 bbox: None,
3620 start_row: r,
3621 start_col: c,
3622 row_span: span,
3623 col_span: 1,
3624 column_header: ched,
3625 row_header: false,
3626 row_section: false,
3627 })
3628 .collect(),
3629 ),
3630 ..Default::default()
3631 }
3632 }
3633
3634 #[test]
3640 fn markdown_and_triplets_share_the_header_rows() {
3641 type Case<'a> = (
3642 &'a str,
3643 usize,
3644 usize,
3645 Vec<(&'a str, usize, usize, usize, bool)>,
3646 &'a str,
3647 &'a str,
3648 );
3649 let cases: Vec<Case> = vec![
3650 (
3651 "rows under a row-spanning header stay in the body",
3652 2,
3653 2,
3654 vec![("Price", 0, 0, 1, true), ("Category", 0, 1, 2, true), ("10.00", 1, 0, 1, false)],
3655 "| Price | Category |\n| - | - |\n| 10.00 | Category |",
3656 "10.00, Category = Category",
3657 ),
3658 (
3659 "a row header flagged as column header stays in the body",
3660 3,
3661 3,
3662 vec![
3663 ("Year", 0, 0, 1, true),
3664 ("Month", 0, 1, 1, true),
3665 ("Revenue", 0, 2, 1, true),
3666 ("2025", 1, 0, 2, true),
3667 ("January", 1, 1, 1, false),
3668 ("$134", 1, 2, 1, false),
3669 ("February", 2, 1, 1, false),
3670 ("$150", 2, 2, 1, false),
3671 ],
3672 "| Year | Month | Revenue |\n| - | - | - |\n| 2025 | January | $134 |\n| 2025 | February | $150 |",
3673 "2025, Month = January. 2025, Revenue = $134. 2025, Month = February. 2025, Revenue = $150",
3674 ),
3675 (
3676 "stacked header with an unmarked row label",
3677 3,
3678 3,
3679 vec![
3680 ("", 0, 0, 1, true),
3681 ("% of Total", 0, 1, 1, true),
3682 ("% of Total", 0, 2, 1, true),
3683 ("class label", 1, 0, 1, false),
3684 ("Train", 1, 1, 1, true),
3685 ("Test", 1, 2, 1, true),
3686 ("Caption", 2, 0, 1, false),
3687 ("2.5", 2, 1, 1, false),
3688 ("2.4", 2, 2, 1, false),
3689 ],
3690 "| class label | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.5 | 2.4 |",
3691 "Caption, % of Total.Train = 2.5. Caption, % of Total.Test = 2.4",
3692 ),
3693 (
3694 "a partially flagged first row stays the header",
3695 2,
3696 2,
3697 vec![("Name", 0, 0, 1, true), ("Value", 0, 1, 1, false), ("A", 1, 0, 1, false), ("1", 1, 1, 1, false)],
3698 "| Name | Value |\n| - | - |\n| A | 1 |",
3699 "A, Value = 1",
3700 ),
3701 (
3702 "no flags: Markdown promotes row 0, triplets do not",
3703 2,
3704 2,
3705 vec![("Name", 0, 0, 1, false), ("Value", 0, 1, 1, false), ("A", 1, 0, 1, false), ("1", 1, 1, 1, false)],
3706 "| Name | Value |\n| - | - |\n| A | 1 |",
3707 "Name, 1 = Value. A, 1 = 1",
3708 ),
3709 (
3710 "row headers flagged as column headers stay in the body",
3711 2,
3712 2,
3713 vec![("2025", 0, 0, 1, true), ("$134", 0, 1, 1, false), ("2026", 1, 0, 1, true), ("$150", 1, 1, 1, false)],
3714 "| | |\n| - | - |\n| 2025 | $134 |\n| 2026 | $150 |",
3715 "2025, 1 = $134. 2026, 1 = $150",
3716 ),
3717 (
3718 "a form with flagged first-column labels is all data",
3719 3,
3720 2,
3721 vec![
3722 ("Name", 0, 0, 1, true),
3723 ("Bob", 0, 1, 1, false),
3724 ("Age", 1, 0, 1, true),
3725 ("42", 1, 1, 1, false),
3726 ("City", 2, 0, 1, true),
3727 ("Paris", 2, 1, 1, false),
3728 ],
3729 "| | |\n| - | - |\n| Name | Bob |\n| Age | 42 |\n| City | Paris |",
3730 "Name, 1 = Bob. Age, 1 = 42. City, 1 = Paris",
3731 ),
3732 (
3733 "a partly flagged row 0 above a stacked header row",
3734 3,
3735 3,
3736 vec![
3737 ("Region", 0, 0, 1, true),
3738 ("2025", 0, 1, 1, false),
3739 ("", 0, 2, 1, false),
3740 ("", 1, 0, 1, false),
3741 ("Q1", 1, 1, 1, true),
3742 ("Q2", 1, 2, 1, true),
3743 ("North", 2, 0, 1, false),
3744 ("1", 2, 1, 1, false),
3745 ("2", 2, 2, 1, false),
3746 ],
3747 "| Region | 2025 - Q1 | Q2 |\n| - | - | - |\n| North | 1 | 2 |",
3748 "North, 2025.Q1 = 1. North, Q2 = 2",
3749 ),
3750 ];
3751 for (name, rows, cols, cells, md, triplets) in cases {
3752 let t = cell_table(rows, cols, &cells);
3753 assert_eq!(
3754 crate::markdown::render_table(&t, true),
3755 md,
3756 "{name}: markdown"
3757 );
3758 assert_eq!(triplet_table_text(&t), triplets, "{name}: triplets");
3759 }
3760 }
3761
3762 #[test]
3767 fn a_column_spanning_rich_cell_repeats_in_every_column() {
3768 let mut t = cell_table(
3769 2,
3770 3,
3771 &[
3772 ("", 0, 0, 1, true),
3773 ("Partner", 0, 1, 1, true),
3774 ("Status", 1, 0, 1, false),
3775 ("Done", 1, 1, 1, false),
3776 ("Open", 1, 2, 1, false),
3777 ],
3778 );
3779 if let Some(cells) = t.cells.as_mut() {
3780 cells[1].col_span = 2;
3781 }
3782 let mut blocks = vec![vec![Vec::new(); 3]; 2];
3783 blocks[0][1] = vec![Node::Paragraph {
3784 text: "Partner".into(),
3785 }];
3786 t.cell_blocks = Some(blocks);
3787 assert_eq!(
3788 t.rows[0][2], "",
3789 "the covered position carries no text of its own"
3790 );
3791 assert_eq!(
3792 triplet_table_text(&t),
3793 "Status, Partner = Done. Status, Partner = Open"
3794 );
3795 let latex = crate::latex::render_table(&t);
3796 assert!(
3797 latex.contains(" & Partner & Partner \\\\ \\hline\nStatus & Done & Open \\\\ \\hline"),
3798 "{latex}"
3799 );
3800 t.rows[0][2] = "Partner".into();
3802 assert_eq!(
3803 crate::markdown::render_table(&t, true),
3804 "| | Partner | Partner |\n| - | - | - |\n| Status | Done | Open |"
3805 );
3806 }
3807
3808 #[test]
3809 fn hybrid_merges_small_peers_and_splits_large() {
3810 let doc = doc_with(vec![
3811 Node::Heading {
3812 level: 2,
3813 text: "S".into(),
3814 },
3815 Node::Paragraph { text: "a b".into() },
3816 Node::Paragraph { text: "c d".into() },
3817 ]);
3818 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
3819 assert_eq!(chunks.len(), 1, "peers under one heading merge");
3820 assert_eq!(chunks[0].text, "a b\nc d");
3821
3822 let long = "w ".repeat(40).trim().to_string();
3823 let doc = doc_with(vec![Node::Paragraph { text: long }]);
3824 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
3825 assert!(chunks.len() > 1, "oversized paragraph splits");
3826 for c in &chunks {
3827 assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
3828 }
3829 }
3830
3831 #[test]
3832 fn semchunk_prefers_newlines_then_sentences() {
3833 let tok = WordTok(4);
3834 let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
3835 assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
3836 }
3837
3838 #[test]
3841 fn dollar_amounts_are_not_inline_formulas() {
3842 for text in [
3843 "costs $5 and $0.25",
3844 "a bet of $5 riding on the game. The player has just won $6 on the game.",
3845 "pay $10, get $ 3 back",
3846 ] {
3847 assert_eq!(
3848 inline_segments(text),
3849 vec![text.to_string()],
3850 "{text:?} was split"
3851 );
3852 let doc = doc_with(vec![Node::Paragraph { text: text.into() }]);
3853 let chunks = HierarchicalChunker.chunk(&doc);
3854 assert_eq!(chunks.len(), 1);
3855 assert_eq!(chunks[0].text, text);
3856 assert_eq!(chunks[0].doc_items.len(), 1);
3857 assert_eq!(chunks[0].doc_items[0].text, text);
3858 }
3859 }
3860
3861 #[test]
3863 fn dollar_math_inline_formulas_still_split() {
3864 assert_eq!(
3865 inline_segments("where $E=mc^2$ holds"),
3866 vec!["where", "$$E=mc^2$$", "holds"]
3867 );
3868 assert_eq!(inline_segments("$x$"), vec!["$$x$$"]);
3869 }
3870
3871 #[test]
3874 fn formula_runs_decide_inline_formulas() {
3875 let runs = vec![
3876 crate::InlineRun {
3877 text: "costs $5, and".into(),
3878 ..Default::default()
3879 },
3880 crate::InlineRun {
3881 text: "x + 1".into(),
3882 formula: true,
3883 ..Default::default()
3884 },
3885 crate::InlineRun {
3886 text: "is $6".into(),
3887 ..Default::default()
3888 },
3889 ];
3890 let segs: Vec<String> = inline_segments_tagged("costs $5, and $x + 1$ is $6", &runs)
3891 .into_iter()
3892 .map(|(t, _)| t)
3893 .collect();
3894 assert_eq!(segs, vec!["costs $5, and", "$$x + 1$$", "is $6"]);
3895 }
3896}