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