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