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::Caption { text, .. } => {
486 let self_ref = self.alloc.text();
487 self.emit_inline(text, self_ref);
488 }
489 Node::CheckboxItem { checked, text } => {
490 let self_ref = self.alloc.text();
491 let mark = if *checked { "- [x] " } else { "- [ ] " };
492 let body = format!("{mark}{}", unescape_text(text));
493 self.emit(
494 body.clone(),
495 vec![ChunkItem {
496 self_ref,
497 kind: ChunkItemKind::Text,
498 text: body,
499 }],
500 );
501 }
502 Node::Formula { latex, .. } => {
505 let self_ref = self.alloc.text();
506 let body = format!("$${}$$", latex);
507 self.emit(
508 body.clone(),
509 vec![ChunkItem {
510 self_ref,
511 kind: ChunkItemKind::Text,
512 text: body,
513 }],
514 );
515 }
516 Node::Code { text, .. } => {
517 let self_ref = self.alloc.text();
518 let body = format!("```\n{}\n```", unescape_text(text));
519 self.emit(
520 body.clone(),
521 vec![ChunkItem {
522 self_ref,
523 kind: ChunkItemKind::Text,
524 text: body,
525 }],
526 );
527 }
528 Node::Table(t) => {
529 let self_ref = self.alloc.table();
530 let body = triplet_table_text(t);
531 self.emit(
532 body.clone(),
533 vec![ChunkItem {
534 self_ref,
535 kind: ChunkItemKind::Table,
536 text: body,
537 }],
538 );
539 }
540 Node::Picture { caption, .. } => {
541 let cap = caption.as_deref().filter(|c| !c.is_empty());
542 let cap_item = cap.map(|c| ChunkItem {
543 self_ref: self.alloc.text(),
544 kind: ChunkItemKind::Text,
545 text: unescape_text(c),
546 });
547 self.alloc.picture();
548 if let Some(cap_item) = cap_item {
552 let body = cap_item.text.clone();
553 self.emit(body, vec![cap_item]);
554 }
555 }
556 Node::Chart {
557 kind,
558 table,
559 caption,
560 ..
561 } => {
562 let cap = caption.as_deref().filter(|c| !c.is_empty());
563 let cap_item = cap.map(|c| ChunkItem {
564 self_ref: self.alloc.text(),
565 kind: ChunkItemKind::Text,
566 text: unescape_text(c),
567 });
568 let pic_ref = self.alloc.picture();
569 let mut parts: Vec<String> = Vec::new();
573 if let Some(ci) = &cap_item {
574 parts.push(ci.text.clone());
575 }
576 parts.push(humanize_label(kind));
577 let grid = crate::markdown::render_table(table, false);
578 if !grid.is_empty() {
579 parts.push(unescape_text(&grid));
580 }
581 let body = parts.join("\n\n");
582 let pic_item = ChunkItem {
587 self_ref: pic_ref,
588 kind: ChunkItemKind::Picture,
589 text: body.clone(),
590 };
591 let items = match cap_item {
592 Some(mut ci) => {
593 ci.text = String::new();
594 vec![ci, pic_item]
595 }
596 None => vec![pic_item],
597 };
598 self.emit(body, items);
599 }
600 Node::Group { layer: Some(_), .. } => {}
603 Node::Group { children, .. } => {
604 self.alloc.group();
607 self.walk(children);
608 }
609 Node::FieldRegion { items } => {
610 self.alloc.field_region();
613 for item in items {
614 self.alloc.field_item();
615 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
616 let self_ref = self.alloc.text();
617 let body = unescape_text(part);
618 self.emit(
619 body.clone(),
620 vec![ChunkItem {
621 self_ref,
622 kind: ChunkItemKind::Text,
623 text: body,
624 }],
625 );
626 }
627 }
628 }
629 Node::InlineGroup { md_text, runs, .. } => {
630 let self_ref = self.alloc.text();
631 self.emit_inline_with_runs(md_text, self_ref, runs);
632 }
633 Node::TextDump(text) => {
634 let self_ref = self.alloc.text();
635 let body = unescape_text(text);
636 self.emit(
637 body.clone(),
638 vec![ChunkItem {
639 self_ref,
640 kind: ChunkItemKind::Text,
641 text: body,
642 }],
643 );
644 }
645 Node::Located { inner, .. } | Node::Commented { inner, .. } => self.one(inner),
647 Node::CommentSection { .. }
650 | Node::Furniture { .. }
651 | Node::PageFurniture { .. }
652 | Node::PageBreak
653 | Node::PageInfo { .. }
654 | Node::DoclangOnly(_) => {}
655 Node::ListItem { .. } => self.sibling_lists(std::slice::from_ref(node)),
658 }
659 }
660}
661
662fn level_of(node: &Node) -> u8 {
663 match node {
664 Node::ListItem { level, .. } => *level,
665 _ => 0,
666 }
667}
668
669fn render_list(items: &[Node]) -> String {
672 let mut lines: Vec<String> = Vec::new();
673 for item in items {
674 let Node::ListItem {
675 ordered,
676 number,
677 text,
678 level,
679 layer,
680 ..
681 } = item
682 else {
683 continue;
684 };
685 if layer.is_some() {
686 continue;
687 }
688 let indent = " ".repeat(*level as usize);
689 let marker = if *ordered {
690 format!("{number}.")
691 } else {
692 "-".to_string()
693 };
694 lines.push(format!(
695 "{indent}{marker} {}",
696 unescape_text(&strip_image_markers(text))
697 ));
698 }
699 lines.join("\n")
700}
701
702fn strip_image_markers(text: &str) -> String {
707 if !text.contains("<!-- image -->") {
708 return text.to_string();
709 }
710 let cleaned: Vec<&str> = text
711 .split('\n')
712 .map(str::trim_end)
713 .filter(|l| *l != "<!-- image -->")
714 .collect();
715 cleaned.join("\n").trim_end().to_string()
716}
717
718fn humanize_label(label: &str) -> String {
721 let text = label.replace('_', " ");
722 let mut chars = text.chars();
723 match chars.next() {
724 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
725 None => text,
726 }
727}
728
729fn triplet_table_text(t: &Table) -> String {
736 let rows: Vec<Vec<String>> = t
737 .rows
738 .iter()
739 .enumerate()
740 .map(|(ri, r)| (0..r.len()).map(|ci| cell_chunk_text(t, ri, ci)).collect())
741 .collect();
742 let num_rows = rows.len();
743 let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
744 if num_rows == 0 || num_cols == 0 {
745 return String::new();
746 }
747 let cell = |r: usize, c: usize| -> &str {
748 rows.get(r)
749 .and_then(|row| row.get(c))
750 .map(String::as_str)
751 .unwrap_or("")
752 };
753
754 let num_headers = {
760 let derived;
761 let cells: &[crate::TableCell] = match &t.cells {
762 Some(c) if !c.is_empty() => c,
763 _ => {
764 derived = t.derive_cells();
765 &derived
766 }
767 };
768 (0..num_rows)
769 .take_while(|&r| cells.iter().any(|c| c.column_header && c.start_row == r))
770 .count()
771 };
772
773 let columns: Vec<String> = if num_headers > 0 {
776 (0..num_cols)
777 .map(|c| {
778 let mut name = String::new();
779 for r in 0..num_headers {
780 if !name.is_empty() {
781 name.push('.');
782 }
783 name.push_str(cell(r, c));
784 }
785 name
786 })
787 .collect()
788 } else {
789 (0..num_cols).map(|c| c.to_string()).collect()
790 };
791 let data_rows = num_headers..num_rows;
792 let n_data = data_rows.len();
793
794 if n_data == 0 {
796 return columns
797 .iter()
798 .map(|s| s.trim())
799 .filter(|s| !s.is_empty())
800 .collect::<Vec<_>>()
801 .join(". ");
802 }
803
804 let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
805 let text = if num_cols == 1 {
806 let col_name = data(0, 0).trim().to_string();
809 if n_data == 1 {
810 col_name
811 } else {
812 (1..n_data)
813 .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
814 .collect::<Vec<_>>()
815 .join(". ")
816 }
817 } else {
818 let mut parts = Vec::new();
820 for r in 0..n_data {
821 for (c, col_name) in columns.iter().enumerate().skip(1) {
822 parts.push(format!(
823 "{}, {} = {}",
824 data(r, 0).trim(),
825 col_name.trim(),
826 data(r, c).trim()
827 ));
828 }
829 }
830 parts.join(". ")
831 };
832 if !text.is_empty() {
833 return text;
834 }
835
836 (0..n_data)
839 .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
840 .map(|(r, c)| data(r, c).trim())
841 .filter(|s| !s.is_empty())
842 .collect::<Vec<_>>()
843 .join(". ")
844}
845
846fn inline_segments(md: &str) -> Vec<String> {
854 inline_segments_tagged(md)
855 .into_iter()
856 .map(|(t, _)| t)
857 .collect()
858}
859
860fn inline_segments_tagged(md: &str) -> Vec<(String, bool)> {
864 let chars: Vec<char> = md.chars().collect();
865 let n = chars.len();
866 let find = |from: usize, pat: &str| -> Option<usize> {
867 let hay: String = chars[from..].iter().collect();
868 hay.find(pat).map(|p| from + hay[..p].chars().count())
869 };
870 let mut out: Vec<(String, bool)> = Vec::new();
871 let mut plain = String::new();
872 let mut after_span = false;
873
874 fn flush(
875 out: &mut Vec<(String, bool)>,
876 plain: &mut String,
877 before_span: bool,
878 after_span: bool,
879 ) {
880 let mut p = std::mem::take(plain);
881 if after_span {
882 if let Some(rest) = p.strip_prefix(' ') {
883 p = rest.to_string();
884 }
885 }
886 if before_span {
887 if let Some(rest) = p.strip_suffix(' ') {
888 p = rest.to_string();
889 }
890 }
891 if !p.is_empty() {
892 out.push((unescape_text(&p), true));
893 }
894 }
895
896 let mut i = 0;
897 while i < n {
898 let rest: String = chars[i..].iter().collect();
899 if chars[i] == '[' && !rest.starts_with("[](") {
903 let balanced = |c: usize| {
907 let mut d = 0i32;
908 for &ch in &chars[i + 1..c] {
909 match ch {
910 '[' => d += 1,
911 ']' => d -= 1,
912 _ => {}
913 }
914 }
915 d == 0
916 };
917 if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
918 let mut depth = 0usize;
919 let mut url_end = None;
920 for (k, &c) in chars.iter().enumerate().skip(close + 2) {
921 match c {
922 '(' => depth += 1,
923 ')' => {
924 if depth == 0 {
925 url_end = Some(k);
926 break;
927 }
928 depth -= 1;
929 }
930 _ => {}
931 }
932 }
933 if let Some(endp) = url_end {
934 flush(&mut out, &mut plain, true, after_span);
935 out.push((
936 unescape_text(&chars[i..=endp].iter().collect::<String>()),
937 false,
938 ));
939 i = endp + 1;
940 after_span = true;
941 continue;
942 }
943 }
944 }
945 let mut matched = false;
948 for marker in ["***", "**", "*", "~~", "`"] {
949 if rest.starts_with(marker) {
950 let mlen = marker.chars().count();
951 if let Some(end) = find(i + mlen, marker) {
952 let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
956 if end > i + mlen && !inner_blank {
957 flush(&mut out, &mut plain, true, after_span);
958 if marker == "`" {
959 let inner: String = chars[i + 1..end].iter().collect();
960 out.push((format!("```\n{}\n```", unescape_text(&inner)), false));
961 } else {
962 out.push((
963 unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
964 false,
965 ));
966 }
967 i = end + mlen;
968 after_span = true;
969 matched = true;
970 }
971 }
972 break;
973 }
974 }
975 if matched {
976 continue;
977 }
978 if rest.starts_with("$$") {
981 plain.push_str("$$");
982 i += 2;
983 continue;
984 }
985 if chars[i] == '$' {
987 if let Some(end) = find(i + 1, "$") {
988 if end > i + 1 {
989 flush(&mut out, &mut plain, true, after_span);
990 let latex: String = chars[i + 1..end].iter().collect();
991 out.push((format!("$${latex}$$"), false));
992 i = end + 1;
993 after_span = true;
994 continue;
995 }
996 }
997 }
998 plain.push(chars[i]);
999 i += 1;
1000 }
1001 flush(&mut out, &mut plain, false, after_span);
1002 if out.is_empty() {
1003 out.push((unescape_text(md), true));
1004 }
1005 out
1006}
1007
1008fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1013 let target = segment.trim();
1014 if target.is_empty() {
1015 return None;
1016 }
1017 let plainish =
1018 |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1019 let fully_plain =
1020 |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1021 let unmarked: Vec<(&str, bool)> = runs
1022 .iter()
1023 .filter(|r| plainish(r))
1024 .map(|r| (r.text.as_str(), fully_plain(r)))
1025 .collect();
1026 for start in 0..unmarked.len() {
1027 let mut rest = target;
1028 let mut taken: Vec<(String, bool)> = Vec::new();
1029 for (t, fully) in &unmarked[start..] {
1030 let t = t.trim();
1031 if t.is_empty() {
1032 continue;
1033 }
1034 match rest.strip_prefix(t) {
1035 Some(r) => {
1036 taken.push((unescape_text(t), *fully));
1037 rest = r.trim_start();
1038 if rest.is_empty() {
1039 break;
1040 }
1041 }
1042 None => break,
1043 }
1044 }
1045 if rest.is_empty() && taken.len() >= 2 {
1046 let mut merged: Vec<(String, bool)> = Vec::new();
1051 for (t, fully) in taken {
1052 match merged.last_mut() {
1053 Some((last, true)) if fully => {
1054 last.push(' ');
1055 last.push_str(&t);
1056 }
1057 _ => merged.push((t, fully)),
1058 }
1059 }
1060 if merged.len() >= 2 {
1061 return Some(merged.into_iter().map(|(t, _)| t).collect());
1062 }
1063 return None;
1064 }
1065 }
1066 None
1067}
1068
1069fn cell_chunk_text(t: &Table, r: usize, c: usize) -> String {
1076 if let Some(blocks) = t
1077 .cell_blocks
1078 .as_ref()
1079 .and_then(|b| b.get(r))
1080 .and_then(|row| row.get(c))
1081 .filter(|b| !b.is_empty())
1082 {
1083 let mut parts: Vec<String> = Vec::new();
1084 for node in blocks.iter() {
1085 let part = block_chunk_text(node);
1086 if !part.is_empty() {
1087 parts.push(part);
1088 }
1089 }
1090 return parts.join("\n\n");
1091 }
1092 let flat = t
1093 .rows
1094 .get(r)
1095 .and_then(|row| row.get(c))
1096 .map(String::as_str)
1097 .unwrap_or("");
1098 unescape_text(flat)
1099 .replace("<!-- image -->", "")
1100 .trim()
1101 .to_string()
1102}
1103
1104fn block_chunk_text(node: &Node) -> String {
1106 match node {
1107 Node::Paragraph { text } => unescape_text(text),
1108 Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1109 Node::Code { text, .. } => format!("```\n{}\n```", unescape_text(text)),
1110 Node::Table(inner) => triplet_table_text(inner),
1111 Node::Picture { caption, .. } => caption
1112 .as_deref()
1113 .filter(|c| !c.is_empty())
1114 .map(unescape_text)
1115 .unwrap_or_default(),
1116 Node::ListItem {
1117 ordered,
1118 number,
1119 text,
1120 ..
1121 } => {
1122 let marker = if *ordered {
1123 format!("{number}.")
1124 } else {
1125 "-".to_string()
1126 };
1127 format!("{marker} {}", unescape_text(text))
1128 }
1129 Node::CheckboxItem { checked, text } => {
1130 let mark = if *checked { "- [x] " } else { "- [ ] " };
1131 format!("{mark}{}", unescape_text(text))
1132 }
1133 Node::Heading { text, .. } => unescape_text(text),
1134 Node::Located { inner, .. } | Node::Commented { inner, .. } => block_chunk_text(inner),
1135 Node::Group { layer: Some(_), .. } => String::new(),
1136 Node::Group { children, .. } => children
1137 .iter()
1138 .map(block_chunk_text)
1139 .filter(|s| !s.is_empty())
1140 .collect::<Vec<_>>()
1141 .join("\n"),
1142 _ => String::new(),
1143 }
1144}
1145
1146fn unescape_text(s: &str) -> String {
1149 s.replace("<", "<")
1150 .replace(">", ">")
1151 .replace("&", "&")
1152 .replace("\\_", "_")
1153}
1154
1155pub trait ChunkTokenizer {
1161 fn count_tokens(&self, text: &str) -> usize;
1163 fn max_tokens(&self) -> usize;
1165}
1166
1167pub struct HybridChunker<T: ChunkTokenizer> {
1171 tokenizer: T,
1172 merge_peers: bool,
1173}
1174
1175impl<T: ChunkTokenizer> HybridChunker<T> {
1176 pub fn new(tokenizer: T) -> Self {
1177 Self {
1178 tokenizer,
1179 merge_peers: true,
1180 }
1181 }
1182
1183 pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1185 self.merge_peers = merge_peers;
1186 self
1187 }
1188
1189 pub fn max_tokens(&self) -> usize {
1190 self.tokenizer.max_tokens()
1191 }
1192
1193 pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1195 let mut chunks = Vec::new();
1196 self.chunk_with(doc, &mut |c| {
1197 chunks.push(c);
1198 true
1199 });
1200 chunks
1201 }
1202
1203 pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1210 let mut merger = PeerMerger::default();
1211 let mut alive = true;
1212 HierarchicalChunker.chunk_with(doc, &mut |c| {
1213 for split in self.split_by_doc_items(c) {
1214 for chunk in self.split_using_plain_text(split) {
1215 if !alive {
1216 return false;
1217 }
1218 alive = if self.merge_peers {
1219 self.merge_push(&mut merger, chunk, sink)
1220 } else {
1221 sink(chunk)
1222 };
1223 }
1224 }
1225 alive
1226 });
1227 if alive {
1228 self.merge_flush(&mut merger, sink);
1229 }
1230 }
1231
1232 fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1233 self.tokenizer.count_tokens(&contextualize(chunk))
1234 }
1235
1236 fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1239 let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1240 let text = if chunk.doc_items.len() == 1 {
1241 chunk.text.clone()
1242 } else {
1243 doc_items
1244 .iter()
1245 .filter(|it| !it.text.is_empty())
1246 .map(|it| it.text.as_str())
1247 .collect::<Vec<_>>()
1248 .join("\n")
1249 };
1250 DocChunk {
1251 text,
1252 headings: chunk.headings.clone(),
1253 doc_items,
1254 }
1255 }
1256
1257 fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1258 if chunk.doc_items.is_empty() {
1259 return vec![chunk];
1260 }
1261 let max = self.max_tokens();
1262 let num_items = chunk.doc_items.len();
1263 let mut chunks = Vec::new();
1264 let mut window_start = 0usize;
1265 let mut window_end = 0usize; while window_end < num_items {
1267 let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1268 if self.count_chunk_tokens(&new_chunk) <= max {
1269 if window_end < num_items - 1 {
1270 window_end += 1;
1271 continue;
1272 } else {
1273 window_end = num_items; }
1275 } else if window_start == window_end {
1276 window_end += 1;
1279 window_start = window_end;
1280 } else {
1281 new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1284 window_start = window_end;
1285 }
1286 chunks.push(new_chunk);
1287 }
1288 chunks
1289 }
1290
1291 fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1292 let total = self.count_chunk_tokens(&chunk);
1293 let max = self.max_tokens();
1294 if total <= max {
1295 return vec![chunk];
1296 }
1297 let text_len = self.tokenizer.count_tokens(&chunk.text);
1298 let other_len = total - text_len;
1299 if other_len >= max {
1300 let stripped = DocChunk {
1302 headings: None,
1303 ..chunk
1304 };
1305 return self.split_using_plain_text(stripped);
1306 }
1307 let available = max - other_len;
1308
1309 let segments =
1310 if chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table {
1311 let lines: Vec<String> = chunk
1318 .text
1319 .split('\n')
1320 .filter(|l| !l.trim().is_empty())
1321 .map(|l| l.to_string())
1322 .collect();
1323 line_chunk_text(&lines, &self.tokenizer, max)
1324 } else {
1325 semchunk(&chunk.text, available, &self.tokenizer)
1326 };
1327 segments
1328 .into_iter()
1329 .map(|s| DocChunk {
1330 text: s,
1331 headings: chunk.headings.clone(),
1332 doc_items: chunk.doc_items.clone(),
1333 })
1334 .collect()
1335 }
1336
1337 fn merge_push(
1343 &self,
1344 m: &mut PeerMerger,
1345 chunk: DocChunk,
1346 sink: &mut dyn FnMut(DocChunk) -> bool,
1347 ) -> bool {
1348 if m.window.is_empty() {
1349 m.window.push(chunk);
1350 return true;
1351 }
1352 let candidate = DocChunk {
1353 text: m
1354 .window
1355 .iter()
1356 .map(|c| c.text.as_str())
1357 .chain([chunk.text.as_str()])
1358 .collect::<Vec<_>>()
1359 .join("\n"),
1360 headings: m.window[0].headings.clone(),
1361 doc_items: m
1362 .window
1363 .iter()
1364 .flat_map(|c| c.doc_items.iter().cloned())
1365 .chain(chunk.doc_items.iter().cloned())
1366 .collect(),
1367 };
1368 if chunk.headings == m.window[0].headings
1369 && self.count_chunk_tokens(&candidate) <= self.max_tokens()
1370 {
1371 m.window.push(chunk);
1372 m.merged = Some(candidate);
1373 true
1374 } else {
1375 let alive = self.merge_flush(m, sink);
1376 m.window.push(chunk);
1377 alive
1378 }
1379 }
1380
1381 fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
1385 let alive = if m.window.len() == 1 {
1386 sink(m.window.pop().expect("single-chunk window"))
1387 } else if !m.window.is_empty() {
1388 m.window.clear();
1389 sink(m.merged.take().expect("multi-chunk window has a merge"))
1390 } else {
1391 true
1392 };
1393 m.merged = None;
1394 alive
1395 }
1396}
1397
1398#[derive(Default)]
1400struct PeerMerger {
1401 window: Vec<DocChunk>,
1402 merged: Option<DocChunk>,
1403}
1404
1405fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
1415 let mut chunks: Vec<String> = Vec::new();
1416 let mut current = String::new();
1417 let mut current_len = 0usize;
1418
1419 for line in lines {
1420 let mut remaining: Vec<char> = line.chars().collect();
1421 loop {
1422 let rem_str: String = remaining.iter().collect();
1423 let line_tokens = tok.count_tokens(&rem_str);
1424 let available = max_tokens.saturating_sub(current_len);
1425
1426 if line_tokens <= available {
1427 current.push_str(&rem_str);
1428 current_len += line_tokens;
1429 break;
1430 }
1431 if line_tokens <= max_tokens {
1432 chunks.push(std::mem::take(&mut current));
1433 current_len = 0;
1434 continue;
1435 }
1436 let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
1438 let mut rest = rest;
1439 if take.is_empty() {
1440 if rest.is_empty() {
1441 break;
1442 }
1443 take = rest[..1].iter().collect();
1444 rest = rest[1..].to_vec();
1445 }
1446 current.push('\n');
1447 current.push_str(&take);
1448 chunks.push(std::mem::take(&mut current));
1449 current_len = 0;
1450 remaining = rest;
1451 }
1452 }
1453 if !current.is_empty() {
1454 chunks.push(current);
1455 }
1456 chunks
1457}
1458
1459fn split_by_token_limit<T: ChunkTokenizer>(
1463 text: &[char],
1464 token_limit: usize,
1465 tok: &T,
1466) -> (String, Vec<char>) {
1467 if token_limit == 0 || text.is_empty() {
1468 return (String::new(), text.to_vec());
1469 }
1470 let full: String = text.iter().collect();
1471 if tok.count_tokens(&full) <= token_limit {
1472 return (full, Vec::new());
1473 }
1474 let (mut lo, mut hi) = (0usize, text.len());
1475 let mut best: Option<usize> = None;
1476 while lo <= hi {
1477 let mid = (lo + hi) / 2;
1478 let head: String = text[..mid].iter().collect();
1479 if tok.count_tokens(&head) <= token_limit {
1480 best = Some(mid);
1481 lo = mid + 1;
1482 } else {
1483 if mid == 0 {
1484 break;
1485 }
1486 hi = mid - 1;
1487 }
1488 }
1489 let mut best_idx = match best {
1490 Some(b) if b > 0 => b,
1491 _ => return (String::new(), text.to_vec()),
1492 };
1493 if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
1495 if pos > 0 {
1496 best_idx = pos;
1497 }
1498 }
1499 (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
1500}
1501
1502const NON_WS_SPLITTERS: &[&str] = &[
1508 ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
1509 "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
1510];
1511
1512pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
1516 let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
1517 let mut counter = |s: &str| -> usize {
1518 if let Some(n) = cache.get(s) {
1519 return *n;
1520 }
1521 let n = tok.count_tokens(s);
1522 cache.insert(s.to_string(), n);
1523 n
1524 };
1525 let chunks = semchunk_rec(text, chunk_size, &mut counter);
1526 chunks
1528 .into_iter()
1529 .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
1530 .collect()
1531}
1532
1533fn semchunk_rec(
1536 text: &str,
1537 chunk_size: usize,
1538 counter: &mut dyn FnMut(&str) -> usize,
1539) -> Vec<String> {
1540 let (splitter, splitter_is_ws, splits) = split_text(text);
1541
1542 let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
1543 let mut cum_lens = Vec::with_capacity(splits.len() + 1);
1544 cum_lens.push(0usize);
1545 for l in &split_lens {
1546 cum_lens.push(cum_lens.last().unwrap() + l);
1547 }
1548 let num_splits_plus_one = splits.len() + 1;
1549
1550 let mut chunks: Vec<String> = Vec::new();
1551 let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
1552
1553 for i in 0..splits.len() {
1554 if skips.contains(&i) {
1555 continue;
1556 }
1557 let split = &splits[i];
1558 if counter(split) > chunk_size {
1559 let inner = semchunk_rec(split, chunk_size, counter);
1560 chunks.extend(inner);
1561 } else {
1562 let (end, merged) = merge_splits(
1563 &splits,
1564 &cum_lens,
1565 chunk_size,
1566 &splitter,
1567 counter,
1568 i,
1569 num_splits_plus_one,
1570 );
1571 for j in (i + 1)..end {
1572 skips.insert(j);
1573 }
1574 chunks.push(merged);
1575 }
1576 let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
1579 if !splitter_is_ws && !is_last {
1580 let with_splitter = format!(
1581 "{}{}",
1582 chunks.last().map(String::as_str).unwrap_or(""),
1583 splitter
1584 );
1585 if counter(&with_splitter) <= chunk_size {
1586 if let Some(last) = chunks.last_mut() {
1587 *last = with_splitter;
1588 } else {
1589 chunks.push(with_splitter);
1590 }
1591 } else {
1592 chunks.push(splitter.clone());
1593 }
1594 }
1595 }
1596 chunks
1597}
1598
1599fn merge_splits(
1602 splits: &[String],
1603 cum_lens: &[usize],
1604 chunk_size: usize,
1605 splitter: &str,
1606 counter: &mut dyn FnMut(&str) -> usize,
1607 start: usize,
1608 high_init: usize,
1609) -> (usize, String) {
1610 let mut average = 0.2f64;
1611 let mut low = start;
1612 let mut high = high_init;
1613 let offset = cum_lens[start];
1614 let mut target = offset as f64 + (chunk_size as f64 * average);
1615
1616 while low < high {
1617 let i = bisect_left(cum_lens, target, low, high);
1618 let midpoint = i.min(high - 1);
1619 let joined = splits[start..midpoint.max(start)].join(splitter);
1620 let tokens = counter(&joined);
1621 let local_cum = cum_lens[midpoint] - offset;
1622 if local_cum > 0 && tokens > 0 {
1623 average = local_cum as f64 / tokens as f64;
1624 target = offset as f64 + (chunk_size as f64 * average);
1625 }
1626 if tokens > chunk_size {
1627 high = midpoint;
1628 } else {
1629 low = midpoint + 1;
1630 }
1631 }
1632 let end = low - 1;
1633 (end, splits[start..end.max(start)].join(splitter))
1634}
1635
1636fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
1637 while low < high {
1638 let mid = (low + high) / 2;
1639 if (sorted[mid] as f64) < target {
1640 low = mid + 1;
1641 } else {
1642 high = mid;
1643 }
1644 }
1645 low
1646}
1647
1648fn split_text(text: &str) -> (String, bool, Vec<String>) {
1650 if text.contains('\n') || text.contains('\r') {
1652 let splitter = longest_run(text, |c| c == '\n' || c == '\r');
1653 return (splitter.clone(), true, split_on(text, &splitter));
1654 }
1655 if text.contains('\t') {
1657 let splitter = longest_run(text, |c| c == '\t');
1658 return (splitter.clone(), true, split_on(text, &splitter));
1659 }
1660 if text.chars().any(char::is_whitespace) {
1662 let splitter = longest_run(text, char::is_whitespace);
1663 if splitter.chars().count() == 1 {
1664 for preceder in NON_WS_SPLITTERS {
1666 if let Some((ws, parts)) = split_after_preceder(text, preceder) {
1667 return (ws, true, parts);
1668 }
1669 }
1670 }
1671 return (splitter.clone(), true, split_on(text, &splitter));
1672 }
1673 for s in NON_WS_SPLITTERS {
1675 if text.contains(s) {
1676 return (s.to_string(), false, split_on(text, s));
1677 }
1678 }
1679 (
1681 String::new(),
1682 true,
1683 text.chars().map(|c| c.to_string()).collect(),
1684 )
1685}
1686
1687fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
1689 let mut best = String::new();
1690 let mut cur = String::new();
1691 for c in text.chars() {
1692 if pred(c) {
1693 cur.push(c);
1694 } else {
1695 if cur.chars().count() > best.chars().count() {
1696 best = cur.clone();
1697 }
1698 cur.clear();
1699 }
1700 }
1701 if cur.chars().count() > best.chars().count() {
1702 best = cur;
1703 }
1704 best
1705}
1706
1707fn split_on(text: &str, splitter: &str) -> Vec<String> {
1708 text.split(splitter).map(str::to_string).collect()
1709}
1710
1711fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
1715 let chars: Vec<char> = text.chars().collect();
1716 let p: Vec<char> = preceder.chars().collect();
1717 let mut ws: Option<char> = None;
1718 for i in p.len()..chars.len() {
1719 if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
1720 ws = Some(chars[i]);
1721 break;
1722 }
1723 }
1724 let ws = ws?;
1725 let mut parts = Vec::new();
1726 let mut cur = String::new();
1727 let mut i = 0usize;
1728 while i < chars.len() {
1729 if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
1730 parts.push(std::mem::take(&mut cur));
1731 i += 1;
1732 continue;
1733 }
1734 cur.push(chars[i]);
1735 i += 1;
1736 }
1737 parts.push(cur);
1738 Some((ws.to_string(), parts))
1739}
1740
1741#[cfg(feature = "chunking")]
1746mod hf {
1747 use super::ChunkTokenizer;
1748
1749 pub const DEFAULT_TOKENIZER_PATH: &str = ".models/chunk/tokenizer.json";
1754
1755 pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
1760 if let Some(p) = explicit {
1761 return Ok(p.to_string());
1762 }
1763 let resolved = crate::assets::resolve(DEFAULT_TOKENIZER_PATH);
1764 if std::path::Path::new(&resolved).exists() {
1765 return Ok(resolved);
1766 }
1767 Err(format!(
1768 "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
1769 {DEFAULT_TOKENIZER_PATH} does not exist — run \
1770 scripts/install/download_dependencies.sh (or pass an explicit path)"
1771 ))
1772 }
1773
1774 pub struct HuggingFaceTokenizer {
1778 tok: tokenizers::Tokenizer,
1779 max_tokens: usize,
1780 }
1781
1782 impl HuggingFaceTokenizer {
1783 pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
1787 Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
1788 }
1789
1790 pub fn from_file(
1794 path: impl AsRef<std::path::Path>,
1795 max_tokens: usize,
1796 ) -> Result<Self, String> {
1797 let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
1798 .map_err(|e| format!("failed to load tokenizer: {e}"))?;
1799 let _ = tok.with_truncation(None);
1804 tok.with_padding(None);
1805 Ok(Self { tok, max_tokens })
1806 }
1807 }
1808
1809 impl ChunkTokenizer for HuggingFaceTokenizer {
1810 fn count_tokens(&self, text: &str) -> usize {
1811 self.tok
1812 .encode(text, false)
1813 .map(|e| e.get_tokens().len())
1814 .unwrap_or(0)
1815 }
1816 fn max_tokens(&self) -> usize {
1817 self.max_tokens
1818 }
1819 }
1820}
1821
1822#[cfg(feature = "chunking")]
1823pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
1824
1825#[cfg(feature = "chunking")]
1830mod window {
1831 use super::DocChunk;
1832 use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
1833
1834 #[derive(Debug, Clone, Default)]
1836 pub struct Section {
1837 pub heading_path: Vec<String>,
1840 pub words: Vec<String>,
1842 }
1843
1844 impl Section {
1845 pub fn heading_context(&self) -> String {
1848 if self.heading_path.is_empty() {
1849 String::new()
1850 } else {
1851 format!("# {}", self.heading_path.join(" > "))
1852 }
1853 }
1854 }
1855
1856 fn level_index(level: HeadingLevel) -> usize {
1857 match level {
1858 HeadingLevel::H1 => 1,
1859 HeadingLevel::H2 => 2,
1860 HeadingLevel::H3 => 3,
1861 HeadingLevel::H4 => 4,
1862 HeadingLevel::H5 => 5,
1863 HeadingLevel::H6 => 6,
1864 }
1865 }
1866
1867 pub fn parse_sections(markdown: &str) -> Vec<Section> {
1871 parse_sections_with_stack(markdown, Vec::new()).0
1872 }
1873
1874 pub fn parse_sections_with_stack(
1879 markdown: &str,
1880 initial_stack: Vec<String>,
1881 ) -> (Vec<Section>, Vec<String>) {
1882 let mut heading_stack: Vec<String> = initial_stack;
1883 let mut sections: Vec<Section> = Vec::new();
1884 let mut current = Section {
1887 heading_path: heading_stack
1888 .iter()
1889 .filter(|h| !h.is_empty())
1890 .cloned()
1891 .collect(),
1892 words: Vec::new(),
1893 };
1894
1895 let mut in_heading = false;
1896 let mut heading_level = 0usize;
1897 let mut heading_buf = String::new();
1898
1899 let push_words = |section: &mut Section, text: &str| {
1900 for w in text.split_whitespace() {
1901 section.words.push(w.to_string());
1902 }
1903 };
1904
1905 let flush = |sections: &mut Vec<Section>, section: &mut Section| {
1906 if !section.words.is_empty() {
1907 sections.push(std::mem::take(section));
1908 } else {
1909 *section = Section::default();
1910 }
1911 };
1912
1913 for event in Parser::new(markdown) {
1914 match event {
1915 Event::Start(Tag::Heading { level, .. }) => {
1916 in_heading = true;
1917 heading_level = level_index(level);
1918 heading_buf.clear();
1919 }
1920 Event::End(TagEnd::Heading(_)) => {
1921 in_heading = false;
1922 let idx = heading_level.saturating_sub(1);
1924 if heading_stack.len() <= idx {
1925 heading_stack.resize(idx + 1, String::new());
1926 } else {
1927 heading_stack.truncate(idx + 1);
1928 }
1929 heading_stack[idx] = heading_buf.trim().to_string();
1930 flush(&mut sections, &mut current);
1932 current.heading_path = heading_stack
1933 .iter()
1934 .filter(|h| !h.is_empty())
1935 .cloned()
1936 .collect();
1937 }
1938 Event::Text(t) | Event::Code(t) => {
1939 if in_heading {
1940 if !heading_buf.is_empty() {
1941 heading_buf.push(' ');
1942 }
1943 heading_buf.push_str(&t);
1944 } else {
1945 push_words(&mut current, &t);
1946 }
1947 }
1948 Event::SoftBreak | Event::HardBreak | Event::Rule => {}
1950 _ => {}
1951 }
1952 }
1953 flush(&mut sections, &mut current);
1954 (sections, heading_stack)
1955 }
1956
1957 #[derive(Debug, Clone)]
1963 pub struct WindowChunker {
1964 pub max_words: usize,
1966 pub overlap: f32,
1968 }
1969
1970 impl Default for WindowChunker {
1971 fn default() -> Self {
1972 WindowChunker {
1973 max_words: 300,
1974 overlap: 0.05,
1975 }
1976 }
1977 }
1978
1979 impl WindowChunker {
1980 pub fn new(max_words: usize, overlap: f32) -> Self {
1981 WindowChunker { max_words, overlap }
1982 }
1983
1984 fn word_budget(&self) -> usize {
1986 self.max_words.max(1)
1987 }
1988
1989 fn overlap_words(&self, budget: usize) -> usize {
1992 let o = (budget as f32 * self.overlap).round() as usize;
1993 o.min(budget.saturating_sub(1))
1994 }
1995
1996 pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
1998 let mut chunks = Vec::new();
1999 self.chunk_with(markdown, &mut |c| {
2000 chunks.push(c);
2001 true
2002 });
2003 chunks
2004 }
2005
2006 pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2010 let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2011 for section in §ions {
2012 if !self.pack_section(section, sink) {
2013 return;
2014 }
2015 }
2016 }
2017
2018 pub fn pack_section(
2022 &self,
2023 section: &Section,
2024 sink: &mut dyn FnMut(DocChunk) -> bool,
2025 ) -> bool {
2026 let words = §ion.words;
2027 if words.is_empty() {
2028 return true;
2029 }
2030 let budget = self.word_budget();
2031 let step = budget - self.overlap_words(budget); let mut start = 0;
2033 loop {
2034 let end = (start + budget).min(words.len());
2035 let chunk = DocChunk {
2036 text: words[start..end].join(" "),
2037 headings: (!section.heading_path.is_empty())
2038 .then(|| section.heading_path.clone()),
2039 doc_items: Vec::new(),
2040 };
2041 if !sink(chunk) {
2042 return false;
2043 }
2044 if end >= words.len() {
2045 return true;
2046 }
2047 start += step;
2048 }
2049 }
2050
2051 pub fn contextualize(chunk: &DocChunk) -> String {
2057 match &chunk.headings {
2058 Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2059 _ => chunk.text.clone(),
2060 }
2061 }
2062 }
2063
2064 #[cfg(test)]
2065 mod tests {
2066 use super::*;
2067
2068 #[test]
2069 fn splits_on_headings_and_tracks_path() {
2070 let md = "\
2071intro words
2072# Chapter 1
2073para one
2074## Section 1.1
2075para two
2076# Chapter 2
2077para three";
2078 let secs = parse_sections(md);
2079 assert_eq!(secs.len(), 4);
2081 assert!(secs[0].heading_path.is_empty());
2082 assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2083 assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2084 assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2086 }
2087
2088 #[test]
2089 fn strips_markup_to_plain_words() {
2090 let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2091 let secs = parse_sections(md);
2092 let words = &secs[0].words;
2093 assert!(words.contains(&"bold".to_string()));
2094 assert!(words.contains(&"code".to_string()));
2095 assert!(words.contains(&"link".to_string()));
2096 assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2098 }
2099
2100 #[test]
2101 fn windows_overlap_and_never_cross_headings() {
2102 let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2103 let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2104 let chunker = WindowChunker::new(10, 0.2); let chunks = chunker.chunk(&md);
2106 let a: Vec<_> = chunks
2108 .iter()
2109 .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2110 .collect();
2111 assert_eq!(a.len(), 3);
2112 assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2113 assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2114 assert!(a[2].text.ends_with(" w24"));
2115 let b: Vec<_> = chunks
2117 .iter()
2118 .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2119 .collect();
2120 assert_eq!(b.len(), 1);
2121 assert_eq!(b[0].text, "short tail");
2122 assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2123 }
2124
2125 #[test]
2126 fn sink_false_cancels_the_window_walk() {
2127 let md = format!(
2128 "# A\n\n{}\n",
2129 (0..50)
2130 .map(|i| format!("w{i}"))
2131 .collect::<Vec<_>>()
2132 .join(" ")
2133 );
2134 let chunker = WindowChunker::new(10, 0.0);
2135 let mut n = 0;
2136 chunker.chunk_with(&md, &mut |_| {
2137 n += 1;
2138 false
2139 });
2140 assert_eq!(n, 1);
2141 }
2142 }
2143}
2144
2145#[cfg(feature = "chunking")]
2146pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2147
2148#[cfg(test)]
2149mod tests {
2150 use super::*;
2151
2152 struct WordTok(usize);
2154 impl ChunkTokenizer for WordTok {
2155 fn count_tokens(&self, text: &str) -> usize {
2156 text.split_whitespace().count()
2157 }
2158 fn max_tokens(&self) -> usize {
2159 self.0
2160 }
2161 }
2162
2163 fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2164 let mut d = DoclingDocument::new("t");
2165 for n in nodes {
2166 d.push(n);
2167 }
2168 d
2169 }
2170
2171 #[test]
2172 fn hierarchical_headings_and_items() {
2173 let doc = doc_with(vec![
2174 Node::Heading {
2175 level: 1,
2176 text: "Title".into(),
2177 },
2178 Node::Paragraph {
2179 text: "Intro".into(),
2180 },
2181 Node::Heading {
2182 level: 2,
2183 text: "Sec".into(),
2184 },
2185 Node::Paragraph {
2186 text: "Body".into(),
2187 },
2188 ]);
2189 let chunks = HierarchicalChunker.chunk(&doc);
2190 assert_eq!(chunks.len(), 2);
2191 assert_eq!(chunks[0].text, "Intro");
2192 assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2193 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2194 assert_eq!(
2195 chunks[1].headings.as_deref(),
2196 Some(&["Title".into(), "Sec".into()][..])
2197 );
2198 assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
2199 }
2200
2201 #[test]
2202 fn heading_shadowing_prunes_deeper_levels() {
2203 let doc = doc_with(vec![
2204 Node::Heading {
2205 level: 2,
2206 text: "A".into(),
2207 },
2208 Node::Heading {
2209 level: 3,
2210 text: "A.1".into(),
2211 },
2212 Node::Heading {
2213 level: 2,
2214 text: "B".into(),
2215 },
2216 Node::Paragraph { text: "p".into() },
2217 ]);
2218 let chunks = HierarchicalChunker.chunk(&doc);
2219 assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
2220 }
2221
2222 #[test]
2223 fn triplet_table() {
2224 let t = Table {
2225 rows: vec![
2226 vec!["".into(), "Col1".into()],
2227 vec!["Row1".into(), "v".into()],
2228 ],
2229 ..Default::default()
2230 };
2231 assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
2232 let single = Table {
2235 rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
2236 ..Default::default()
2237 };
2238 assert_eq!(triplet_table_text(&single), "a = b");
2239 }
2240
2241 #[test]
2242 fn hybrid_merges_small_peers_and_splits_large() {
2243 let doc = doc_with(vec![
2244 Node::Heading {
2245 level: 2,
2246 text: "S".into(),
2247 },
2248 Node::Paragraph { text: "a b".into() },
2249 Node::Paragraph { text: "c d".into() },
2250 ]);
2251 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2252 assert_eq!(chunks.len(), 1, "peers under one heading merge");
2253 assert_eq!(chunks[0].text, "a b\nc d");
2254
2255 let long = "w ".repeat(40).trim().to_string();
2256 let doc = doc_with(vec![Node::Paragraph { text: long }]);
2257 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2258 assert!(chunks.len() > 1, "oversized paragraph splits");
2259 for c in &chunks {
2260 assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
2261 }
2262 }
2263
2264 #[test]
2265 fn semchunk_prefers_newlines_then_sentences() {
2266 let tok = WordTok(4);
2267 let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
2268 assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
2269 }
2270}