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 for k in 0..run.len() {
273 let Node::ListItem {
274 first_in_list,
275 level,
276 ..
277 } = &run[k]
278 else {
279 continue;
280 };
281 if *level != base {
282 continue; }
284 if k > seg && *first_in_list {
286 self.list(&run[seg..k]);
287 seg = k;
288 }
289 }
290 self.list(&run[seg..]);
291 }
292
293 fn list(&mut self, items: &[Node]) {
297 self.alloc.group();
298 let mut chunk_items = Vec::new();
299 self.list_refs(items, &mut chunk_items);
300 let text = render_list(items);
301 self.emit(text, chunk_items);
302 }
303
304 fn list_refs(&mut self, items: &[Node], out: &mut Vec<ChunkItem>) {
308 let base = level_of(&items[0]);
309 let mut i = 0;
310 while i < items.len() {
311 let Node::ListItem {
312 ordered,
313 number,
314 text,
315 level,
316 layer,
317 ..
318 } = &items[i]
319 else {
320 i += 1;
321 continue;
322 };
323 if *level > base {
324 i += 1;
325 continue;
326 }
327 let item_ref = self.alloc.text();
328 let mut j = i + 1;
329 while j < items.len() && level_of(&items[j]) > base {
330 j += 1;
331 }
332 let has_nested = j > i + 1;
333 if layer.is_none() {
334 let marker = if *ordered {
335 format!("{number}.")
336 } else {
337 "-".to_string()
338 };
339 let has_pics = text.contains("<!-- image -->");
353 let text = strip_image_markers(text);
354 let text = text.as_str();
355 let segments = inline_segments(text);
356 if (has_nested || has_pics) && segments.len() > 1 && text.contains("](") {
357 out.push(ChunkItem {
358 self_ref: item_ref.clone(),
359 kind: ChunkItemKind::Text,
360 text: format!("{marker} "),
361 });
362 for seg in segments {
363 out.push(ChunkItem {
364 self_ref: item_ref.clone(),
365 kind: ChunkItemKind::Text,
366 text: seg,
367 });
368 }
369 } else {
370 out.push(ChunkItem {
371 self_ref: item_ref.clone(),
372 kind: ChunkItemKind::Text,
373 text: format!("{marker} {}", unescape_text(text)),
374 });
375 }
376 }
377 if j > i + 1 {
380 self.nested_sibling_lists(&items[i + 1..j], out);
381 }
382 i = j;
383 }
384 }
385
386 fn nested_sibling_lists(&mut self, run: &[Node], out: &mut Vec<ChunkItem>) {
387 let base = level_of(&run[0]);
388 let mut seg = 0;
389 for k in 0..run.len() {
390 let Node::ListItem {
391 first_in_list,
392 level,
393 ..
394 } = &run[k]
395 else {
396 continue;
397 };
398 if *level != base {
399 continue;
400 }
401 if k > seg && *first_in_list {
402 self.alloc.group();
403 self.list_refs(&run[seg..k], out);
404 seg = k;
405 }
406 }
407 self.alloc.group();
408 self.list_refs(&run[seg..], out);
409 }
410
411 fn one(&mut self, node: &Node) {
412 match node {
413 Node::Heading { level, text } => {
414 let doc_level = if *level == 1 {
415 0
416 } else {
417 level.saturating_sub(1)
418 };
419 let self_ref = self.alloc.text();
420 let runs = crate::inline_runs_from_markdown(text);
426 if runs.len() <= 1 {
427 let plain = runs
428 .first()
429 .map(|r| r.text.clone())
430 .unwrap_or_else(|| text.clone());
431 self.set_heading(doc_level, unescape_text(&plain));
432 } else {
433 self.set_heading(doc_level, String::new());
434 let body = unescape_text(text);
435 self.emit(
436 body.clone(),
437 vec![ChunkItem {
438 self_ref,
439 kind: ChunkItemKind::Text,
440 text: body,
441 }],
442 );
443 }
444 }
445 Node::Paragraph { text } => {
446 let t = text.trim();
447 let self_ref = self.alloc.text();
448 if let Some(inner) = t
451 .strip_prefix("$$")
452 .and_then(|s| s.strip_suffix("$$"))
453 .filter(|s| !s.is_empty())
454 {
455 let body = format!("$${inner}$$");
456 self.emit(
457 body.clone(),
458 vec![ChunkItem {
459 self_ref,
460 kind: ChunkItemKind::Text,
461 text: body,
462 }],
463 );
464 return;
465 }
466 self.emit_inline(text, self_ref);
467 }
468 Node::Caption { text, .. } => {
471 let self_ref = self.alloc.text();
472 self.emit_inline(text, self_ref);
473 }
474 Node::LabeledText { .. } => self.one(&node.labeled_as_paragraph()),
475 Node::CheckboxItem { checked, text } => {
476 let self_ref = self.alloc.text();
477 let mark = if *checked { "- [x] " } else { "- [ ] " };
478 let body = format!("{mark}{}", unescape_text(text));
479 self.emit(
480 body.clone(),
481 vec![ChunkItem {
482 self_ref,
483 kind: ChunkItemKind::Text,
484 text: body,
485 }],
486 );
487 }
488 Node::Formula { latex, .. } => {
491 let self_ref = self.alloc.text();
492 let body = format!("$${}$$", latex);
493 self.emit(
494 body.clone(),
495 vec![ChunkItem {
496 self_ref,
497 kind: ChunkItemKind::Text,
498 text: body,
499 }],
500 );
501 }
502 Node::Code { text, .. } => {
503 let self_ref = self.alloc.text();
504 let body = format!("```\n{}\n```", unescape_text(text));
505 self.emit(
506 body.clone(),
507 vec![ChunkItem {
508 self_ref,
509 kind: ChunkItemKind::Text,
510 text: body,
511 }],
512 );
513 }
514 Node::Table(t) => {
515 let self_ref = self.alloc.table();
516 let body = triplet_table_text(t);
517 self.emit(
518 body.clone(),
519 vec![ChunkItem {
520 self_ref,
521 kind: ChunkItemKind::Table,
522 text: body,
523 }],
524 );
525 }
526 Node::Picture { caption, .. } => {
527 let cap = caption.as_deref().filter(|c| !c.is_empty());
528 let cap_item = cap.map(|c| ChunkItem {
529 self_ref: self.alloc.text(),
530 kind: ChunkItemKind::Text,
531 text: unescape_text(c),
532 });
533 self.alloc.picture();
534 if let Some(cap_item) = cap_item {
538 let body = cap_item.text.clone();
539 self.emit(body, vec![cap_item]);
540 }
541 }
542 Node::Chart {
543 kind,
544 table,
545 caption,
546 ..
547 } => {
548 let cap = caption.as_deref().filter(|c| !c.is_empty());
549 let cap_item = cap.map(|c| ChunkItem {
550 self_ref: self.alloc.text(),
551 kind: ChunkItemKind::Text,
552 text: unescape_text(c),
553 });
554 let pic_ref = self.alloc.picture();
555 let mut parts: Vec<String> = Vec::new();
559 if let Some(ci) = &cap_item {
560 parts.push(ci.text.clone());
561 }
562 parts.push(humanize_label(kind));
563 let grid = crate::markdown::render_table(table, false);
564 if !grid.is_empty() {
565 parts.push(unescape_text(&grid));
566 }
567 let body = parts.join("\n\n");
568 let pic_item = ChunkItem {
573 self_ref: pic_ref,
574 kind: ChunkItemKind::Picture,
575 text: body.clone(),
576 };
577 let items = match cap_item {
578 Some(mut ci) => {
579 ci.text = String::new();
580 vec![ci, pic_item]
581 }
582 None => vec![pic_item],
583 };
584 self.emit(body, items);
585 }
586 Node::Group { layer: Some(_), .. } => {}
589 Node::Group { children, .. } => {
590 self.alloc.group();
593 self.walk(children);
594 }
595 Node::KeyValueGraph { .. } => {}
597 Node::FieldRegion { items } => {
598 self.alloc.field_region();
601 for item in items {
602 self.alloc.field_item();
603 for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
604 let self_ref = self.alloc.text();
605 let body = unescape_text(part);
606 self.emit(
607 body.clone(),
608 vec![ChunkItem {
609 self_ref,
610 kind: ChunkItemKind::Text,
611 text: body,
612 }],
613 );
614 }
615 }
616 }
617 Node::InlineGroup { md_text, runs, .. } => {
618 let self_ref = self.alloc.text();
619 self.emit_inline_with_runs(md_text, self_ref, runs);
620 }
621 Node::TextDump(text) => {
622 let self_ref = self.alloc.text();
623 let body = unescape_text(text);
624 self.emit(
625 body.clone(),
626 vec![ChunkItem {
627 self_ref,
628 kind: ChunkItemKind::Text,
629 text: body,
630 }],
631 );
632 }
633 Node::Located { inner, .. }
635 | Node::Prov { inner, .. }
636 | Node::Commented { inner, .. } => self.one(inner),
637 Node::PageFurniture { .. } | Node::FurnitureText { .. } => {
641 self.alloc.text();
642 }
643 Node::PictureChildren(children) => {
649 for child in children {
650 match child {
651 Node::PageFurniture { .. } => self.one(child),
654 Node::ListItem { .. } => {
655 self.alloc.group();
656 self.alloc.text();
657 }
658 _ => {
659 self.alloc.text();
660 }
661 }
662 }
663 }
664 Node::CommentSection { .. }
667 | Node::Furniture { .. }
668 | Node::PageBreak
669 | Node::PageInfo { .. }
670 | Node::DoclangOnly(_) => {}
671 Node::ListItem { .. } => self.sibling_lists(std::slice::from_ref(node)),
674 }
675 }
676}
677
678fn level_of(node: &Node) -> u8 {
679 match node {
680 Node::ListItem { level, .. } => *level,
681 _ => 0,
682 }
683}
684
685fn render_list(items: &[Node]) -> String {
688 let mut lines: Vec<String> = Vec::new();
689 for item in items {
690 let Node::ListItem {
691 ordered,
692 number,
693 text,
694 level,
695 layer,
696 ..
697 } = item
698 else {
699 continue;
700 };
701 if layer.is_some() {
702 continue;
703 }
704 let indent = " ".repeat(*level as usize);
705 let marker = if *ordered {
706 format!("{number}.")
707 } else {
708 "-".to_string()
709 };
710 lines.push(format!(
711 "{indent}{marker} {}",
712 unescape_text(&strip_image_markers(text))
713 ));
714 }
715 lines.join("\n")
716}
717
718fn strip_image_markers(text: &str) -> String {
723 if !text.contains("<!-- image -->") {
724 return text.to_string();
725 }
726 let cleaned: Vec<&str> = text
727 .split('\n')
728 .map(str::trim_end)
729 .filter(|l| *l != "<!-- image -->")
730 .collect();
731 cleaned.join("\n").trim_end().to_string()
732}
733
734fn humanize_label(label: &str) -> String {
737 let text = label.replace('_', " ");
738 let mut chars = text.chars();
739 match chars.next() {
740 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
741 None => text,
742 }
743}
744
745fn triplet_table_text(t: &Table) -> String {
752 let rows: Vec<Vec<String>> = t
753 .rows
754 .iter()
755 .enumerate()
756 .map(|(ri, r)| (0..r.len()).map(|ci| cell_chunk_text(t, ri, ci)).collect())
757 .collect();
758 let num_rows = rows.len();
759 let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
760 if num_rows == 0 || num_cols == 0 {
761 return String::new();
762 }
763 let cell = |r: usize, c: usize| -> &str {
764 rows.get(r)
765 .and_then(|row| row.get(c))
766 .map(String::as_str)
767 .unwrap_or("")
768 };
769
770 let num_headers = {
776 let derived;
777 let cells: &[crate::TableCell] = match &t.cells {
778 Some(c) if !c.is_empty() => c,
779 _ => {
780 derived = t.derive_cells();
781 &derived
782 }
783 };
784 (0..num_rows)
785 .take_while(|&r| cells.iter().any(|c| c.column_header && c.start_row == r))
786 .count()
787 };
788
789 let columns: Vec<String> = if num_headers > 0 {
792 (0..num_cols)
793 .map(|c| {
794 let mut name = String::new();
795 for r in 0..num_headers {
796 if !name.is_empty() {
797 name.push('.');
798 }
799 name.push_str(cell(r, c));
800 }
801 name
802 })
803 .collect()
804 } else {
805 (0..num_cols).map(|c| c.to_string()).collect()
806 };
807 let data_rows = num_headers..num_rows;
808 let n_data = data_rows.len();
809
810 if n_data == 0 {
812 return columns
813 .iter()
814 .map(|s| s.trim())
815 .filter(|s| !s.is_empty())
816 .collect::<Vec<_>>()
817 .join(". ");
818 }
819
820 let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
821 let text = if num_cols == 1 {
822 let col_name = data(0, 0).trim().to_string();
825 if n_data == 1 {
826 col_name
827 } else {
828 (1..n_data)
829 .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
830 .collect::<Vec<_>>()
831 .join(". ")
832 }
833 } else {
834 let mut parts = Vec::new();
836 for r in 0..n_data {
837 for (c, col_name) in columns.iter().enumerate().skip(1) {
838 parts.push(format!(
839 "{}, {} = {}",
840 data(r, 0).trim(),
841 col_name.trim(),
842 data(r, c).trim()
843 ));
844 }
845 }
846 parts.join(". ")
847 };
848 if !text.is_empty() {
849 return text;
850 }
851
852 (0..n_data)
855 .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
856 .map(|(r, c)| data(r, c).trim())
857 .filter(|s| !s.is_empty())
858 .collect::<Vec<_>>()
859 .join(". ")
860}
861
862fn inline_segments(md: &str) -> Vec<String> {
870 inline_segments_tagged(md)
871 .into_iter()
872 .map(|(t, _)| t)
873 .collect()
874}
875
876fn inline_segments_tagged(md: &str) -> Vec<(String, bool)> {
880 let chars: Vec<char> = md.chars().collect();
881 let n = chars.len();
882 let find = |from: usize, pat: &str| -> Option<usize> {
883 let hay: String = chars[from..].iter().collect();
884 hay.find(pat).map(|p| from + hay[..p].chars().count())
885 };
886 let mut out: Vec<(String, bool)> = Vec::new();
887 let mut plain = String::new();
888 let mut after_span = false;
889
890 fn flush(
891 out: &mut Vec<(String, bool)>,
892 plain: &mut String,
893 before_span: bool,
894 after_span: bool,
895 ) {
896 let mut p = std::mem::take(plain);
897 if after_span {
898 if let Some(rest) = p.strip_prefix(' ') {
899 p = rest.to_string();
900 }
901 }
902 if before_span {
903 if let Some(rest) = p.strip_suffix(' ') {
904 p = rest.to_string();
905 }
906 }
907 if !p.is_empty() {
908 out.push((unescape_text(&p), true));
909 }
910 }
911
912 let mut i = 0;
913 while i < n {
914 let rest: String = chars[i..].iter().collect();
915 if chars[i] == '[' && !rest.starts_with("[](") {
919 let balanced = |c: usize| {
923 let mut d = 0i32;
924 for &ch in &chars[i + 1..c] {
925 match ch {
926 '[' => d += 1,
927 ']' => d -= 1,
928 _ => {}
929 }
930 }
931 d == 0
932 };
933 if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
934 let mut depth = 0usize;
935 let mut url_end = None;
936 for (k, &c) in chars.iter().enumerate().skip(close + 2) {
937 match c {
938 '(' => depth += 1,
939 ')' => {
940 if depth == 0 {
941 url_end = Some(k);
942 break;
943 }
944 depth -= 1;
945 }
946 _ => {}
947 }
948 }
949 if let Some(endp) = url_end {
950 flush(&mut out, &mut plain, true, after_span);
951 out.push((
952 unescape_text(&chars[i..=endp].iter().collect::<String>()),
953 false,
954 ));
955 i = endp + 1;
956 after_span = true;
957 continue;
958 }
959 }
960 }
961 let mut matched = false;
964 for marker in ["***", "**", "*", "~~", "`"] {
965 if rest.starts_with(marker) {
966 let mlen = marker.chars().count();
967 if let Some(end) = find(i + mlen, marker) {
968 let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
972 if end > i + mlen && !inner_blank {
973 flush(&mut out, &mut plain, true, after_span);
974 if marker == "`" {
975 let inner: String = chars[i + 1..end].iter().collect();
976 out.push((format!("```\n{}\n```", unescape_text(&inner)), false));
977 } else {
978 out.push((
979 unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
980 false,
981 ));
982 }
983 i = end + mlen;
984 after_span = true;
985 matched = true;
986 }
987 }
988 break;
989 }
990 }
991 if matched {
992 continue;
993 }
994 if rest.starts_with("$$") {
997 plain.push_str("$$");
998 i += 2;
999 continue;
1000 }
1001 if chars[i] == '$' {
1003 if let Some(end) = find(i + 1, "$") {
1004 if end > i + 1 {
1005 flush(&mut out, &mut plain, true, after_span);
1006 let latex: String = chars[i + 1..end].iter().collect();
1007 out.push((format!("$${latex}$$"), false));
1008 i = end + 1;
1009 after_span = true;
1010 continue;
1011 }
1012 }
1013 }
1014 plain.push(chars[i]);
1015 i += 1;
1016 }
1017 flush(&mut out, &mut plain, false, after_span);
1018 if out.is_empty() {
1019 out.push((unescape_text(md), true));
1020 }
1021 out
1022}
1023
1024fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1029 let target = segment.trim();
1030 if target.is_empty() {
1031 return None;
1032 }
1033 let plainish =
1034 |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1035 let fully_plain =
1036 |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1037 let unmarked: Vec<(&str, bool)> = runs
1038 .iter()
1039 .filter(|r| plainish(r))
1040 .map(|r| (r.text.as_str(), fully_plain(r)))
1041 .collect();
1042 for start in 0..unmarked.len() {
1043 let mut rest = target;
1044 let mut taken: Vec<(String, bool)> = Vec::new();
1045 for (t, fully) in &unmarked[start..] {
1046 let t = t.trim();
1047 if t.is_empty() {
1048 continue;
1049 }
1050 match rest.strip_prefix(t) {
1051 Some(r) => {
1052 taken.push((unescape_text(t), *fully));
1053 rest = r.trim_start();
1054 if rest.is_empty() {
1055 break;
1056 }
1057 }
1058 None => break,
1059 }
1060 }
1061 if rest.is_empty() && taken.len() >= 2 {
1062 let mut merged: Vec<(String, bool)> = Vec::new();
1067 for (t, fully) in taken {
1068 match merged.last_mut() {
1069 Some((last, true)) if fully => {
1070 last.push(' ');
1071 last.push_str(&t);
1072 }
1073 _ => merged.push((t, fully)),
1074 }
1075 }
1076 if merged.len() >= 2 {
1077 return Some(merged.into_iter().map(|(t, _)| t).collect());
1078 }
1079 return None;
1080 }
1081 }
1082 None
1083}
1084
1085fn cell_chunk_text(t: &Table, r: usize, c: usize) -> String {
1092 if let Some(blocks) = t
1093 .cell_blocks
1094 .as_ref()
1095 .and_then(|b| b.get(r))
1096 .and_then(|row| row.get(c))
1097 .filter(|b| !b.is_empty())
1098 {
1099 let mut parts: Vec<String> = Vec::new();
1100 for node in blocks.iter() {
1101 let part = block_chunk_text(node);
1102 if !part.is_empty() {
1103 parts.push(part);
1104 }
1105 }
1106 return parts.join("\n\n");
1107 }
1108 let flat = t
1109 .rows
1110 .get(r)
1111 .and_then(|row| row.get(c))
1112 .map(String::as_str)
1113 .unwrap_or("");
1114 unescape_text(flat)
1115 .replace("<!-- image -->", "")
1116 .trim()
1117 .to_string()
1118}
1119
1120fn block_chunk_text(node: &Node) -> String {
1122 match node {
1123 Node::Paragraph { text } => unescape_text(text),
1124 Node::LabeledText { .. } => block_chunk_text(&node.labeled_as_paragraph()),
1125 Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1126 Node::Code { text, .. } => format!("```\n{}\n```", unescape_text(text)),
1127 Node::Table(inner) => triplet_table_text(inner),
1128 Node::Picture { caption, .. } => caption
1129 .as_deref()
1130 .filter(|c| !c.is_empty())
1131 .map(unescape_text)
1132 .unwrap_or_default(),
1133 Node::ListItem {
1134 ordered,
1135 number,
1136 text,
1137 ..
1138 } => {
1139 let marker = if *ordered {
1140 format!("{number}.")
1141 } else {
1142 "-".to_string()
1143 };
1144 format!("{marker} {}", unescape_text(text))
1145 }
1146 Node::CheckboxItem { checked, text } => {
1147 let mark = if *checked { "- [x] " } else { "- [ ] " };
1148 format!("{mark}{}", unescape_text(text))
1149 }
1150 Node::Heading { text, .. } => unescape_text(text),
1151 Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Commented { inner, .. } => {
1152 block_chunk_text(inner)
1153 }
1154 Node::Group { layer: Some(_), .. } => String::new(),
1155 Node::Group { children, .. } => children
1156 .iter()
1157 .map(block_chunk_text)
1158 .filter(|s| !s.is_empty())
1159 .collect::<Vec<_>>()
1160 .join("\n"),
1161 _ => String::new(),
1162 }
1163}
1164
1165fn unescape_text(s: &str) -> String {
1168 s.replace("<", "<")
1169 .replace(">", ">")
1170 .replace("&", "&")
1171 .replace("\\_", "_")
1172}
1173
1174pub trait ChunkTokenizer {
1180 fn count_tokens(&self, text: &str) -> usize;
1182 fn max_tokens(&self) -> usize;
1184}
1185
1186pub struct HybridChunker<T: ChunkTokenizer> {
1190 tokenizer: T,
1191 merge_peers: bool,
1192}
1193
1194impl<T: ChunkTokenizer> HybridChunker<T> {
1195 pub fn new(tokenizer: T) -> Self {
1196 Self {
1197 tokenizer,
1198 merge_peers: true,
1199 }
1200 }
1201
1202 pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1204 self.merge_peers = merge_peers;
1205 self
1206 }
1207
1208 pub fn max_tokens(&self) -> usize {
1209 self.tokenizer.max_tokens()
1210 }
1211
1212 pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1214 let mut chunks = Vec::new();
1215 self.chunk_with(doc, &mut |c| {
1216 chunks.push(c);
1217 true
1218 });
1219 chunks
1220 }
1221
1222 pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1229 let mut merger = PeerMerger::default();
1230 let mut alive = true;
1231 HierarchicalChunker.chunk_with(doc, &mut |c| {
1232 for split in self.split_by_doc_items(c) {
1233 for chunk in self.split_using_plain_text(split) {
1234 if !alive {
1235 return false;
1236 }
1237 alive = if self.merge_peers {
1238 self.merge_push(&mut merger, chunk, sink)
1239 } else {
1240 sink(chunk)
1241 };
1242 }
1243 }
1244 alive
1245 });
1246 if alive {
1247 self.merge_flush(&mut merger, sink);
1248 }
1249 }
1250
1251 fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1252 self.tokenizer.count_tokens(&contextualize(chunk))
1253 }
1254
1255 fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1258 let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1259 let text = if chunk.doc_items.len() == 1 {
1260 chunk.text.clone()
1261 } else {
1262 doc_items
1263 .iter()
1264 .filter(|it| !it.text.is_empty())
1265 .map(|it| it.text.as_str())
1266 .collect::<Vec<_>>()
1267 .join("\n")
1268 };
1269 DocChunk {
1270 text,
1271 headings: chunk.headings.clone(),
1272 doc_items,
1273 }
1274 }
1275
1276 fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1277 if chunk.doc_items.is_empty() {
1278 return vec![chunk];
1279 }
1280 let max = self.max_tokens();
1281 let num_items = chunk.doc_items.len();
1282 let mut chunks = Vec::new();
1283 let mut window_start = 0usize;
1284 let mut window_end = 0usize; while window_end < num_items {
1286 let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1287 if self.count_chunk_tokens(&new_chunk) <= max {
1288 if window_end < num_items - 1 {
1289 window_end += 1;
1290 continue;
1291 } else {
1292 window_end = num_items; }
1294 } else if window_start == window_end {
1295 window_end += 1;
1298 window_start = window_end;
1299 } else {
1300 new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1303 window_start = window_end;
1304 }
1305 chunks.push(new_chunk);
1306 }
1307 chunks
1308 }
1309
1310 fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1311 let total = self.count_chunk_tokens(&chunk);
1312 let max = self.max_tokens();
1313 if total <= max {
1314 return vec![chunk];
1315 }
1316 let text_len = self.tokenizer.count_tokens(&chunk.text);
1317 let other_len = total - text_len;
1318 if other_len >= max {
1319 let stripped = DocChunk {
1321 headings: None,
1322 ..chunk
1323 };
1324 return self.split_using_plain_text(stripped);
1325 }
1326 let available = max - other_len;
1327
1328 let segments =
1329 if chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table {
1330 let lines: Vec<String> = chunk
1337 .text
1338 .split('\n')
1339 .filter(|l| !l.trim().is_empty())
1340 .map(|l| l.to_string())
1341 .collect();
1342 line_chunk_text(&lines, &self.tokenizer, max)
1343 } else {
1344 semchunk(&chunk.text, available, &self.tokenizer)
1345 };
1346 segments
1347 .into_iter()
1348 .map(|s| DocChunk {
1349 text: s,
1350 headings: chunk.headings.clone(),
1351 doc_items: chunk.doc_items.clone(),
1352 })
1353 .collect()
1354 }
1355
1356 fn merge_push(
1362 &self,
1363 m: &mut PeerMerger,
1364 chunk: DocChunk,
1365 sink: &mut dyn FnMut(DocChunk) -> bool,
1366 ) -> bool {
1367 if m.window.is_empty() {
1368 m.window.push(chunk);
1369 return true;
1370 }
1371 let candidate = DocChunk {
1372 text: m
1373 .window
1374 .iter()
1375 .map(|c| c.text.as_str())
1376 .chain([chunk.text.as_str()])
1377 .collect::<Vec<_>>()
1378 .join("\n"),
1379 headings: m.window[0].headings.clone(),
1380 doc_items: m
1381 .window
1382 .iter()
1383 .flat_map(|c| c.doc_items.iter().cloned())
1384 .chain(chunk.doc_items.iter().cloned())
1385 .collect(),
1386 };
1387 if chunk.headings == m.window[0].headings
1388 && self.count_chunk_tokens(&candidate) <= self.max_tokens()
1389 {
1390 m.window.push(chunk);
1391 m.merged = Some(candidate);
1392 true
1393 } else {
1394 let alive = self.merge_flush(m, sink);
1395 m.window.push(chunk);
1396 alive
1397 }
1398 }
1399
1400 fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
1404 let alive = if m.window.len() == 1 {
1405 sink(m.window.pop().expect("single-chunk window"))
1406 } else if !m.window.is_empty() {
1407 m.window.clear();
1408 sink(m.merged.take().expect("multi-chunk window has a merge"))
1409 } else {
1410 true
1411 };
1412 m.merged = None;
1413 alive
1414 }
1415}
1416
1417#[derive(Default)]
1419struct PeerMerger {
1420 window: Vec<DocChunk>,
1421 merged: Option<DocChunk>,
1422}
1423
1424fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
1434 let mut chunks: Vec<String> = Vec::new();
1435 let mut current = String::new();
1436 let mut current_len = 0usize;
1437
1438 for line in lines {
1439 let mut remaining: Vec<char> = line.chars().collect();
1440 loop {
1441 let rem_str: String = remaining.iter().collect();
1442 let line_tokens = tok.count_tokens(&rem_str);
1443 let available = max_tokens.saturating_sub(current_len);
1444
1445 if line_tokens <= available {
1446 current.push_str(&rem_str);
1447 current_len += line_tokens;
1448 break;
1449 }
1450 if line_tokens <= max_tokens {
1451 chunks.push(std::mem::take(&mut current));
1452 current_len = 0;
1453 continue;
1454 }
1455 let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
1457 let mut rest = rest;
1458 if take.is_empty() {
1459 if rest.is_empty() {
1460 break;
1461 }
1462 take = rest[..1].iter().collect();
1463 rest = rest[1..].to_vec();
1464 }
1465 current.push('\n');
1466 current.push_str(&take);
1467 chunks.push(std::mem::take(&mut current));
1468 current_len = 0;
1469 remaining = rest;
1470 }
1471 }
1472 if !current.is_empty() {
1473 chunks.push(current);
1474 }
1475 chunks
1476}
1477
1478fn split_by_token_limit<T: ChunkTokenizer>(
1482 text: &[char],
1483 token_limit: usize,
1484 tok: &T,
1485) -> (String, Vec<char>) {
1486 if token_limit == 0 || text.is_empty() {
1487 return (String::new(), text.to_vec());
1488 }
1489 let full: String = text.iter().collect();
1490 if tok.count_tokens(&full) <= token_limit {
1491 return (full, Vec::new());
1492 }
1493 let (mut lo, mut hi) = (0usize, text.len());
1494 let mut best: Option<usize> = None;
1495 while lo <= hi {
1496 let mid = (lo + hi) / 2;
1497 let head: String = text[..mid].iter().collect();
1498 if tok.count_tokens(&head) <= token_limit {
1499 best = Some(mid);
1500 lo = mid + 1;
1501 } else {
1502 if mid == 0 {
1503 break;
1504 }
1505 hi = mid - 1;
1506 }
1507 }
1508 let mut best_idx = match best {
1509 Some(b) if b > 0 => b,
1510 _ => return (String::new(), text.to_vec()),
1511 };
1512 if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
1514 if pos > 0 {
1515 best_idx = pos;
1516 }
1517 }
1518 (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
1519}
1520
1521const NON_WS_SPLITTERS: &[&str] = &[
1527 ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
1528 "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
1529];
1530
1531pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
1535 let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
1536 let mut counter = |s: &str| -> usize {
1537 if let Some(n) = cache.get(s) {
1538 return *n;
1539 }
1540 let n = tok.count_tokens(s);
1541 cache.insert(s.to_string(), n);
1542 n
1543 };
1544 let chunks = semchunk_rec(text, chunk_size, &mut counter);
1545 chunks
1547 .into_iter()
1548 .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
1549 .collect()
1550}
1551
1552fn semchunk_rec(
1555 text: &str,
1556 chunk_size: usize,
1557 counter: &mut dyn FnMut(&str) -> usize,
1558) -> Vec<String> {
1559 let (splitter, splitter_is_ws, splits) = split_text(text);
1560
1561 let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
1562 let mut cum_lens = Vec::with_capacity(splits.len() + 1);
1563 cum_lens.push(0usize);
1564 for l in &split_lens {
1565 cum_lens.push(cum_lens.last().unwrap() + l);
1566 }
1567 let num_splits_plus_one = splits.len() + 1;
1568
1569 let mut chunks: Vec<String> = Vec::new();
1570 let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
1571
1572 for i in 0..splits.len() {
1573 if skips.contains(&i) {
1574 continue;
1575 }
1576 let split = &splits[i];
1577 if counter(split) > chunk_size {
1578 let inner = semchunk_rec(split, chunk_size, counter);
1579 chunks.extend(inner);
1580 } else {
1581 let (end, merged) = merge_splits(
1582 &splits,
1583 &cum_lens,
1584 chunk_size,
1585 &splitter,
1586 counter,
1587 i,
1588 num_splits_plus_one,
1589 );
1590 for j in (i + 1)..end {
1591 skips.insert(j);
1592 }
1593 chunks.push(merged);
1594 }
1595 let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
1598 if !splitter_is_ws && !is_last {
1599 let with_splitter = format!(
1600 "{}{}",
1601 chunks.last().map(String::as_str).unwrap_or(""),
1602 splitter
1603 );
1604 if counter(&with_splitter) <= chunk_size {
1605 if let Some(last) = chunks.last_mut() {
1606 *last = with_splitter;
1607 } else {
1608 chunks.push(with_splitter);
1609 }
1610 } else {
1611 chunks.push(splitter.clone());
1612 }
1613 }
1614 }
1615 chunks
1616}
1617
1618fn merge_splits(
1621 splits: &[String],
1622 cum_lens: &[usize],
1623 chunk_size: usize,
1624 splitter: &str,
1625 counter: &mut dyn FnMut(&str) -> usize,
1626 start: usize,
1627 high_init: usize,
1628) -> (usize, String) {
1629 let mut average = 0.2f64;
1630 let mut low = start;
1631 let mut high = high_init;
1632 let offset = cum_lens[start];
1633 let mut target = offset as f64 + (chunk_size as f64 * average);
1634
1635 while low < high {
1636 let i = bisect_left(cum_lens, target, low, high);
1637 let midpoint = i.min(high - 1);
1638 let joined = splits[start..midpoint.max(start)].join(splitter);
1639 let tokens = counter(&joined);
1640 let local_cum = cum_lens[midpoint] - offset;
1641 if local_cum > 0 && tokens > 0 {
1642 average = local_cum as f64 / tokens as f64;
1643 target = offset as f64 + (chunk_size as f64 * average);
1644 }
1645 if tokens > chunk_size {
1646 high = midpoint;
1647 } else {
1648 low = midpoint + 1;
1649 }
1650 }
1651 let end = low - 1;
1652 (end, splits[start..end.max(start)].join(splitter))
1653}
1654
1655fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
1656 while low < high {
1657 let mid = (low + high) / 2;
1658 if (sorted[mid] as f64) < target {
1659 low = mid + 1;
1660 } else {
1661 high = mid;
1662 }
1663 }
1664 low
1665}
1666
1667fn split_text(text: &str) -> (String, bool, Vec<String>) {
1669 if text.contains('\n') || text.contains('\r') {
1671 let splitter = longest_run(text, |c| c == '\n' || c == '\r');
1672 return (splitter.clone(), true, split_on(text, &splitter));
1673 }
1674 if text.contains('\t') {
1676 let splitter = longest_run(text, |c| c == '\t');
1677 return (splitter.clone(), true, split_on(text, &splitter));
1678 }
1679 if text.chars().any(char::is_whitespace) {
1681 let splitter = longest_run(text, char::is_whitespace);
1682 if splitter.chars().count() == 1 {
1683 for preceder in NON_WS_SPLITTERS {
1685 if let Some((ws, parts)) = split_after_preceder(text, preceder) {
1686 return (ws, true, parts);
1687 }
1688 }
1689 }
1690 return (splitter.clone(), true, split_on(text, &splitter));
1691 }
1692 for s in NON_WS_SPLITTERS {
1694 if text.contains(s) {
1695 return (s.to_string(), false, split_on(text, s));
1696 }
1697 }
1698 (
1700 String::new(),
1701 true,
1702 text.chars().map(|c| c.to_string()).collect(),
1703 )
1704}
1705
1706fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
1708 let mut best = String::new();
1709 let mut cur = String::new();
1710 for c in text.chars() {
1711 if pred(c) {
1712 cur.push(c);
1713 } else {
1714 if cur.chars().count() > best.chars().count() {
1715 best = cur.clone();
1716 }
1717 cur.clear();
1718 }
1719 }
1720 if cur.chars().count() > best.chars().count() {
1721 best = cur;
1722 }
1723 best
1724}
1725
1726fn split_on(text: &str, splitter: &str) -> Vec<String> {
1727 text.split(splitter).map(str::to_string).collect()
1728}
1729
1730fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
1734 let chars: Vec<char> = text.chars().collect();
1735 let p: Vec<char> = preceder.chars().collect();
1736 let mut ws: Option<char> = None;
1737 for i in p.len()..chars.len() {
1738 if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
1739 ws = Some(chars[i]);
1740 break;
1741 }
1742 }
1743 let ws = ws?;
1744 let mut parts = Vec::new();
1745 let mut cur = String::new();
1746 let mut i = 0usize;
1747 while i < chars.len() {
1748 if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
1749 parts.push(std::mem::take(&mut cur));
1750 i += 1;
1751 continue;
1752 }
1753 cur.push(chars[i]);
1754 i += 1;
1755 }
1756 parts.push(cur);
1757 Some((ws.to_string(), parts))
1758}
1759
1760#[cfg(feature = "chunking")]
1765mod hf {
1766 use super::ChunkTokenizer;
1767
1768 pub const DEFAULT_TOKENIZER_PATH: &str = ".models/chunk/tokenizer.json";
1773
1774 pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
1779 if let Some(p) = explicit {
1780 return Ok(p.to_string());
1781 }
1782 let resolved = crate::assets::resolve(DEFAULT_TOKENIZER_PATH);
1783 if std::path::Path::new(&resolved).exists() {
1784 return Ok(resolved);
1785 }
1786 Err(format!(
1787 "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
1788 {DEFAULT_TOKENIZER_PATH} does not exist — run \
1789 scripts/install/download_dependencies.sh (or pass an explicit path)"
1790 ))
1791 }
1792
1793 pub struct HuggingFaceTokenizer {
1797 tok: tokenizers::Tokenizer,
1798 max_tokens: usize,
1799 }
1800
1801 impl HuggingFaceTokenizer {
1802 pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
1806 Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
1807 }
1808
1809 pub fn from_file(
1813 path: impl AsRef<std::path::Path>,
1814 max_tokens: usize,
1815 ) -> Result<Self, String> {
1816 let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
1817 .map_err(|e| format!("failed to load tokenizer: {e}"))?;
1818 let _ = tok.with_truncation(None);
1823 tok.with_padding(None);
1824 Ok(Self { tok, max_tokens })
1825 }
1826 }
1827
1828 impl ChunkTokenizer for HuggingFaceTokenizer {
1829 fn count_tokens(&self, text: &str) -> usize {
1830 self.tok
1831 .encode(text, false)
1832 .map(|e| e.get_tokens().len())
1833 .unwrap_or(0)
1834 }
1835 fn max_tokens(&self) -> usize {
1836 self.max_tokens
1837 }
1838 }
1839}
1840
1841#[cfg(feature = "chunking")]
1842pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
1843
1844#[cfg(feature = "chunking")]
1849mod window {
1850 use super::DocChunk;
1851 use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
1852
1853 #[derive(Debug, Clone, Default)]
1855 pub struct Section {
1856 pub heading_path: Vec<String>,
1859 pub words: Vec<String>,
1861 }
1862
1863 impl Section {
1864 pub fn heading_context(&self) -> String {
1867 if self.heading_path.is_empty() {
1868 String::new()
1869 } else {
1870 format!("# {}", self.heading_path.join(" > "))
1871 }
1872 }
1873 }
1874
1875 fn level_index(level: HeadingLevel) -> usize {
1876 match level {
1877 HeadingLevel::H1 => 1,
1878 HeadingLevel::H2 => 2,
1879 HeadingLevel::H3 => 3,
1880 HeadingLevel::H4 => 4,
1881 HeadingLevel::H5 => 5,
1882 HeadingLevel::H6 => 6,
1883 }
1884 }
1885
1886 pub fn parse_sections(markdown: &str) -> Vec<Section> {
1890 parse_sections_with_stack(markdown, Vec::new()).0
1891 }
1892
1893 pub fn parse_sections_with_stack(
1898 markdown: &str,
1899 initial_stack: Vec<String>,
1900 ) -> (Vec<Section>, Vec<String>) {
1901 let mut heading_stack: Vec<String> = initial_stack;
1902 let mut sections: Vec<Section> = Vec::new();
1903 let mut current = Section {
1906 heading_path: heading_stack
1907 .iter()
1908 .filter(|h| !h.is_empty())
1909 .cloned()
1910 .collect(),
1911 words: Vec::new(),
1912 };
1913
1914 let mut in_heading = false;
1915 let mut heading_level = 0usize;
1916 let mut heading_buf = String::new();
1917
1918 let push_words = |section: &mut Section, text: &str| {
1919 for w in text.split_whitespace() {
1920 section.words.push(w.to_string());
1921 }
1922 };
1923
1924 let flush = |sections: &mut Vec<Section>, section: &mut Section| {
1925 if !section.words.is_empty() {
1926 sections.push(std::mem::take(section));
1927 } else {
1928 *section = Section::default();
1929 }
1930 };
1931
1932 for event in Parser::new(markdown) {
1933 match event {
1934 Event::Start(Tag::Heading { level, .. }) => {
1935 in_heading = true;
1936 heading_level = level_index(level);
1937 heading_buf.clear();
1938 }
1939 Event::End(TagEnd::Heading(_)) => {
1940 in_heading = false;
1941 let idx = heading_level.saturating_sub(1);
1943 if heading_stack.len() <= idx {
1944 heading_stack.resize(idx + 1, String::new());
1945 } else {
1946 heading_stack.truncate(idx + 1);
1947 }
1948 heading_stack[idx] = heading_buf.trim().to_string();
1949 flush(&mut sections, &mut current);
1951 current.heading_path = heading_stack
1952 .iter()
1953 .filter(|h| !h.is_empty())
1954 .cloned()
1955 .collect();
1956 }
1957 Event::Text(t) | Event::Code(t) => {
1958 if in_heading {
1959 if !heading_buf.is_empty() {
1960 heading_buf.push(' ');
1961 }
1962 heading_buf.push_str(&t);
1963 } else {
1964 push_words(&mut current, &t);
1965 }
1966 }
1967 Event::SoftBreak | Event::HardBreak | Event::Rule => {}
1969 _ => {}
1970 }
1971 }
1972 flush(&mut sections, &mut current);
1973 (sections, heading_stack)
1974 }
1975
1976 #[derive(Debug, Clone)]
1982 pub struct WindowChunker {
1983 pub max_words: usize,
1985 pub overlap: f32,
1987 }
1988
1989 impl Default for WindowChunker {
1990 fn default() -> Self {
1991 WindowChunker {
1992 max_words: 300,
1993 overlap: 0.05,
1994 }
1995 }
1996 }
1997
1998 impl WindowChunker {
1999 pub fn new(max_words: usize, overlap: f32) -> Self {
2000 WindowChunker { max_words, overlap }
2001 }
2002
2003 fn word_budget(&self) -> usize {
2005 self.max_words.max(1)
2006 }
2007
2008 fn overlap_words(&self, budget: usize) -> usize {
2011 let o = (budget as f32 * self.overlap).round() as usize;
2012 o.min(budget.saturating_sub(1))
2013 }
2014
2015 pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
2017 let mut chunks = Vec::new();
2018 self.chunk_with(markdown, &mut |c| {
2019 chunks.push(c);
2020 true
2021 });
2022 chunks
2023 }
2024
2025 pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2029 let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2030 for section in §ions {
2031 if !self.pack_section(section, sink) {
2032 return;
2033 }
2034 }
2035 }
2036
2037 pub fn pack_section(
2041 &self,
2042 section: &Section,
2043 sink: &mut dyn FnMut(DocChunk) -> bool,
2044 ) -> bool {
2045 let words = §ion.words;
2046 if words.is_empty() {
2047 return true;
2048 }
2049 let budget = self.word_budget();
2050 let step = budget - self.overlap_words(budget); let mut start = 0;
2052 loop {
2053 let end = (start + budget).min(words.len());
2054 let chunk = DocChunk {
2055 text: words[start..end].join(" "),
2056 headings: (!section.heading_path.is_empty())
2057 .then(|| section.heading_path.clone()),
2058 doc_items: Vec::new(),
2059 };
2060 if !sink(chunk) {
2061 return false;
2062 }
2063 if end >= words.len() {
2064 return true;
2065 }
2066 start += step;
2067 }
2068 }
2069
2070 pub fn contextualize(chunk: &DocChunk) -> String {
2076 match &chunk.headings {
2077 Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2078 _ => chunk.text.clone(),
2079 }
2080 }
2081 }
2082
2083 #[cfg(test)]
2084 mod tests {
2085 use super::*;
2086
2087 #[test]
2088 fn splits_on_headings_and_tracks_path() {
2089 let md = "\
2090intro words
2091# Chapter 1
2092para one
2093## Section 1.1
2094para two
2095# Chapter 2
2096para three";
2097 let secs = parse_sections(md);
2098 assert_eq!(secs.len(), 4);
2100 assert!(secs[0].heading_path.is_empty());
2101 assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2102 assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2103 assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2105 }
2106
2107 #[test]
2108 fn strips_markup_to_plain_words() {
2109 let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2110 let secs = parse_sections(md);
2111 let words = &secs[0].words;
2112 assert!(words.contains(&"bold".to_string()));
2113 assert!(words.contains(&"code".to_string()));
2114 assert!(words.contains(&"link".to_string()));
2115 assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2117 }
2118
2119 #[test]
2120 fn windows_overlap_and_never_cross_headings() {
2121 let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2122 let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2123 let chunker = WindowChunker::new(10, 0.2); let chunks = chunker.chunk(&md);
2125 let a: Vec<_> = chunks
2127 .iter()
2128 .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2129 .collect();
2130 assert_eq!(a.len(), 3);
2131 assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2132 assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2133 assert!(a[2].text.ends_with(" w24"));
2134 let b: Vec<_> = chunks
2136 .iter()
2137 .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2138 .collect();
2139 assert_eq!(b.len(), 1);
2140 assert_eq!(b[0].text, "short tail");
2141 assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2142 }
2143
2144 #[test]
2145 fn sink_false_cancels_the_window_walk() {
2146 let md = format!(
2147 "# A\n\n{}\n",
2148 (0..50)
2149 .map(|i| format!("w{i}"))
2150 .collect::<Vec<_>>()
2151 .join(" ")
2152 );
2153 let chunker = WindowChunker::new(10, 0.0);
2154 let mut n = 0;
2155 chunker.chunk_with(&md, &mut |_| {
2156 n += 1;
2157 false
2158 });
2159 assert_eq!(n, 1);
2160 }
2161 }
2162}
2163
2164#[cfg(feature = "chunking")]
2165pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2166
2167#[cfg(test)]
2168mod tests {
2169 use super::*;
2170
2171 struct WordTok(usize);
2173 impl ChunkTokenizer for WordTok {
2174 fn count_tokens(&self, text: &str) -> usize {
2175 text.split_whitespace().count()
2176 }
2177 fn max_tokens(&self) -> usize {
2178 self.0
2179 }
2180 }
2181
2182 fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2183 let mut d = DoclingDocument::new("t");
2184 for n in nodes {
2185 d.push(n);
2186 }
2187 d
2188 }
2189
2190 #[test]
2191 fn hierarchical_headings_and_items() {
2192 let doc = doc_with(vec![
2193 Node::Heading {
2194 level: 1,
2195 text: "Title".into(),
2196 },
2197 Node::Paragraph {
2198 text: "Intro".into(),
2199 },
2200 Node::Heading {
2201 level: 2,
2202 text: "Sec".into(),
2203 },
2204 Node::Paragraph {
2205 text: "Body".into(),
2206 },
2207 ]);
2208 let chunks = HierarchicalChunker.chunk(&doc);
2209 assert_eq!(chunks.len(), 2);
2210 assert_eq!(chunks[0].text, "Intro");
2211 assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2212 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2213 assert_eq!(
2214 chunks[1].headings.as_deref(),
2215 Some(&["Title".into(), "Sec".into()][..])
2216 );
2217 assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
2218 }
2219
2220 #[test]
2223 fn page_furniture_keeps_refs_aligned_with_json() {
2224 let doc = doc_with(vec![
2225 Node::Paragraph {
2226 text: "Before".into(),
2227 },
2228 Node::PageFurniture {
2229 footer: true,
2230 location: [0, 490, 100, 512],
2231 text: "1.10.2".into(),
2232 },
2233 Node::Paragraph {
2234 text: "After".into(),
2235 },
2236 ]);
2237 let chunks = HierarchicalChunker.chunk(&doc);
2238 assert_eq!(chunks.len(), 2);
2239 assert_eq!(chunks[1].text, "After");
2240 let json: serde_json::Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2241 assert_eq!(json["texts"][2]["text"], "After");
2242 assert_eq!(chunks[1].doc_items[0].self_ref, "#/texts/2");
2243 }
2244
2245 #[test]
2249 fn picture_children_are_not_chunked_but_keep_refs_aligned() {
2250 let doc = doc_with(vec![
2251 Node::Picture {
2252 caption: None,
2253 caption_href: None,
2254 image: None,
2255 classification: None,
2256 caption_parent: crate::CaptionParent::Item,
2257 caption_location: None,
2258 },
2259 Node::PictureChildren(vec![
2260 Node::Paragraph {
2261 text: "axis label".into(),
2262 },
2263 Node::ListItem {
2264 ordered: false,
2265 number: 0,
2266 first_in_list: true,
2267 text: "callout".into(),
2268 level: 0,
2269 marker: None,
2270 location: None,
2271 dclx: None,
2272 href: None,
2273 layer: None,
2274 },
2275 ]),
2276 Node::Paragraph {
2277 text: "Body".into(),
2278 },
2279 ]);
2280 let chunks = HierarchicalChunker.chunk(&doc);
2281 assert_eq!(chunks.len(), 1);
2282 assert_eq!(chunks[0].text, "Body");
2283 let json = doc.export_to_json_value();
2284 assert_eq!(json["texts"][2]["text"], "Body");
2285 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/2");
2286 }
2287
2288 #[test]
2289 fn heading_shadowing_prunes_deeper_levels() {
2290 let doc = doc_with(vec![
2291 Node::Heading {
2292 level: 2,
2293 text: "A".into(),
2294 },
2295 Node::Heading {
2296 level: 3,
2297 text: "A.1".into(),
2298 },
2299 Node::Heading {
2300 level: 2,
2301 text: "B".into(),
2302 },
2303 Node::Paragraph { text: "p".into() },
2304 ]);
2305 let chunks = HierarchicalChunker.chunk(&doc);
2306 assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
2307 }
2308
2309 #[test]
2310 fn triplet_table() {
2311 let t = Table {
2312 rows: vec![
2313 vec!["".into(), "Col1".into()],
2314 vec!["Row1".into(), "v".into()],
2315 ],
2316 ..Default::default()
2317 };
2318 assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
2319 let single = Table {
2322 rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
2323 ..Default::default()
2324 };
2325 assert_eq!(triplet_table_text(&single), "a = b");
2326 }
2327
2328 #[test]
2329 fn hybrid_merges_small_peers_and_splits_large() {
2330 let doc = doc_with(vec![
2331 Node::Heading {
2332 level: 2,
2333 text: "S".into(),
2334 },
2335 Node::Paragraph { text: "a b".into() },
2336 Node::Paragraph { text: "c d".into() },
2337 ]);
2338 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2339 assert_eq!(chunks.len(), 1, "peers under one heading merge");
2340 assert_eq!(chunks[0].text, "a b\nc d");
2341
2342 let long = "w ".repeat(40).trim().to_string();
2343 let doc = doc_with(vec![Node::Paragraph { text: long }]);
2344 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2345 assert!(chunks.len() > 1, "oversized paragraph splits");
2346 for c in &chunks {
2347 assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
2348 }
2349 }
2350
2351 #[test]
2352 fn semchunk_prefers_newlines_then_sentences() {
2353 let tok = WordTok(4);
2354 let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
2355 assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
2356 }
2357}