1use std::collections::BTreeMap;
24
25use crate::document::{DoclingDocument, Node, Table};
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum ChunkItemKind {
31 Text,
33 Table,
36 Picture,
38}
39
40#[derive(Debug, Clone, PartialEq)]
43pub struct ChunkItem {
44 pub self_ref: String,
47 pub kind: ChunkItemKind,
48 pub text: String,
52}
53
54#[derive(Debug, Clone, PartialEq)]
56pub struct DocChunk {
57 pub text: String,
60 pub headings: Option<Vec<String>>,
63 pub doc_items: Vec<ChunkItem>,
65}
66
67pub 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#[derive(Debug, Clone, Default)]
86pub struct HierarchicalChunker;
87
88impl HierarchicalChunker {
89 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 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#[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 headings: BTreeMap<u8, String>,
165 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 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 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 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; }
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 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 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 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 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 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 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 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 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 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 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 Node::Group { children, .. } => {
595 self.alloc.group();
598 self.walk(children);
599 }
600 Node::FieldRegion { items } => {
601 self.alloc.field_region();
604 for item in items {
605 self.alloc.field_item();
606 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
607 let self_ref = self.alloc.text();
608 let body = unescape_text(part);
609 self.emit(
610 body.clone(),
611 vec![ChunkItem {
612 self_ref,
613 kind: ChunkItemKind::Text,
614 text: body,
615 }],
616 );
617 }
618 }
619 }
620 Node::InlineGroup { md_text, runs, .. } => {
621 let self_ref = self.alloc.text();
622 self.emit_inline_with_runs(md_text, self_ref, runs);
623 }
624 Node::TextDump(text) => {
625 let self_ref = self.alloc.text();
626 let body = unescape_text(text);
627 self.emit(
628 body.clone(),
629 vec![ChunkItem {
630 self_ref,
631 kind: ChunkItemKind::Text,
632 text: body,
633 }],
634 );
635 }
636 Node::Located { inner, .. } => self.one(inner),
638 Node::Furniture { .. }
641 | Node::PageFurniture { .. }
642 | Node::PageBreak
643 | Node::DoclangOnly(_) => {}
644 Node::ListItem { .. } => unreachable!("list items are chunked in runs"),
645 }
646 }
647}
648
649fn level_of(node: &Node) -> u8 {
650 match node {
651 Node::ListItem { level, .. } => *level,
652 _ => 0,
653 }
654}
655
656fn render_list(items: &[Node]) -> String {
659 let mut lines: Vec<String> = Vec::new();
660 for item in items {
661 let Node::ListItem {
662 ordered,
663 number,
664 text,
665 level,
666 layer,
667 ..
668 } = item
669 else {
670 continue;
671 };
672 if layer.is_some() {
673 continue;
674 }
675 let indent = " ".repeat(*level as usize);
676 let marker = if *ordered {
677 format!("{number}.")
678 } else {
679 "-".to_string()
680 };
681 lines.push(format!(
682 "{indent}{marker} {}",
683 unescape_text(&strip_image_markers(text))
684 ));
685 }
686 lines.join("\n")
687}
688
689fn strip_image_markers(text: &str) -> String {
694 if !text.contains("<!-- image -->") {
695 return text.to_string();
696 }
697 let cleaned: Vec<&str> = text
698 .split('\n')
699 .map(str::trim_end)
700 .filter(|l| *l != "<!-- image -->")
701 .collect();
702 cleaned.join("\n").trim_end().to_string()
703}
704
705fn humanize_label(label: &str) -> String {
708 let text = label.replace('_', " ");
709 let mut chars = text.chars();
710 match chars.next() {
711 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
712 None => text,
713 }
714}
715
716fn triplet_table_text(t: &Table) -> String {
723 let rows: Vec<Vec<String>> = t
724 .rows
725 .iter()
726 .enumerate()
727 .map(|(ri, r)| (0..r.len()).map(|ci| cell_chunk_text(t, ri, ci)).collect())
728 .collect();
729 let num_rows = rows.len();
730 let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
731 if num_rows == 0 || num_cols == 0 {
732 return String::new();
733 }
734 let cell = |r: usize, c: usize| -> &str {
735 rows.get(r)
736 .and_then(|row| row.get(c))
737 .map(String::as_str)
738 .unwrap_or("")
739 };
740
741 let cell_is_header = |r: usize, c: usize| -> bool {
745 let (mut r, mut c) = (r, c);
746 loop {
747 match &t.structure {
748 Some(s) if !s.col_header.is_empty() => {
749 return s
750 .col_header
751 .get(r)
752 .and_then(|row| row.get(c))
753 .copied()
754 .unwrap_or(false)
755 }
756 Some(s) => {
757 let cont = |g: &Vec<Vec<bool>>| {
758 g.get(r)
759 .and_then(|row| row.get(c))
760 .copied()
761 .unwrap_or(false)
762 };
763 if r > 0 && cont(&s.row_continuation) {
764 r -= 1;
765 continue;
766 }
767 if c > 0 && cont(&s.col_continuation) {
768 c -= 1;
769 continue;
770 }
771 return if s.header_row.is_empty() {
772 r == 0
773 } else {
774 s.header_row.get(r).copied().unwrap_or(false)
775 };
776 }
777 None => return r == 0,
778 }
779 }
780 };
781 let row_is_header = |r: usize| (0..num_cols).any(|c| cell_is_header(r, c));
782 let num_headers = (0..num_rows).take_while(|r| row_is_header(*r)).count();
783
784 let columns: Vec<String> = if num_headers > 0 {
787 (0..num_cols)
788 .map(|c| {
789 let mut name = String::new();
790 for r in 0..num_headers {
791 if !name.is_empty() {
792 name.push('.');
793 }
794 name.push_str(cell(r, c));
795 }
796 name
797 })
798 .collect()
799 } else {
800 (0..num_cols).map(|c| c.to_string()).collect()
801 };
802 let data_rows = num_headers..num_rows;
803 let n_data = data_rows.len();
804
805 if n_data == 0 {
807 return columns
808 .iter()
809 .map(|s| s.trim())
810 .filter(|s| !s.is_empty())
811 .collect::<Vec<_>>()
812 .join(". ");
813 }
814
815 let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
816 let text = if num_cols == 1 {
817 let col_name = data(0, 0).trim().to_string();
820 if n_data == 1 {
821 col_name
822 } else {
823 (1..n_data)
824 .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
825 .collect::<Vec<_>>()
826 .join(". ")
827 }
828 } else {
829 let mut parts = Vec::new();
831 for r in 0..n_data {
832 for (c, col_name) in columns.iter().enumerate().skip(1) {
833 parts.push(format!(
834 "{}, {} = {}",
835 data(r, 0).trim(),
836 col_name.trim(),
837 data(r, c).trim()
838 ));
839 }
840 }
841 parts.join(". ")
842 };
843 if !text.is_empty() {
844 return text;
845 }
846
847 (0..n_data)
850 .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
851 .map(|(r, c)| data(r, c).trim())
852 .filter(|s| !s.is_empty())
853 .collect::<Vec<_>>()
854 .join(". ")
855}
856
857fn inline_segments(md: &str) -> Vec<String> {
865 inline_segments_tagged(md)
866 .into_iter()
867 .map(|(t, _)| t)
868 .collect()
869}
870
871fn inline_segments_tagged(md: &str) -> Vec<(String, bool)> {
875 let chars: Vec<char> = md.chars().collect();
876 let n = chars.len();
877 let find = |from: usize, pat: &str| -> Option<usize> {
878 let hay: String = chars[from..].iter().collect();
879 hay.find(pat).map(|p| from + hay[..p].chars().count())
880 };
881 let mut out: Vec<(String, bool)> = Vec::new();
882 let mut plain = String::new();
883 let mut after_span = false;
884
885 fn flush(
886 out: &mut Vec<(String, bool)>,
887 plain: &mut String,
888 before_span: bool,
889 after_span: bool,
890 ) {
891 let mut p = std::mem::take(plain);
892 if after_span {
893 if let Some(rest) = p.strip_prefix(' ') {
894 p = rest.to_string();
895 }
896 }
897 if before_span {
898 if let Some(rest) = p.strip_suffix(' ') {
899 p = rest.to_string();
900 }
901 }
902 if !p.is_empty() {
903 out.push((unescape_text(&p), true));
904 }
905 }
906
907 let mut i = 0;
908 while i < n {
909 let rest: String = chars[i..].iter().collect();
910 if chars[i] == '[' && !rest.starts_with("[](") {
914 let balanced = |c: usize| {
918 let mut d = 0i32;
919 for &ch in &chars[i + 1..c] {
920 match ch {
921 '[' => d += 1,
922 ']' => d -= 1,
923 _ => {}
924 }
925 }
926 d == 0
927 };
928 if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
929 let mut depth = 0usize;
930 let mut url_end = None;
931 for (k, &c) in chars.iter().enumerate().skip(close + 2) {
932 match c {
933 '(' => depth += 1,
934 ')' => {
935 if depth == 0 {
936 url_end = Some(k);
937 break;
938 }
939 depth -= 1;
940 }
941 _ => {}
942 }
943 }
944 if let Some(endp) = url_end {
945 flush(&mut out, &mut plain, true, after_span);
946 out.push((
947 unescape_text(&chars[i..=endp].iter().collect::<String>()),
948 false,
949 ));
950 i = endp + 1;
951 after_span = true;
952 continue;
953 }
954 }
955 }
956 let mut matched = false;
959 for marker in ["***", "**", "*", "~~", "`"] {
960 if rest.starts_with(marker) {
961 let mlen = marker.chars().count();
962 if let Some(end) = find(i + mlen, marker) {
963 let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
967 if end > i + mlen && !inner_blank {
968 flush(&mut out, &mut plain, true, after_span);
969 if marker == "`" {
970 let inner: String = chars[i + 1..end].iter().collect();
971 out.push((format!("```\n{}\n```", unescape_text(&inner)), false));
972 } else {
973 out.push((
974 unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
975 false,
976 ));
977 }
978 i = end + mlen;
979 after_span = true;
980 matched = true;
981 }
982 }
983 break;
984 }
985 }
986 if matched {
987 continue;
988 }
989 if rest.starts_with("$$") {
992 plain.push_str("$$");
993 i += 2;
994 continue;
995 }
996 if chars[i] == '$' {
998 if let Some(end) = find(i + 1, "$") {
999 if end > i + 1 {
1000 flush(&mut out, &mut plain, true, after_span);
1001 let latex: String = chars[i + 1..end].iter().collect();
1002 out.push((format!("$${latex}$$"), false));
1003 i = end + 1;
1004 after_span = true;
1005 continue;
1006 }
1007 }
1008 }
1009 plain.push(chars[i]);
1010 i += 1;
1011 }
1012 flush(&mut out, &mut plain, false, after_span);
1013 if out.is_empty() {
1014 out.push((unescape_text(md), true));
1015 }
1016 out
1017}
1018
1019fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1024 let target = segment.trim();
1025 if target.is_empty() {
1026 return None;
1027 }
1028 let plainish =
1029 |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1030 let fully_plain =
1031 |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1032 let unmarked: Vec<(&str, bool)> = runs
1033 .iter()
1034 .filter(|r| plainish(r))
1035 .map(|r| (r.text.as_str(), fully_plain(r)))
1036 .collect();
1037 for start in 0..unmarked.len() {
1038 let mut rest = target;
1039 let mut taken: Vec<(String, bool)> = Vec::new();
1040 for (t, fully) in &unmarked[start..] {
1041 let t = t.trim();
1042 if t.is_empty() {
1043 continue;
1044 }
1045 match rest.strip_prefix(t) {
1046 Some(r) => {
1047 taken.push((unescape_text(t), *fully));
1048 rest = r.trim_start();
1049 if rest.is_empty() {
1050 break;
1051 }
1052 }
1053 None => break,
1054 }
1055 }
1056 if rest.is_empty() && taken.len() >= 2 {
1057 let mut merged: Vec<(String, bool)> = Vec::new();
1062 for (t, fully) in taken {
1063 match merged.last_mut() {
1064 Some((last, true)) if fully => {
1065 last.push(' ');
1066 last.push_str(&t);
1067 }
1068 _ => merged.push((t, fully)),
1069 }
1070 }
1071 if merged.len() >= 2 {
1072 return Some(merged.into_iter().map(|(t, _)| t).collect());
1073 }
1074 return None;
1075 }
1076 }
1077 None
1078}
1079
1080fn cell_chunk_text(t: &Table, r: usize, c: usize) -> String {
1087 if let Some(blocks) = t
1088 .cell_blocks
1089 .as_ref()
1090 .and_then(|b| b.get(r))
1091 .and_then(|row| row.get(c))
1092 .filter(|b| !b.is_empty())
1093 {
1094 let mut parts: Vec<String> = Vec::new();
1095 for node in blocks.iter() {
1096 let part = block_chunk_text(node);
1097 if !part.is_empty() {
1098 parts.push(part);
1099 }
1100 }
1101 return parts.join("\n\n");
1102 }
1103 let flat = t
1104 .rows
1105 .get(r)
1106 .and_then(|row| row.get(c))
1107 .map(String::as_str)
1108 .unwrap_or("");
1109 unescape_text(flat)
1110 .replace("<!-- image -->", "")
1111 .trim()
1112 .to_string()
1113}
1114
1115fn block_chunk_text(node: &Node) -> String {
1117 match node {
1118 Node::Paragraph { text } => unescape_text(text),
1119 Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1120 Node::Code { text, .. } => format!("```\n{}\n```", unescape_text(text)),
1121 Node::Table(inner) => triplet_table_text(inner),
1122 Node::Picture { caption, .. } => caption
1123 .as_deref()
1124 .filter(|c| !c.is_empty())
1125 .map(unescape_text)
1126 .unwrap_or_default(),
1127 Node::ListItem {
1128 ordered,
1129 number,
1130 text,
1131 ..
1132 } => {
1133 let marker = if *ordered {
1134 format!("{number}.")
1135 } else {
1136 "-".to_string()
1137 };
1138 format!("{marker} {}", unescape_text(text))
1139 }
1140 Node::CheckboxItem { checked, text } => {
1141 let mark = if *checked { "- [x] " } else { "- [ ] " };
1142 format!("{mark}{}", unescape_text(text))
1143 }
1144 Node::Heading { text, .. } => unescape_text(text),
1145 Node::Located { inner, .. } => block_chunk_text(inner),
1146 Node::Group { children, .. } => children
1147 .iter()
1148 .map(block_chunk_text)
1149 .filter(|s| !s.is_empty())
1150 .collect::<Vec<_>>()
1151 .join("\n"),
1152 _ => String::new(),
1153 }
1154}
1155
1156fn unescape_text(s: &str) -> String {
1159 s.replace("<", "<")
1160 .replace(">", ">")
1161 .replace("&", "&")
1162 .replace("\\_", "_")
1163}
1164
1165pub trait ChunkTokenizer {
1171 fn count_tokens(&self, text: &str) -> usize;
1173 fn max_tokens(&self) -> usize;
1175}
1176
1177pub struct HybridChunker<T: ChunkTokenizer> {
1181 tokenizer: T,
1182 merge_peers: bool,
1183}
1184
1185impl<T: ChunkTokenizer> HybridChunker<T> {
1186 pub fn new(tokenizer: T) -> Self {
1187 Self {
1188 tokenizer,
1189 merge_peers: true,
1190 }
1191 }
1192
1193 pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1195 self.merge_peers = merge_peers;
1196 self
1197 }
1198
1199 pub fn max_tokens(&self) -> usize {
1200 self.tokenizer.max_tokens()
1201 }
1202
1203 pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1205 let mut chunks = Vec::new();
1206 self.chunk_with(doc, &mut |c| {
1207 chunks.push(c);
1208 true
1209 });
1210 chunks
1211 }
1212
1213 pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1220 let mut merger = PeerMerger::default();
1221 let mut alive = true;
1222 HierarchicalChunker.chunk_with(doc, &mut |c| {
1223 for split in self.split_by_doc_items(c) {
1224 for chunk in self.split_using_plain_text(split) {
1225 if !alive {
1226 return false;
1227 }
1228 alive = if self.merge_peers {
1229 self.merge_push(&mut merger, chunk, sink)
1230 } else {
1231 sink(chunk)
1232 };
1233 }
1234 }
1235 alive
1236 });
1237 if alive {
1238 self.merge_flush(&mut merger, sink);
1239 }
1240 }
1241
1242 fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1243 self.tokenizer.count_tokens(&contextualize(chunk))
1244 }
1245
1246 fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1249 let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1250 let text = if chunk.doc_items.len() == 1 {
1251 chunk.text.clone()
1252 } else {
1253 doc_items
1254 .iter()
1255 .filter(|it| !it.text.is_empty())
1256 .map(|it| it.text.as_str())
1257 .collect::<Vec<_>>()
1258 .join("\n")
1259 };
1260 DocChunk {
1261 text,
1262 headings: chunk.headings.clone(),
1263 doc_items,
1264 }
1265 }
1266
1267 fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1268 if chunk.doc_items.is_empty() {
1269 return vec![chunk];
1270 }
1271 let max = self.max_tokens();
1272 let num_items = chunk.doc_items.len();
1273 let mut chunks = Vec::new();
1274 let mut window_start = 0usize;
1275 let mut window_end = 0usize; while window_end < num_items {
1277 let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1278 if self.count_chunk_tokens(&new_chunk) <= max {
1279 if window_end < num_items - 1 {
1280 window_end += 1;
1281 continue;
1282 } else {
1283 window_end = num_items; }
1285 } else if window_start == window_end {
1286 window_end += 1;
1289 window_start = window_end;
1290 } else {
1291 new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1294 window_start = window_end;
1295 }
1296 chunks.push(new_chunk);
1297 }
1298 chunks
1299 }
1300
1301 fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1302 let total = self.count_chunk_tokens(&chunk);
1303 let max = self.max_tokens();
1304 if total <= max {
1305 return vec![chunk];
1306 }
1307 let text_len = self.tokenizer.count_tokens(&chunk.text);
1308 let other_len = total - text_len;
1309 if other_len >= max {
1310 let stripped = DocChunk {
1312 headings: None,
1313 ..chunk
1314 };
1315 return self.split_using_plain_text(stripped);
1316 }
1317 let available = max - other_len;
1318
1319 let segments =
1320 if chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table {
1321 let lines: Vec<String> = chunk
1328 .text
1329 .split('\n')
1330 .filter(|l| !l.trim().is_empty())
1331 .map(|l| l.to_string())
1332 .collect();
1333 line_chunk_text(&lines, &self.tokenizer, max)
1334 } else {
1335 semchunk(&chunk.text, available, &self.tokenizer)
1336 };
1337 segments
1338 .into_iter()
1339 .map(|s| DocChunk {
1340 text: s,
1341 headings: chunk.headings.clone(),
1342 doc_items: chunk.doc_items.clone(),
1343 })
1344 .collect()
1345 }
1346
1347 fn merge_push(
1353 &self,
1354 m: &mut PeerMerger,
1355 chunk: DocChunk,
1356 sink: &mut dyn FnMut(DocChunk) -> bool,
1357 ) -> bool {
1358 if m.window.is_empty() {
1359 m.window.push(chunk);
1360 return true;
1361 }
1362 let candidate = DocChunk {
1363 text: m
1364 .window
1365 .iter()
1366 .map(|c| c.text.as_str())
1367 .chain([chunk.text.as_str()])
1368 .collect::<Vec<_>>()
1369 .join("\n"),
1370 headings: m.window[0].headings.clone(),
1371 doc_items: m
1372 .window
1373 .iter()
1374 .flat_map(|c| c.doc_items.iter().cloned())
1375 .chain(chunk.doc_items.iter().cloned())
1376 .collect(),
1377 };
1378 if chunk.headings == m.window[0].headings
1379 && self.count_chunk_tokens(&candidate) <= self.max_tokens()
1380 {
1381 m.window.push(chunk);
1382 m.merged = Some(candidate);
1383 true
1384 } else {
1385 let alive = self.merge_flush(m, sink);
1386 m.window.push(chunk);
1387 alive
1388 }
1389 }
1390
1391 fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
1395 let alive = if m.window.len() == 1 {
1396 sink(m.window.pop().expect("single-chunk window"))
1397 } else if !m.window.is_empty() {
1398 m.window.clear();
1399 sink(m.merged.take().expect("multi-chunk window has a merge"))
1400 } else {
1401 true
1402 };
1403 m.merged = None;
1404 alive
1405 }
1406}
1407
1408#[derive(Default)]
1410struct PeerMerger {
1411 window: Vec<DocChunk>,
1412 merged: Option<DocChunk>,
1413}
1414
1415fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
1425 let mut chunks: Vec<String> = Vec::new();
1426 let mut current = String::new();
1427 let mut current_len = 0usize;
1428
1429 for line in lines {
1430 let mut remaining: Vec<char> = line.chars().collect();
1431 loop {
1432 let rem_str: String = remaining.iter().collect();
1433 let line_tokens = tok.count_tokens(&rem_str);
1434 let available = max_tokens.saturating_sub(current_len);
1435
1436 if line_tokens <= available {
1437 current.push_str(&rem_str);
1438 current_len += line_tokens;
1439 break;
1440 }
1441 if line_tokens <= max_tokens {
1442 chunks.push(std::mem::take(&mut current));
1443 current_len = 0;
1444 continue;
1445 }
1446 let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
1448 let mut rest = rest;
1449 if take.is_empty() {
1450 if rest.is_empty() {
1451 break;
1452 }
1453 take = rest[..1].iter().collect();
1454 rest = rest[1..].to_vec();
1455 }
1456 current.push('\n');
1457 current.push_str(&take);
1458 chunks.push(std::mem::take(&mut current));
1459 current_len = 0;
1460 remaining = rest;
1461 }
1462 }
1463 if !current.is_empty() {
1464 chunks.push(current);
1465 }
1466 chunks
1467}
1468
1469fn split_by_token_limit<T: ChunkTokenizer>(
1473 text: &[char],
1474 token_limit: usize,
1475 tok: &T,
1476) -> (String, Vec<char>) {
1477 if token_limit == 0 || text.is_empty() {
1478 return (String::new(), text.to_vec());
1479 }
1480 let full: String = text.iter().collect();
1481 if tok.count_tokens(&full) <= token_limit {
1482 return (full, Vec::new());
1483 }
1484 let (mut lo, mut hi) = (0usize, text.len());
1485 let mut best: Option<usize> = None;
1486 while lo <= hi {
1487 let mid = (lo + hi) / 2;
1488 let head: String = text[..mid].iter().collect();
1489 if tok.count_tokens(&head) <= token_limit {
1490 best = Some(mid);
1491 lo = mid + 1;
1492 } else {
1493 if mid == 0 {
1494 break;
1495 }
1496 hi = mid - 1;
1497 }
1498 }
1499 let mut best_idx = match best {
1500 Some(b) if b > 0 => b,
1501 _ => return (String::new(), text.to_vec()),
1502 };
1503 if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
1505 if pos > 0 {
1506 best_idx = pos;
1507 }
1508 }
1509 (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
1510}
1511
1512const NON_WS_SPLITTERS: &[&str] = &[
1518 ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
1519 "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
1520];
1521
1522pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
1526 let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
1527 let mut counter = |s: &str| -> usize {
1528 if let Some(n) = cache.get(s) {
1529 return *n;
1530 }
1531 let n = tok.count_tokens(s);
1532 cache.insert(s.to_string(), n);
1533 n
1534 };
1535 let chunks = semchunk_rec(text, chunk_size, &mut counter);
1536 chunks
1538 .into_iter()
1539 .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
1540 .collect()
1541}
1542
1543fn semchunk_rec(
1546 text: &str,
1547 chunk_size: usize,
1548 counter: &mut dyn FnMut(&str) -> usize,
1549) -> Vec<String> {
1550 let (splitter, splitter_is_ws, splits) = split_text(text);
1551
1552 let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
1553 let mut cum_lens = Vec::with_capacity(splits.len() + 1);
1554 cum_lens.push(0usize);
1555 for l in &split_lens {
1556 cum_lens.push(cum_lens.last().unwrap() + l);
1557 }
1558 let num_splits_plus_one = splits.len() + 1;
1559
1560 let mut chunks: Vec<String> = Vec::new();
1561 let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
1562
1563 for i in 0..splits.len() {
1564 if skips.contains(&i) {
1565 continue;
1566 }
1567 let split = &splits[i];
1568 if counter(split) > chunk_size {
1569 let inner = semchunk_rec(split, chunk_size, counter);
1570 chunks.extend(inner);
1571 } else {
1572 let (end, merged) = merge_splits(
1573 &splits,
1574 &cum_lens,
1575 chunk_size,
1576 &splitter,
1577 counter,
1578 i,
1579 num_splits_plus_one,
1580 );
1581 for j in (i + 1)..end {
1582 skips.insert(j);
1583 }
1584 chunks.push(merged);
1585 }
1586 let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
1589 if !splitter_is_ws && !is_last {
1590 let with_splitter = format!(
1591 "{}{}",
1592 chunks.last().map(String::as_str).unwrap_or(""),
1593 splitter
1594 );
1595 if counter(&with_splitter) <= chunk_size {
1596 if let Some(last) = chunks.last_mut() {
1597 *last = with_splitter;
1598 } else {
1599 chunks.push(with_splitter);
1600 }
1601 } else {
1602 chunks.push(splitter.clone());
1603 }
1604 }
1605 }
1606 chunks
1607}
1608
1609fn merge_splits(
1612 splits: &[String],
1613 cum_lens: &[usize],
1614 chunk_size: usize,
1615 splitter: &str,
1616 counter: &mut dyn FnMut(&str) -> usize,
1617 start: usize,
1618 high_init: usize,
1619) -> (usize, String) {
1620 let mut average = 0.2f64;
1621 let mut low = start;
1622 let mut high = high_init;
1623 let offset = cum_lens[start];
1624 let mut target = offset as f64 + (chunk_size as f64 * average);
1625
1626 while low < high {
1627 let i = bisect_left(cum_lens, target, low, high);
1628 let midpoint = i.min(high - 1);
1629 let joined = splits[start..midpoint.max(start)].join(splitter);
1630 let tokens = counter(&joined);
1631 let local_cum = cum_lens[midpoint] - offset;
1632 if local_cum > 0 && tokens > 0 {
1633 average = local_cum as f64 / tokens as f64;
1634 target = offset as f64 + (chunk_size as f64 * average);
1635 }
1636 if tokens > chunk_size {
1637 high = midpoint;
1638 } else {
1639 low = midpoint + 1;
1640 }
1641 }
1642 let end = low - 1;
1643 (end, splits[start..end.max(start)].join(splitter))
1644}
1645
1646fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
1647 while low < high {
1648 let mid = (low + high) / 2;
1649 if (sorted[mid] as f64) < target {
1650 low = mid + 1;
1651 } else {
1652 high = mid;
1653 }
1654 }
1655 low
1656}
1657
1658fn split_text(text: &str) -> (String, bool, Vec<String>) {
1660 if text.contains('\n') || text.contains('\r') {
1662 let splitter = longest_run(text, |c| c == '\n' || c == '\r');
1663 return (splitter.clone(), true, split_on(text, &splitter));
1664 }
1665 if text.contains('\t') {
1667 let splitter = longest_run(text, |c| c == '\t');
1668 return (splitter.clone(), true, split_on(text, &splitter));
1669 }
1670 if text.chars().any(char::is_whitespace) {
1672 let splitter = longest_run(text, char::is_whitespace);
1673 if splitter.chars().count() == 1 {
1674 for preceder in NON_WS_SPLITTERS {
1676 if let Some((ws, parts)) = split_after_preceder(text, preceder) {
1677 return (ws, true, parts);
1678 }
1679 }
1680 }
1681 return (splitter.clone(), true, split_on(text, &splitter));
1682 }
1683 for s in NON_WS_SPLITTERS {
1685 if text.contains(s) {
1686 return (s.to_string(), false, split_on(text, s));
1687 }
1688 }
1689 (
1691 String::new(),
1692 true,
1693 text.chars().map(|c| c.to_string()).collect(),
1694 )
1695}
1696
1697fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
1699 let mut best = String::new();
1700 let mut cur = String::new();
1701 for c in text.chars() {
1702 if pred(c) {
1703 cur.push(c);
1704 } else {
1705 if cur.chars().count() > best.chars().count() {
1706 best = cur.clone();
1707 }
1708 cur.clear();
1709 }
1710 }
1711 if cur.chars().count() > best.chars().count() {
1712 best = cur;
1713 }
1714 best
1715}
1716
1717fn split_on(text: &str, splitter: &str) -> Vec<String> {
1718 text.split(splitter).map(str::to_string).collect()
1719}
1720
1721fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
1725 let chars: Vec<char> = text.chars().collect();
1726 let p: Vec<char> = preceder.chars().collect();
1727 let mut ws: Option<char> = None;
1728 for i in p.len()..chars.len() {
1729 if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
1730 ws = Some(chars[i]);
1731 break;
1732 }
1733 }
1734 let ws = ws?;
1735 let mut parts = Vec::new();
1736 let mut cur = String::new();
1737 let mut i = 0usize;
1738 while i < chars.len() {
1739 if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
1740 parts.push(std::mem::take(&mut cur));
1741 i += 1;
1742 continue;
1743 }
1744 cur.push(chars[i]);
1745 i += 1;
1746 }
1747 parts.push(cur);
1748 Some((ws.to_string(), parts))
1749}
1750
1751#[cfg(feature = "chunking")]
1756mod hf {
1757 use super::ChunkTokenizer;
1758
1759 pub const DEFAULT_TOKENIZER_PATH: &str = "models/chunk/tokenizer.json";
1764
1765 pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
1770 if let Some(p) = explicit {
1771 return Ok(p.to_string());
1772 }
1773 if std::path::Path::new(DEFAULT_TOKENIZER_PATH).exists() {
1774 return Ok(DEFAULT_TOKENIZER_PATH.to_string());
1775 }
1776 Err(format!(
1777 "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
1778 {DEFAULT_TOKENIZER_PATH} does not exist — run \
1779 scripts/install/download_dependencies.sh (or pass an explicit path)"
1780 ))
1781 }
1782
1783 pub struct HuggingFaceTokenizer {
1787 tok: tokenizers::Tokenizer,
1788 max_tokens: usize,
1789 }
1790
1791 impl HuggingFaceTokenizer {
1792 pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
1796 Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
1797 }
1798
1799 pub fn from_file(
1803 path: impl AsRef<std::path::Path>,
1804 max_tokens: usize,
1805 ) -> Result<Self, String> {
1806 let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
1807 .map_err(|e| format!("failed to load tokenizer: {e}"))?;
1808 let _ = tok.with_truncation(None);
1813 tok.with_padding(None);
1814 Ok(Self { tok, max_tokens })
1815 }
1816 }
1817
1818 impl ChunkTokenizer for HuggingFaceTokenizer {
1819 fn count_tokens(&self, text: &str) -> usize {
1820 self.tok
1821 .encode(text, false)
1822 .map(|e| e.get_tokens().len())
1823 .unwrap_or(0)
1824 }
1825 fn max_tokens(&self) -> usize {
1826 self.max_tokens
1827 }
1828 }
1829}
1830
1831#[cfg(feature = "chunking")]
1832pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
1833
1834#[cfg(feature = "chunking")]
1839mod window {
1840 use super::DocChunk;
1841 use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
1842
1843 #[derive(Debug, Clone, Default)]
1845 pub struct Section {
1846 pub heading_path: Vec<String>,
1849 pub words: Vec<String>,
1851 }
1852
1853 impl Section {
1854 pub fn heading_context(&self) -> String {
1857 if self.heading_path.is_empty() {
1858 String::new()
1859 } else {
1860 format!("# {}", self.heading_path.join(" > "))
1861 }
1862 }
1863 }
1864
1865 fn level_index(level: HeadingLevel) -> usize {
1866 match level {
1867 HeadingLevel::H1 => 1,
1868 HeadingLevel::H2 => 2,
1869 HeadingLevel::H3 => 3,
1870 HeadingLevel::H4 => 4,
1871 HeadingLevel::H5 => 5,
1872 HeadingLevel::H6 => 6,
1873 }
1874 }
1875
1876 pub fn parse_sections(markdown: &str) -> Vec<Section> {
1880 parse_sections_with_stack(markdown, Vec::new()).0
1881 }
1882
1883 pub fn parse_sections_with_stack(
1888 markdown: &str,
1889 initial_stack: Vec<String>,
1890 ) -> (Vec<Section>, Vec<String>) {
1891 let mut heading_stack: Vec<String> = initial_stack;
1892 let mut sections: Vec<Section> = Vec::new();
1893 let mut current = Section {
1896 heading_path: heading_stack
1897 .iter()
1898 .filter(|h| !h.is_empty())
1899 .cloned()
1900 .collect(),
1901 words: Vec::new(),
1902 };
1903
1904 let mut in_heading = false;
1905 let mut heading_level = 0usize;
1906 let mut heading_buf = String::new();
1907
1908 let push_words = |section: &mut Section, text: &str| {
1909 for w in text.split_whitespace() {
1910 section.words.push(w.to_string());
1911 }
1912 };
1913
1914 let flush = |sections: &mut Vec<Section>, section: &mut Section| {
1915 if !section.words.is_empty() {
1916 sections.push(std::mem::take(section));
1917 } else {
1918 *section = Section::default();
1919 }
1920 };
1921
1922 for event in Parser::new(markdown) {
1923 match event {
1924 Event::Start(Tag::Heading { level, .. }) => {
1925 in_heading = true;
1926 heading_level = level_index(level);
1927 heading_buf.clear();
1928 }
1929 Event::End(TagEnd::Heading(_)) => {
1930 in_heading = false;
1931 let idx = heading_level.saturating_sub(1);
1933 if heading_stack.len() <= idx {
1934 heading_stack.resize(idx + 1, String::new());
1935 } else {
1936 heading_stack.truncate(idx + 1);
1937 }
1938 heading_stack[idx] = heading_buf.trim().to_string();
1939 flush(&mut sections, &mut current);
1941 current.heading_path = heading_stack
1942 .iter()
1943 .filter(|h| !h.is_empty())
1944 .cloned()
1945 .collect();
1946 }
1947 Event::Text(t) | Event::Code(t) => {
1948 if in_heading {
1949 if !heading_buf.is_empty() {
1950 heading_buf.push(' ');
1951 }
1952 heading_buf.push_str(&t);
1953 } else {
1954 push_words(&mut current, &t);
1955 }
1956 }
1957 Event::SoftBreak | Event::HardBreak | Event::Rule => {}
1959 _ => {}
1960 }
1961 }
1962 flush(&mut sections, &mut current);
1963 (sections, heading_stack)
1964 }
1965
1966 #[derive(Debug, Clone)]
1972 pub struct WindowChunker {
1973 pub max_words: usize,
1975 pub overlap: f32,
1977 }
1978
1979 impl Default for WindowChunker {
1980 fn default() -> Self {
1981 WindowChunker {
1982 max_words: 300,
1983 overlap: 0.05,
1984 }
1985 }
1986 }
1987
1988 impl WindowChunker {
1989 pub fn new(max_words: usize, overlap: f32) -> Self {
1990 WindowChunker { max_words, overlap }
1991 }
1992
1993 fn word_budget(&self) -> usize {
1995 self.max_words.max(1)
1996 }
1997
1998 fn overlap_words(&self, budget: usize) -> usize {
2001 let o = (budget as f32 * self.overlap).round() as usize;
2002 o.min(budget.saturating_sub(1))
2003 }
2004
2005 pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
2007 let mut chunks = Vec::new();
2008 self.chunk_with(markdown, &mut |c| {
2009 chunks.push(c);
2010 true
2011 });
2012 chunks
2013 }
2014
2015 pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2019 let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2020 for section in §ions {
2021 if !self.pack_section(section, sink) {
2022 return;
2023 }
2024 }
2025 }
2026
2027 pub fn pack_section(
2031 &self,
2032 section: &Section,
2033 sink: &mut dyn FnMut(DocChunk) -> bool,
2034 ) -> bool {
2035 let words = §ion.words;
2036 if words.is_empty() {
2037 return true;
2038 }
2039 let budget = self.word_budget();
2040 let step = budget - self.overlap_words(budget); let mut start = 0;
2042 loop {
2043 let end = (start + budget).min(words.len());
2044 let chunk = DocChunk {
2045 text: words[start..end].join(" "),
2046 headings: (!section.heading_path.is_empty())
2047 .then(|| section.heading_path.clone()),
2048 doc_items: Vec::new(),
2049 };
2050 if !sink(chunk) {
2051 return false;
2052 }
2053 if end >= words.len() {
2054 return true;
2055 }
2056 start += step;
2057 }
2058 }
2059
2060 pub fn contextualize(chunk: &DocChunk) -> String {
2066 match &chunk.headings {
2067 Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2068 _ => chunk.text.clone(),
2069 }
2070 }
2071 }
2072
2073 #[cfg(test)]
2074 mod tests {
2075 use super::*;
2076
2077 #[test]
2078 fn splits_on_headings_and_tracks_path() {
2079 let md = "\
2080intro words
2081# Chapter 1
2082para one
2083## Section 1.1
2084para two
2085# Chapter 2
2086para three";
2087 let secs = parse_sections(md);
2088 assert_eq!(secs.len(), 4);
2090 assert!(secs[0].heading_path.is_empty());
2091 assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2092 assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2093 assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2095 }
2096
2097 #[test]
2098 fn strips_markup_to_plain_words() {
2099 let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2100 let secs = parse_sections(md);
2101 let words = &secs[0].words;
2102 assert!(words.contains(&"bold".to_string()));
2103 assert!(words.contains(&"code".to_string()));
2104 assert!(words.contains(&"link".to_string()));
2105 assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2107 }
2108
2109 #[test]
2110 fn windows_overlap_and_never_cross_headings() {
2111 let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2112 let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2113 let chunker = WindowChunker::new(10, 0.2); let chunks = chunker.chunk(&md);
2115 let a: Vec<_> = chunks
2117 .iter()
2118 .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2119 .collect();
2120 assert_eq!(a.len(), 3);
2121 assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2122 assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2123 assert!(a[2].text.ends_with(" w24"));
2124 let b: Vec<_> = chunks
2126 .iter()
2127 .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2128 .collect();
2129 assert_eq!(b.len(), 1);
2130 assert_eq!(b[0].text, "short tail");
2131 assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2132 }
2133
2134 #[test]
2135 fn sink_false_cancels_the_window_walk() {
2136 let md = format!(
2137 "# A\n\n{}\n",
2138 (0..50)
2139 .map(|i| format!("w{i}"))
2140 .collect::<Vec<_>>()
2141 .join(" ")
2142 );
2143 let chunker = WindowChunker::new(10, 0.0);
2144 let mut n = 0;
2145 chunker.chunk_with(&md, &mut |_| {
2146 n += 1;
2147 false
2148 });
2149 assert_eq!(n, 1);
2150 }
2151 }
2152}
2153
2154#[cfg(feature = "chunking")]
2155pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2156
2157#[cfg(test)]
2158mod tests {
2159 use super::*;
2160
2161 struct WordTok(usize);
2163 impl ChunkTokenizer for WordTok {
2164 fn count_tokens(&self, text: &str) -> usize {
2165 text.split_whitespace().count()
2166 }
2167 fn max_tokens(&self) -> usize {
2168 self.0
2169 }
2170 }
2171
2172 fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2173 let mut d = DoclingDocument::new("t");
2174 for n in nodes {
2175 d.push(n);
2176 }
2177 d
2178 }
2179
2180 #[test]
2181 fn hierarchical_headings_and_items() {
2182 let doc = doc_with(vec![
2183 Node::Heading {
2184 level: 1,
2185 text: "Title".into(),
2186 },
2187 Node::Paragraph {
2188 text: "Intro".into(),
2189 },
2190 Node::Heading {
2191 level: 2,
2192 text: "Sec".into(),
2193 },
2194 Node::Paragraph {
2195 text: "Body".into(),
2196 },
2197 ]);
2198 let chunks = HierarchicalChunker.chunk(&doc);
2199 assert_eq!(chunks.len(), 2);
2200 assert_eq!(chunks[0].text, "Intro");
2201 assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2202 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2203 assert_eq!(
2204 chunks[1].headings.as_deref(),
2205 Some(&["Title".into(), "Sec".into()][..])
2206 );
2207 assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
2208 }
2209
2210 #[test]
2211 fn heading_shadowing_prunes_deeper_levels() {
2212 let doc = doc_with(vec![
2213 Node::Heading {
2214 level: 2,
2215 text: "A".into(),
2216 },
2217 Node::Heading {
2218 level: 3,
2219 text: "A.1".into(),
2220 },
2221 Node::Heading {
2222 level: 2,
2223 text: "B".into(),
2224 },
2225 Node::Paragraph { text: "p".into() },
2226 ]);
2227 let chunks = HierarchicalChunker.chunk(&doc);
2228 assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
2229 }
2230
2231 #[test]
2232 fn triplet_table() {
2233 let t = Table {
2234 rows: vec![
2235 vec!["".into(), "Col1".into()],
2236 vec!["Row1".into(), "v".into()],
2237 ],
2238 ..Default::default()
2239 };
2240 assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
2241 let single = Table {
2244 rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
2245 ..Default::default()
2246 };
2247 assert_eq!(triplet_table_text(&single), "a = b");
2248 }
2249
2250 #[test]
2251 fn hybrid_merges_small_peers_and_splits_large() {
2252 let doc = doc_with(vec![
2253 Node::Heading {
2254 level: 2,
2255 text: "S".into(),
2256 },
2257 Node::Paragraph { text: "a b".into() },
2258 Node::Paragraph { text: "c d".into() },
2259 ]);
2260 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2261 assert_eq!(chunks.len(), 1, "peers under one heading merge");
2262 assert_eq!(chunks[0].text, "a b\nc d");
2263
2264 let long = "w ".repeat(40).trim().to_string();
2265 let doc = doc_with(vec![Node::Paragraph { text: long }]);
2266 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2267 assert!(chunks.len() > 1, "oversized paragraph splits");
2268 for c in &chunks {
2269 assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
2270 }
2271 }
2272
2273 #[test]
2274 fn semchunk_prefers_newlines_then_sentences() {
2275 let tok = WordTok(4);
2276 let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
2277 assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
2278 }
2279}