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