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 { .. } => {
640 self.alloc.text();
641 }
642 Node::CommentSection { .. }
645 | Node::Furniture { .. }
646 | Node::PageBreak
647 | Node::PageInfo { .. }
648 | Node::DoclangOnly(_) => {}
649 Node::ListItem { .. } => self.sibling_lists(std::slice::from_ref(node)),
652 }
653 }
654}
655
656fn level_of(node: &Node) -> u8 {
657 match node {
658 Node::ListItem { level, .. } => *level,
659 _ => 0,
660 }
661}
662
663fn render_list(items: &[Node]) -> String {
666 let mut lines: Vec<String> = Vec::new();
667 for item in items {
668 let Node::ListItem {
669 ordered,
670 number,
671 text,
672 level,
673 layer,
674 ..
675 } = item
676 else {
677 continue;
678 };
679 if layer.is_some() {
680 continue;
681 }
682 let indent = " ".repeat(*level as usize);
683 let marker = if *ordered {
684 format!("{number}.")
685 } else {
686 "-".to_string()
687 };
688 lines.push(format!(
689 "{indent}{marker} {}",
690 unescape_text(&strip_image_markers(text))
691 ));
692 }
693 lines.join("\n")
694}
695
696fn strip_image_markers(text: &str) -> String {
701 if !text.contains("<!-- image -->") {
702 return text.to_string();
703 }
704 let cleaned: Vec<&str> = text
705 .split('\n')
706 .map(str::trim_end)
707 .filter(|l| *l != "<!-- image -->")
708 .collect();
709 cleaned.join("\n").trim_end().to_string()
710}
711
712fn humanize_label(label: &str) -> String {
715 let text = label.replace('_', " ");
716 let mut chars = text.chars();
717 match chars.next() {
718 Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
719 None => text,
720 }
721}
722
723fn triplet_table_text(t: &Table) -> String {
730 let rows: Vec<Vec<String>> = t
731 .rows
732 .iter()
733 .enumerate()
734 .map(|(ri, r)| (0..r.len()).map(|ci| cell_chunk_text(t, ri, ci)).collect())
735 .collect();
736 let num_rows = rows.len();
737 let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
738 if num_rows == 0 || num_cols == 0 {
739 return String::new();
740 }
741 let cell = |r: usize, c: usize| -> &str {
742 rows.get(r)
743 .and_then(|row| row.get(c))
744 .map(String::as_str)
745 .unwrap_or("")
746 };
747
748 let num_headers = {
754 let derived;
755 let cells: &[crate::TableCell] = match &t.cells {
756 Some(c) if !c.is_empty() => c,
757 _ => {
758 derived = t.derive_cells();
759 &derived
760 }
761 };
762 (0..num_rows)
763 .take_while(|&r| cells.iter().any(|c| c.column_header && c.start_row == r))
764 .count()
765 };
766
767 let columns: Vec<String> = if num_headers > 0 {
770 (0..num_cols)
771 .map(|c| {
772 let mut name = String::new();
773 for r in 0..num_headers {
774 if !name.is_empty() {
775 name.push('.');
776 }
777 name.push_str(cell(r, c));
778 }
779 name
780 })
781 .collect()
782 } else {
783 (0..num_cols).map(|c| c.to_string()).collect()
784 };
785 let data_rows = num_headers..num_rows;
786 let n_data = data_rows.len();
787
788 if n_data == 0 {
790 return columns
791 .iter()
792 .map(|s| s.trim())
793 .filter(|s| !s.is_empty())
794 .collect::<Vec<_>>()
795 .join(". ");
796 }
797
798 let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
799 let text = if num_cols == 1 {
800 let col_name = data(0, 0).trim().to_string();
803 if n_data == 1 {
804 col_name
805 } else {
806 (1..n_data)
807 .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
808 .collect::<Vec<_>>()
809 .join(". ")
810 }
811 } else {
812 let mut parts = Vec::new();
814 for r in 0..n_data {
815 for (c, col_name) in columns.iter().enumerate().skip(1) {
816 parts.push(format!(
817 "{}, {} = {}",
818 data(r, 0).trim(),
819 col_name.trim(),
820 data(r, c).trim()
821 ));
822 }
823 }
824 parts.join(". ")
825 };
826 if !text.is_empty() {
827 return text;
828 }
829
830 (0..n_data)
833 .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
834 .map(|(r, c)| data(r, c).trim())
835 .filter(|s| !s.is_empty())
836 .collect::<Vec<_>>()
837 .join(". ")
838}
839
840fn inline_segments(md: &str) -> Vec<String> {
848 inline_segments_tagged(md)
849 .into_iter()
850 .map(|(t, _)| t)
851 .collect()
852}
853
854fn inline_segments_tagged(md: &str) -> Vec<(String, bool)> {
858 let chars: Vec<char> = md.chars().collect();
859 let n = chars.len();
860 let find = |from: usize, pat: &str| -> Option<usize> {
861 let hay: String = chars[from..].iter().collect();
862 hay.find(pat).map(|p| from + hay[..p].chars().count())
863 };
864 let mut out: Vec<(String, bool)> = Vec::new();
865 let mut plain = String::new();
866 let mut after_span = false;
867
868 fn flush(
869 out: &mut Vec<(String, bool)>,
870 plain: &mut String,
871 before_span: bool,
872 after_span: bool,
873 ) {
874 let mut p = std::mem::take(plain);
875 if after_span {
876 if let Some(rest) = p.strip_prefix(' ') {
877 p = rest.to_string();
878 }
879 }
880 if before_span {
881 if let Some(rest) = p.strip_suffix(' ') {
882 p = rest.to_string();
883 }
884 }
885 if !p.is_empty() {
886 out.push((unescape_text(&p), true));
887 }
888 }
889
890 let mut i = 0;
891 while i < n {
892 let rest: String = chars[i..].iter().collect();
893 if chars[i] == '[' && !rest.starts_with("[](") {
897 let balanced = |c: usize| {
901 let mut d = 0i32;
902 for &ch in &chars[i + 1..c] {
903 match ch {
904 '[' => d += 1,
905 ']' => d -= 1,
906 _ => {}
907 }
908 }
909 d == 0
910 };
911 if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
912 let mut depth = 0usize;
913 let mut url_end = None;
914 for (k, &c) in chars.iter().enumerate().skip(close + 2) {
915 match c {
916 '(' => depth += 1,
917 ')' => {
918 if depth == 0 {
919 url_end = Some(k);
920 break;
921 }
922 depth -= 1;
923 }
924 _ => {}
925 }
926 }
927 if let Some(endp) = url_end {
928 flush(&mut out, &mut plain, true, after_span);
929 out.push((
930 unescape_text(&chars[i..=endp].iter().collect::<String>()),
931 false,
932 ));
933 i = endp + 1;
934 after_span = true;
935 continue;
936 }
937 }
938 }
939 let mut matched = false;
942 for marker in ["***", "**", "*", "~~", "`"] {
943 if rest.starts_with(marker) {
944 let mlen = marker.chars().count();
945 if let Some(end) = find(i + mlen, marker) {
946 let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
950 if end > i + mlen && !inner_blank {
951 flush(&mut out, &mut plain, true, after_span);
952 if marker == "`" {
953 let inner: String = chars[i + 1..end].iter().collect();
954 out.push((format!("```\n{}\n```", unescape_text(&inner)), false));
955 } else {
956 out.push((
957 unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
958 false,
959 ));
960 }
961 i = end + mlen;
962 after_span = true;
963 matched = true;
964 }
965 }
966 break;
967 }
968 }
969 if matched {
970 continue;
971 }
972 if rest.starts_with("$$") {
975 plain.push_str("$$");
976 i += 2;
977 continue;
978 }
979 if chars[i] == '$' {
981 if let Some(end) = find(i + 1, "$") {
982 if end > i + 1 {
983 flush(&mut out, &mut plain, true, after_span);
984 let latex: String = chars[i + 1..end].iter().collect();
985 out.push((format!("$${latex}$$"), false));
986 i = end + 1;
987 after_span = true;
988 continue;
989 }
990 }
991 }
992 plain.push(chars[i]);
993 i += 1;
994 }
995 flush(&mut out, &mut plain, false, after_span);
996 if out.is_empty() {
997 out.push((unescape_text(md), true));
998 }
999 out
1000}
1001
1002fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1007 let target = segment.trim();
1008 if target.is_empty() {
1009 return None;
1010 }
1011 let plainish =
1012 |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1013 let fully_plain =
1014 |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1015 let unmarked: Vec<(&str, bool)> = runs
1016 .iter()
1017 .filter(|r| plainish(r))
1018 .map(|r| (r.text.as_str(), fully_plain(r)))
1019 .collect();
1020 for start in 0..unmarked.len() {
1021 let mut rest = target;
1022 let mut taken: Vec<(String, bool)> = Vec::new();
1023 for (t, fully) in &unmarked[start..] {
1024 let t = t.trim();
1025 if t.is_empty() {
1026 continue;
1027 }
1028 match rest.strip_prefix(t) {
1029 Some(r) => {
1030 taken.push((unescape_text(t), *fully));
1031 rest = r.trim_start();
1032 if rest.is_empty() {
1033 break;
1034 }
1035 }
1036 None => break,
1037 }
1038 }
1039 if rest.is_empty() && taken.len() >= 2 {
1040 let mut merged: Vec<(String, bool)> = Vec::new();
1045 for (t, fully) in taken {
1046 match merged.last_mut() {
1047 Some((last, true)) if fully => {
1048 last.push(' ');
1049 last.push_str(&t);
1050 }
1051 _ => merged.push((t, fully)),
1052 }
1053 }
1054 if merged.len() >= 2 {
1055 return Some(merged.into_iter().map(|(t, _)| t).collect());
1056 }
1057 return None;
1058 }
1059 }
1060 None
1061}
1062
1063fn cell_chunk_text(t: &Table, r: usize, c: usize) -> String {
1070 if let Some(blocks) = t
1071 .cell_blocks
1072 .as_ref()
1073 .and_then(|b| b.get(r))
1074 .and_then(|row| row.get(c))
1075 .filter(|b| !b.is_empty())
1076 {
1077 let mut parts: Vec<String> = Vec::new();
1078 for node in blocks.iter() {
1079 let part = block_chunk_text(node);
1080 if !part.is_empty() {
1081 parts.push(part);
1082 }
1083 }
1084 return parts.join("\n\n");
1085 }
1086 let flat = t
1087 .rows
1088 .get(r)
1089 .and_then(|row| row.get(c))
1090 .map(String::as_str)
1091 .unwrap_or("");
1092 unescape_text(flat)
1093 .replace("<!-- image -->", "")
1094 .trim()
1095 .to_string()
1096}
1097
1098fn block_chunk_text(node: &Node) -> String {
1100 match node {
1101 Node::Paragraph { text } => unescape_text(text),
1102 Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1103 Node::Code { text, .. } => format!("```\n{}\n```", unescape_text(text)),
1104 Node::Table(inner) => triplet_table_text(inner),
1105 Node::Picture { caption, .. } => caption
1106 .as_deref()
1107 .filter(|c| !c.is_empty())
1108 .map(unescape_text)
1109 .unwrap_or_default(),
1110 Node::ListItem {
1111 ordered,
1112 number,
1113 text,
1114 ..
1115 } => {
1116 let marker = if *ordered {
1117 format!("{number}.")
1118 } else {
1119 "-".to_string()
1120 };
1121 format!("{marker} {}", unescape_text(text))
1122 }
1123 Node::CheckboxItem { checked, text } => {
1124 let mark = if *checked { "- [x] " } else { "- [ ] " };
1125 format!("{mark}{}", unescape_text(text))
1126 }
1127 Node::Heading { text, .. } => unescape_text(text),
1128 Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Commented { inner, .. } => {
1129 block_chunk_text(inner)
1130 }
1131 Node::Group { layer: Some(_), .. } => String::new(),
1132 Node::Group { children, .. } => children
1133 .iter()
1134 .map(block_chunk_text)
1135 .filter(|s| !s.is_empty())
1136 .collect::<Vec<_>>()
1137 .join("\n"),
1138 _ => String::new(),
1139 }
1140}
1141
1142fn unescape_text(s: &str) -> String {
1145 s.replace("<", "<")
1146 .replace(">", ">")
1147 .replace("&", "&")
1148 .replace("\\_", "_")
1149}
1150
1151pub trait ChunkTokenizer {
1157 fn count_tokens(&self, text: &str) -> usize;
1159 fn max_tokens(&self) -> usize;
1161}
1162
1163pub struct HybridChunker<T: ChunkTokenizer> {
1167 tokenizer: T,
1168 merge_peers: bool,
1169}
1170
1171impl<T: ChunkTokenizer> HybridChunker<T> {
1172 pub fn new(tokenizer: T) -> Self {
1173 Self {
1174 tokenizer,
1175 merge_peers: true,
1176 }
1177 }
1178
1179 pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1181 self.merge_peers = merge_peers;
1182 self
1183 }
1184
1185 pub fn max_tokens(&self) -> usize {
1186 self.tokenizer.max_tokens()
1187 }
1188
1189 pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1191 let mut chunks = Vec::new();
1192 self.chunk_with(doc, &mut |c| {
1193 chunks.push(c);
1194 true
1195 });
1196 chunks
1197 }
1198
1199 pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1206 let mut merger = PeerMerger::default();
1207 let mut alive = true;
1208 HierarchicalChunker.chunk_with(doc, &mut |c| {
1209 for split in self.split_by_doc_items(c) {
1210 for chunk in self.split_using_plain_text(split) {
1211 if !alive {
1212 return false;
1213 }
1214 alive = if self.merge_peers {
1215 self.merge_push(&mut merger, chunk, sink)
1216 } else {
1217 sink(chunk)
1218 };
1219 }
1220 }
1221 alive
1222 });
1223 if alive {
1224 self.merge_flush(&mut merger, sink);
1225 }
1226 }
1227
1228 fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1229 self.tokenizer.count_tokens(&contextualize(chunk))
1230 }
1231
1232 fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1235 let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1236 let text = if chunk.doc_items.len() == 1 {
1237 chunk.text.clone()
1238 } else {
1239 doc_items
1240 .iter()
1241 .filter(|it| !it.text.is_empty())
1242 .map(|it| it.text.as_str())
1243 .collect::<Vec<_>>()
1244 .join("\n")
1245 };
1246 DocChunk {
1247 text,
1248 headings: chunk.headings.clone(),
1249 doc_items,
1250 }
1251 }
1252
1253 fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1254 if chunk.doc_items.is_empty() {
1255 return vec![chunk];
1256 }
1257 let max = self.max_tokens();
1258 let num_items = chunk.doc_items.len();
1259 let mut chunks = Vec::new();
1260 let mut window_start = 0usize;
1261 let mut window_end = 0usize; while window_end < num_items {
1263 let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1264 if self.count_chunk_tokens(&new_chunk) <= max {
1265 if window_end < num_items - 1 {
1266 window_end += 1;
1267 continue;
1268 } else {
1269 window_end = num_items; }
1271 } else if window_start == window_end {
1272 window_end += 1;
1275 window_start = window_end;
1276 } else {
1277 new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1280 window_start = window_end;
1281 }
1282 chunks.push(new_chunk);
1283 }
1284 chunks
1285 }
1286
1287 fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1288 let total = self.count_chunk_tokens(&chunk);
1289 let max = self.max_tokens();
1290 if total <= max {
1291 return vec![chunk];
1292 }
1293 let text_len = self.tokenizer.count_tokens(&chunk.text);
1294 let other_len = total - text_len;
1295 if other_len >= max {
1296 let stripped = DocChunk {
1298 headings: None,
1299 ..chunk
1300 };
1301 return self.split_using_plain_text(stripped);
1302 }
1303 let available = max - other_len;
1304
1305 let segments =
1306 if chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table {
1307 let lines: Vec<String> = chunk
1314 .text
1315 .split('\n')
1316 .filter(|l| !l.trim().is_empty())
1317 .map(|l| l.to_string())
1318 .collect();
1319 line_chunk_text(&lines, &self.tokenizer, max)
1320 } else {
1321 semchunk(&chunk.text, available, &self.tokenizer)
1322 };
1323 segments
1324 .into_iter()
1325 .map(|s| DocChunk {
1326 text: s,
1327 headings: chunk.headings.clone(),
1328 doc_items: chunk.doc_items.clone(),
1329 })
1330 .collect()
1331 }
1332
1333 fn merge_push(
1339 &self,
1340 m: &mut PeerMerger,
1341 chunk: DocChunk,
1342 sink: &mut dyn FnMut(DocChunk) -> bool,
1343 ) -> bool {
1344 if m.window.is_empty() {
1345 m.window.push(chunk);
1346 return true;
1347 }
1348 let candidate = DocChunk {
1349 text: m
1350 .window
1351 .iter()
1352 .map(|c| c.text.as_str())
1353 .chain([chunk.text.as_str()])
1354 .collect::<Vec<_>>()
1355 .join("\n"),
1356 headings: m.window[0].headings.clone(),
1357 doc_items: m
1358 .window
1359 .iter()
1360 .flat_map(|c| c.doc_items.iter().cloned())
1361 .chain(chunk.doc_items.iter().cloned())
1362 .collect(),
1363 };
1364 if chunk.headings == m.window[0].headings
1365 && self.count_chunk_tokens(&candidate) <= self.max_tokens()
1366 {
1367 m.window.push(chunk);
1368 m.merged = Some(candidate);
1369 true
1370 } else {
1371 let alive = self.merge_flush(m, sink);
1372 m.window.push(chunk);
1373 alive
1374 }
1375 }
1376
1377 fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
1381 let alive = if m.window.len() == 1 {
1382 sink(m.window.pop().expect("single-chunk window"))
1383 } else if !m.window.is_empty() {
1384 m.window.clear();
1385 sink(m.merged.take().expect("multi-chunk window has a merge"))
1386 } else {
1387 true
1388 };
1389 m.merged = None;
1390 alive
1391 }
1392}
1393
1394#[derive(Default)]
1396struct PeerMerger {
1397 window: Vec<DocChunk>,
1398 merged: Option<DocChunk>,
1399}
1400
1401fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
1411 let mut chunks: Vec<String> = Vec::new();
1412 let mut current = String::new();
1413 let mut current_len = 0usize;
1414
1415 for line in lines {
1416 let mut remaining: Vec<char> = line.chars().collect();
1417 loop {
1418 let rem_str: String = remaining.iter().collect();
1419 let line_tokens = tok.count_tokens(&rem_str);
1420 let available = max_tokens.saturating_sub(current_len);
1421
1422 if line_tokens <= available {
1423 current.push_str(&rem_str);
1424 current_len += line_tokens;
1425 break;
1426 }
1427 if line_tokens <= max_tokens {
1428 chunks.push(std::mem::take(&mut current));
1429 current_len = 0;
1430 continue;
1431 }
1432 let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
1434 let mut rest = rest;
1435 if take.is_empty() {
1436 if rest.is_empty() {
1437 break;
1438 }
1439 take = rest[..1].iter().collect();
1440 rest = rest[1..].to_vec();
1441 }
1442 current.push('\n');
1443 current.push_str(&take);
1444 chunks.push(std::mem::take(&mut current));
1445 current_len = 0;
1446 remaining = rest;
1447 }
1448 }
1449 if !current.is_empty() {
1450 chunks.push(current);
1451 }
1452 chunks
1453}
1454
1455fn split_by_token_limit<T: ChunkTokenizer>(
1459 text: &[char],
1460 token_limit: usize,
1461 tok: &T,
1462) -> (String, Vec<char>) {
1463 if token_limit == 0 || text.is_empty() {
1464 return (String::new(), text.to_vec());
1465 }
1466 let full: String = text.iter().collect();
1467 if tok.count_tokens(&full) <= token_limit {
1468 return (full, Vec::new());
1469 }
1470 let (mut lo, mut hi) = (0usize, text.len());
1471 let mut best: Option<usize> = None;
1472 while lo <= hi {
1473 let mid = (lo + hi) / 2;
1474 let head: String = text[..mid].iter().collect();
1475 if tok.count_tokens(&head) <= token_limit {
1476 best = Some(mid);
1477 lo = mid + 1;
1478 } else {
1479 if mid == 0 {
1480 break;
1481 }
1482 hi = mid - 1;
1483 }
1484 }
1485 let mut best_idx = match best {
1486 Some(b) if b > 0 => b,
1487 _ => return (String::new(), text.to_vec()),
1488 };
1489 if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
1491 if pos > 0 {
1492 best_idx = pos;
1493 }
1494 }
1495 (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
1496}
1497
1498const NON_WS_SPLITTERS: &[&str] = &[
1504 ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
1505 "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
1506];
1507
1508pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
1512 let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
1513 let mut counter = |s: &str| -> usize {
1514 if let Some(n) = cache.get(s) {
1515 return *n;
1516 }
1517 let n = tok.count_tokens(s);
1518 cache.insert(s.to_string(), n);
1519 n
1520 };
1521 let chunks = semchunk_rec(text, chunk_size, &mut counter);
1522 chunks
1524 .into_iter()
1525 .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
1526 .collect()
1527}
1528
1529fn semchunk_rec(
1532 text: &str,
1533 chunk_size: usize,
1534 counter: &mut dyn FnMut(&str) -> usize,
1535) -> Vec<String> {
1536 let (splitter, splitter_is_ws, splits) = split_text(text);
1537
1538 let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
1539 let mut cum_lens = Vec::with_capacity(splits.len() + 1);
1540 cum_lens.push(0usize);
1541 for l in &split_lens {
1542 cum_lens.push(cum_lens.last().unwrap() + l);
1543 }
1544 let num_splits_plus_one = splits.len() + 1;
1545
1546 let mut chunks: Vec<String> = Vec::new();
1547 let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
1548
1549 for i in 0..splits.len() {
1550 if skips.contains(&i) {
1551 continue;
1552 }
1553 let split = &splits[i];
1554 if counter(split) > chunk_size {
1555 let inner = semchunk_rec(split, chunk_size, counter);
1556 chunks.extend(inner);
1557 } else {
1558 let (end, merged) = merge_splits(
1559 &splits,
1560 &cum_lens,
1561 chunk_size,
1562 &splitter,
1563 counter,
1564 i,
1565 num_splits_plus_one,
1566 );
1567 for j in (i + 1)..end {
1568 skips.insert(j);
1569 }
1570 chunks.push(merged);
1571 }
1572 let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
1575 if !splitter_is_ws && !is_last {
1576 let with_splitter = format!(
1577 "{}{}",
1578 chunks.last().map(String::as_str).unwrap_or(""),
1579 splitter
1580 );
1581 if counter(&with_splitter) <= chunk_size {
1582 if let Some(last) = chunks.last_mut() {
1583 *last = with_splitter;
1584 } else {
1585 chunks.push(with_splitter);
1586 }
1587 } else {
1588 chunks.push(splitter.clone());
1589 }
1590 }
1591 }
1592 chunks
1593}
1594
1595fn merge_splits(
1598 splits: &[String],
1599 cum_lens: &[usize],
1600 chunk_size: usize,
1601 splitter: &str,
1602 counter: &mut dyn FnMut(&str) -> usize,
1603 start: usize,
1604 high_init: usize,
1605) -> (usize, String) {
1606 let mut average = 0.2f64;
1607 let mut low = start;
1608 let mut high = high_init;
1609 let offset = cum_lens[start];
1610 let mut target = offset as f64 + (chunk_size as f64 * average);
1611
1612 while low < high {
1613 let i = bisect_left(cum_lens, target, low, high);
1614 let midpoint = i.min(high - 1);
1615 let joined = splits[start..midpoint.max(start)].join(splitter);
1616 let tokens = counter(&joined);
1617 let local_cum = cum_lens[midpoint] - offset;
1618 if local_cum > 0 && tokens > 0 {
1619 average = local_cum as f64 / tokens as f64;
1620 target = offset as f64 + (chunk_size as f64 * average);
1621 }
1622 if tokens > chunk_size {
1623 high = midpoint;
1624 } else {
1625 low = midpoint + 1;
1626 }
1627 }
1628 let end = low - 1;
1629 (end, splits[start..end.max(start)].join(splitter))
1630}
1631
1632fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
1633 while low < high {
1634 let mid = (low + high) / 2;
1635 if (sorted[mid] as f64) < target {
1636 low = mid + 1;
1637 } else {
1638 high = mid;
1639 }
1640 }
1641 low
1642}
1643
1644fn split_text(text: &str) -> (String, bool, Vec<String>) {
1646 if text.contains('\n') || text.contains('\r') {
1648 let splitter = longest_run(text, |c| c == '\n' || c == '\r');
1649 return (splitter.clone(), true, split_on(text, &splitter));
1650 }
1651 if text.contains('\t') {
1653 let splitter = longest_run(text, |c| c == '\t');
1654 return (splitter.clone(), true, split_on(text, &splitter));
1655 }
1656 if text.chars().any(char::is_whitespace) {
1658 let splitter = longest_run(text, char::is_whitespace);
1659 if splitter.chars().count() == 1 {
1660 for preceder in NON_WS_SPLITTERS {
1662 if let Some((ws, parts)) = split_after_preceder(text, preceder) {
1663 return (ws, true, parts);
1664 }
1665 }
1666 }
1667 return (splitter.clone(), true, split_on(text, &splitter));
1668 }
1669 for s in NON_WS_SPLITTERS {
1671 if text.contains(s) {
1672 return (s.to_string(), false, split_on(text, s));
1673 }
1674 }
1675 (
1677 String::new(),
1678 true,
1679 text.chars().map(|c| c.to_string()).collect(),
1680 )
1681}
1682
1683fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
1685 let mut best = String::new();
1686 let mut cur = String::new();
1687 for c in text.chars() {
1688 if pred(c) {
1689 cur.push(c);
1690 } else {
1691 if cur.chars().count() > best.chars().count() {
1692 best = cur.clone();
1693 }
1694 cur.clear();
1695 }
1696 }
1697 if cur.chars().count() > best.chars().count() {
1698 best = cur;
1699 }
1700 best
1701}
1702
1703fn split_on(text: &str, splitter: &str) -> Vec<String> {
1704 text.split(splitter).map(str::to_string).collect()
1705}
1706
1707fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
1711 let chars: Vec<char> = text.chars().collect();
1712 let p: Vec<char> = preceder.chars().collect();
1713 let mut ws: Option<char> = None;
1714 for i in p.len()..chars.len() {
1715 if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
1716 ws = Some(chars[i]);
1717 break;
1718 }
1719 }
1720 let ws = ws?;
1721 let mut parts = Vec::new();
1722 let mut cur = String::new();
1723 let mut i = 0usize;
1724 while i < chars.len() {
1725 if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
1726 parts.push(std::mem::take(&mut cur));
1727 i += 1;
1728 continue;
1729 }
1730 cur.push(chars[i]);
1731 i += 1;
1732 }
1733 parts.push(cur);
1734 Some((ws.to_string(), parts))
1735}
1736
1737#[cfg(feature = "chunking")]
1742mod hf {
1743 use super::ChunkTokenizer;
1744
1745 pub const DEFAULT_TOKENIZER_PATH: &str = ".models/chunk/tokenizer.json";
1750
1751 pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
1756 if let Some(p) = explicit {
1757 return Ok(p.to_string());
1758 }
1759 let resolved = crate::assets::resolve(DEFAULT_TOKENIZER_PATH);
1760 if std::path::Path::new(&resolved).exists() {
1761 return Ok(resolved);
1762 }
1763 Err(format!(
1764 "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
1765 {DEFAULT_TOKENIZER_PATH} does not exist — run \
1766 scripts/install/download_dependencies.sh (or pass an explicit path)"
1767 ))
1768 }
1769
1770 pub struct HuggingFaceTokenizer {
1774 tok: tokenizers::Tokenizer,
1775 max_tokens: usize,
1776 }
1777
1778 impl HuggingFaceTokenizer {
1779 pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
1783 Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
1784 }
1785
1786 pub fn from_file(
1790 path: impl AsRef<std::path::Path>,
1791 max_tokens: usize,
1792 ) -> Result<Self, String> {
1793 let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
1794 .map_err(|e| format!("failed to load tokenizer: {e}"))?;
1795 let _ = tok.with_truncation(None);
1800 tok.with_padding(None);
1801 Ok(Self { tok, max_tokens })
1802 }
1803 }
1804
1805 impl ChunkTokenizer for HuggingFaceTokenizer {
1806 fn count_tokens(&self, text: &str) -> usize {
1807 self.tok
1808 .encode(text, false)
1809 .map(|e| e.get_tokens().len())
1810 .unwrap_or(0)
1811 }
1812 fn max_tokens(&self) -> usize {
1813 self.max_tokens
1814 }
1815 }
1816}
1817
1818#[cfg(feature = "chunking")]
1819pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
1820
1821#[cfg(feature = "chunking")]
1826mod window {
1827 use super::DocChunk;
1828 use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
1829
1830 #[derive(Debug, Clone, Default)]
1832 pub struct Section {
1833 pub heading_path: Vec<String>,
1836 pub words: Vec<String>,
1838 }
1839
1840 impl Section {
1841 pub fn heading_context(&self) -> String {
1844 if self.heading_path.is_empty() {
1845 String::new()
1846 } else {
1847 format!("# {}", self.heading_path.join(" > "))
1848 }
1849 }
1850 }
1851
1852 fn level_index(level: HeadingLevel) -> usize {
1853 match level {
1854 HeadingLevel::H1 => 1,
1855 HeadingLevel::H2 => 2,
1856 HeadingLevel::H3 => 3,
1857 HeadingLevel::H4 => 4,
1858 HeadingLevel::H5 => 5,
1859 HeadingLevel::H6 => 6,
1860 }
1861 }
1862
1863 pub fn parse_sections(markdown: &str) -> Vec<Section> {
1867 parse_sections_with_stack(markdown, Vec::new()).0
1868 }
1869
1870 pub fn parse_sections_with_stack(
1875 markdown: &str,
1876 initial_stack: Vec<String>,
1877 ) -> (Vec<Section>, Vec<String>) {
1878 let mut heading_stack: Vec<String> = initial_stack;
1879 let mut sections: Vec<Section> = Vec::new();
1880 let mut current = Section {
1883 heading_path: heading_stack
1884 .iter()
1885 .filter(|h| !h.is_empty())
1886 .cloned()
1887 .collect(),
1888 words: Vec::new(),
1889 };
1890
1891 let mut in_heading = false;
1892 let mut heading_level = 0usize;
1893 let mut heading_buf = String::new();
1894
1895 let push_words = |section: &mut Section, text: &str| {
1896 for w in text.split_whitespace() {
1897 section.words.push(w.to_string());
1898 }
1899 };
1900
1901 let flush = |sections: &mut Vec<Section>, section: &mut Section| {
1902 if !section.words.is_empty() {
1903 sections.push(std::mem::take(section));
1904 } else {
1905 *section = Section::default();
1906 }
1907 };
1908
1909 for event in Parser::new(markdown) {
1910 match event {
1911 Event::Start(Tag::Heading { level, .. }) => {
1912 in_heading = true;
1913 heading_level = level_index(level);
1914 heading_buf.clear();
1915 }
1916 Event::End(TagEnd::Heading(_)) => {
1917 in_heading = false;
1918 let idx = heading_level.saturating_sub(1);
1920 if heading_stack.len() <= idx {
1921 heading_stack.resize(idx + 1, String::new());
1922 } else {
1923 heading_stack.truncate(idx + 1);
1924 }
1925 heading_stack[idx] = heading_buf.trim().to_string();
1926 flush(&mut sections, &mut current);
1928 current.heading_path = heading_stack
1929 .iter()
1930 .filter(|h| !h.is_empty())
1931 .cloned()
1932 .collect();
1933 }
1934 Event::Text(t) | Event::Code(t) => {
1935 if in_heading {
1936 if !heading_buf.is_empty() {
1937 heading_buf.push(' ');
1938 }
1939 heading_buf.push_str(&t);
1940 } else {
1941 push_words(&mut current, &t);
1942 }
1943 }
1944 Event::SoftBreak | Event::HardBreak | Event::Rule => {}
1946 _ => {}
1947 }
1948 }
1949 flush(&mut sections, &mut current);
1950 (sections, heading_stack)
1951 }
1952
1953 #[derive(Debug, Clone)]
1959 pub struct WindowChunker {
1960 pub max_words: usize,
1962 pub overlap: f32,
1964 }
1965
1966 impl Default for WindowChunker {
1967 fn default() -> Self {
1968 WindowChunker {
1969 max_words: 300,
1970 overlap: 0.05,
1971 }
1972 }
1973 }
1974
1975 impl WindowChunker {
1976 pub fn new(max_words: usize, overlap: f32) -> Self {
1977 WindowChunker { max_words, overlap }
1978 }
1979
1980 fn word_budget(&self) -> usize {
1982 self.max_words.max(1)
1983 }
1984
1985 fn overlap_words(&self, budget: usize) -> usize {
1988 let o = (budget as f32 * self.overlap).round() as usize;
1989 o.min(budget.saturating_sub(1))
1990 }
1991
1992 pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
1994 let mut chunks = Vec::new();
1995 self.chunk_with(markdown, &mut |c| {
1996 chunks.push(c);
1997 true
1998 });
1999 chunks
2000 }
2001
2002 pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2006 let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2007 for section in §ions {
2008 if !self.pack_section(section, sink) {
2009 return;
2010 }
2011 }
2012 }
2013
2014 pub fn pack_section(
2018 &self,
2019 section: &Section,
2020 sink: &mut dyn FnMut(DocChunk) -> bool,
2021 ) -> bool {
2022 let words = §ion.words;
2023 if words.is_empty() {
2024 return true;
2025 }
2026 let budget = self.word_budget();
2027 let step = budget - self.overlap_words(budget); let mut start = 0;
2029 loop {
2030 let end = (start + budget).min(words.len());
2031 let chunk = DocChunk {
2032 text: words[start..end].join(" "),
2033 headings: (!section.heading_path.is_empty())
2034 .then(|| section.heading_path.clone()),
2035 doc_items: Vec::new(),
2036 };
2037 if !sink(chunk) {
2038 return false;
2039 }
2040 if end >= words.len() {
2041 return true;
2042 }
2043 start += step;
2044 }
2045 }
2046
2047 pub fn contextualize(chunk: &DocChunk) -> String {
2053 match &chunk.headings {
2054 Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2055 _ => chunk.text.clone(),
2056 }
2057 }
2058 }
2059
2060 #[cfg(test)]
2061 mod tests {
2062 use super::*;
2063
2064 #[test]
2065 fn splits_on_headings_and_tracks_path() {
2066 let md = "\
2067intro words
2068# Chapter 1
2069para one
2070## Section 1.1
2071para two
2072# Chapter 2
2073para three";
2074 let secs = parse_sections(md);
2075 assert_eq!(secs.len(), 4);
2077 assert!(secs[0].heading_path.is_empty());
2078 assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2079 assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2080 assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2082 }
2083
2084 #[test]
2085 fn strips_markup_to_plain_words() {
2086 let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2087 let secs = parse_sections(md);
2088 let words = &secs[0].words;
2089 assert!(words.contains(&"bold".to_string()));
2090 assert!(words.contains(&"code".to_string()));
2091 assert!(words.contains(&"link".to_string()));
2092 assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2094 }
2095
2096 #[test]
2097 fn windows_overlap_and_never_cross_headings() {
2098 let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2099 let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2100 let chunker = WindowChunker::new(10, 0.2); let chunks = chunker.chunk(&md);
2102 let a: Vec<_> = chunks
2104 .iter()
2105 .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2106 .collect();
2107 assert_eq!(a.len(), 3);
2108 assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2109 assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2110 assert!(a[2].text.ends_with(" w24"));
2111 let b: Vec<_> = chunks
2113 .iter()
2114 .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2115 .collect();
2116 assert_eq!(b.len(), 1);
2117 assert_eq!(b[0].text, "short tail");
2118 assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2119 }
2120
2121 #[test]
2122 fn sink_false_cancels_the_window_walk() {
2123 let md = format!(
2124 "# A\n\n{}\n",
2125 (0..50)
2126 .map(|i| format!("w{i}"))
2127 .collect::<Vec<_>>()
2128 .join(" ")
2129 );
2130 let chunker = WindowChunker::new(10, 0.0);
2131 let mut n = 0;
2132 chunker.chunk_with(&md, &mut |_| {
2133 n += 1;
2134 false
2135 });
2136 assert_eq!(n, 1);
2137 }
2138 }
2139}
2140
2141#[cfg(feature = "chunking")]
2142pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2143
2144#[cfg(test)]
2145mod tests {
2146 use super::*;
2147
2148 struct WordTok(usize);
2150 impl ChunkTokenizer for WordTok {
2151 fn count_tokens(&self, text: &str) -> usize {
2152 text.split_whitespace().count()
2153 }
2154 fn max_tokens(&self) -> usize {
2155 self.0
2156 }
2157 }
2158
2159 fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2160 let mut d = DoclingDocument::new("t");
2161 for n in nodes {
2162 d.push(n);
2163 }
2164 d
2165 }
2166
2167 #[test]
2168 fn hierarchical_headings_and_items() {
2169 let doc = doc_with(vec![
2170 Node::Heading {
2171 level: 1,
2172 text: "Title".into(),
2173 },
2174 Node::Paragraph {
2175 text: "Intro".into(),
2176 },
2177 Node::Heading {
2178 level: 2,
2179 text: "Sec".into(),
2180 },
2181 Node::Paragraph {
2182 text: "Body".into(),
2183 },
2184 ]);
2185 let chunks = HierarchicalChunker.chunk(&doc);
2186 assert_eq!(chunks.len(), 2);
2187 assert_eq!(chunks[0].text, "Intro");
2188 assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2189 assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2190 assert_eq!(
2191 chunks[1].headings.as_deref(),
2192 Some(&["Title".into(), "Sec".into()][..])
2193 );
2194 assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
2195 }
2196
2197 #[test]
2200 fn page_furniture_keeps_refs_aligned_with_json() {
2201 let doc = doc_with(vec![
2202 Node::Paragraph {
2203 text: "Before".into(),
2204 },
2205 Node::PageFurniture {
2206 footer: true,
2207 location: [0, 490, 100, 512],
2208 text: "1.10.2".into(),
2209 },
2210 Node::Paragraph {
2211 text: "After".into(),
2212 },
2213 ]);
2214 let chunks = HierarchicalChunker.chunk(&doc);
2215 assert_eq!(chunks.len(), 2);
2216 assert_eq!(chunks[1].text, "After");
2217 let json: serde_json::Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2218 assert_eq!(json["texts"][2]["text"], "After");
2219 assert_eq!(chunks[1].doc_items[0].self_ref, "#/texts/2");
2220 }
2221
2222 #[test]
2223 fn heading_shadowing_prunes_deeper_levels() {
2224 let doc = doc_with(vec![
2225 Node::Heading {
2226 level: 2,
2227 text: "A".into(),
2228 },
2229 Node::Heading {
2230 level: 3,
2231 text: "A.1".into(),
2232 },
2233 Node::Heading {
2234 level: 2,
2235 text: "B".into(),
2236 },
2237 Node::Paragraph { text: "p".into() },
2238 ]);
2239 let chunks = HierarchicalChunker.chunk(&doc);
2240 assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
2241 }
2242
2243 #[test]
2244 fn triplet_table() {
2245 let t = Table {
2246 rows: vec![
2247 vec!["".into(), "Col1".into()],
2248 vec!["Row1".into(), "v".into()],
2249 ],
2250 ..Default::default()
2251 };
2252 assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
2253 let single = Table {
2256 rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
2257 ..Default::default()
2258 };
2259 assert_eq!(triplet_table_text(&single), "a = b");
2260 }
2261
2262 #[test]
2263 fn hybrid_merges_small_peers_and_splits_large() {
2264 let doc = doc_with(vec![
2265 Node::Heading {
2266 level: 2,
2267 text: "S".into(),
2268 },
2269 Node::Paragraph { text: "a b".into() },
2270 Node::Paragraph { text: "c d".into() },
2271 ]);
2272 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2273 assert_eq!(chunks.len(), 1, "peers under one heading merge");
2274 assert_eq!(chunks[0].text, "a b\nc d");
2275
2276 let long = "w ".repeat(40).trim().to_string();
2277 let doc = doc_with(vec![Node::Paragraph { text: long }]);
2278 let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
2279 assert!(chunks.len() > 1, "oversized paragraph splits");
2280 for c in &chunks {
2281 assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
2282 }
2283 }
2284
2285 #[test]
2286 fn semchunk_prefers_newlines_then_sentences() {
2287 let tok = WordTok(4);
2288 let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
2289 assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
2290 }
2291}