1use serde_json::{json, Value};
12
13use crate::document::{CaptionParent, ContentLayer, DoclingDocument, Node, Table};
14
15const SCHEMA_VERSION: &str = "1.10.0";
16
17const CODE_LANGUAGES: &[&str] = &[
20 "Ada",
21 "Awk",
22 "Bash",
23 "bc",
24 "C",
25 "C#",
26 "C++",
27 "CMake",
28 "COBOL",
29 "CSS",
30 "Ceylon",
31 "Clojure",
32 "Crystal",
33 "Cuda",
34 "Cython",
35 "D",
36 "Dart",
37 "dc",
38 "Dockerfile",
39 "DocLang",
40 "Elixir",
41 "Erlang",
42 "FORTRAN",
43 "Forth",
44 "Go",
45 "HTML",
46 "Haskell",
47 "Haxe",
48 "Java",
49 "JavaScript",
50 "JSON",
51 "Julia",
52 "Kotlin",
53 "Latex",
54 "Lisp",
55 "Lua",
56 "Matlab",
57 "MoonScript",
58 "Nim",
59 "OCaml",
60 "ObjectiveC",
61 "Octave",
62 "PHP",
63 "Pascal",
64 "Perl",
65 "Prolog",
66 "Python",
67 "Racket",
68 "Ruby",
69 "Rust",
70 "SML",
71 "SQL",
72 "Scala",
73 "Scheme",
74 "Swift",
75 "Tikz",
76 "TypeScript",
77 "VisualBasic",
78 "XML",
79 "YAML",
80];
81
82pub fn code_language_label(lang: &str) -> &'static str {
88 code_language(Some(lang))
89}
90
91pub(crate) fn code_language(lang: Option<&str>) -> &'static str {
92 match lang {
93 Some(l) => CODE_LANGUAGES
94 .iter()
95 .find(|c| c.eq_ignore_ascii_case(l))
96 .copied()
97 .unwrap_or("unknown"),
98 None => "unknown",
99 }
100}
101
102#[derive(Clone, Copy)]
106struct ExactProv {
107 page_no: usize,
108 bbox: [f64; 4],
109 bottom_left: bool,
110 charspan: [usize; 2],
111}
112
113impl From<&crate::tree::TreeProv> for ExactProv {
114 fn from(p: &crate::tree::TreeProv) -> Self {
115 ExactProv {
116 page_no: p.page_no,
117 bbox: p.bbox,
118 bottom_left: p.bottom_left,
119 charspan: p.charspan,
120 }
121 }
122}
123
124fn clamp_boxes_to_pages(out: &mut Value, pages: &[(usize, f64, f64)]) {
129 if pages.is_empty() {
130 return;
131 }
132 let size = |page_no: &Value| -> Option<(f64, f64)> {
133 let n = page_no.as_u64()? as usize;
134 pages
135 .iter()
136 .find(|(p, _, _)| *p == n)
137 .map(|(_, w, h)| (*w, *h))
138 };
139 let r2 = |v: f64| (v * 100.0).round() / 100.0;
140 let clamp_bbox = |bbox: &mut Value, (w, h): (f64, f64)| {
141 for (key, hi) in [("l", w), ("r", w), ("t", h), ("b", h)] {
142 if let Some(v) = bbox.get(key).and_then(Value::as_f64) {
143 bbox[key] = json!(r2(v.clamp(0.0, hi.max(0.0))));
144 }
145 }
146 };
147 for bucket in [
148 "texts",
149 "pictures",
150 "tables",
151 "key_value_items",
152 "form_items",
153 "field_regions",
154 "field_items",
155 ] {
156 let Some(items) = out.get_mut(bucket).and_then(Value::as_array_mut) else {
157 continue;
158 };
159 for item in items {
160 let mut table_page: Option<Option<(f64, f64)>> = None;
161 if let Some(provs) = item.get_mut("prov").and_then(Value::as_array_mut) {
162 let mut page_nos: Vec<u64> = Vec::new();
163 for prov in provs.iter_mut() {
164 if let Some(n) = prov.get("page_no").and_then(Value::as_u64) {
165 page_nos.push(n);
166 }
167 let Some(sz) = prov.get("page_no").and_then(size) else {
168 continue;
169 };
170 if let Some(bbox) = prov.get_mut("bbox") {
171 clamp_bbox(bbox, sz);
172 }
173 }
174 page_nos.sort_unstable();
175 page_nos.dedup();
176 if let [only] = page_nos[..] {
177 table_page = Some(size(&json!(only)));
178 }
179 }
180 if let (Some(Some(sz)), Some(data)) = (table_page, item.get_mut("data")) {
182 for key in ["table_cells", "grid"] {
183 let Some(rows) = data.get_mut(key).and_then(Value::as_array_mut) else {
184 continue;
185 };
186 for entry in rows.iter_mut() {
187 let cells: Vec<&mut Value> = match entry {
188 Value::Array(row) => row.iter_mut().collect(),
189 other => vec![other],
190 };
191 for cell in cells {
192 if let Some(bbox) = cell.get_mut("bbox").filter(|b| b.is_object()) {
193 clamp_bbox(bbox, sz);
194 }
195 }
196 }
197 }
198 }
199 }
200 }
201}
202
203fn formatting_json(f: &crate::tree::Formatting) -> Value {
205 json!({
206 "bold": f.bold,
207 "italic": f.italic,
208 "underline": f.underline,
209 "strikethrough": f.strikethrough,
210 "script": match f.script {
211 crate::Script::Baseline => "baseline",
212 crate::Script::Sub => "sub",
213 crate::Script::Super => "super",
214 },
215 })
216}
217
218fn track_json(t: &crate::tree::TreeTrack) -> Value {
221 let mut m = serde_json::Map::new();
222 m.insert("kind".into(), json!("track"));
223 m.insert("start_time".into(), json!(t.start_time));
224 m.insert("end_time".into(), json!(t.end_time));
225 if let Some(id) = &t.identifier {
226 m.insert("identifier".into(), json!(id));
227 }
228 if let Some(v) = &t.voice {
229 m.insert("voice".into(), json!(v));
230 }
231 Value::Object(m)
232}
233
234pub fn to_json(doc: &DoclingDocument) -> Value {
236 let mut b = Builder::default();
237 let body = match &doc.tree {
241 Some(tree) => {
242 for n in &doc.nodes {
245 if let Node::PageInfo {
246 page_no,
247 width,
248 height,
249 } = n
250 {
251 if *page_no > 0 {
252 b.pages.push((*page_no, *width as f64, *height as f64));
253 }
254 }
255 }
256 b.write_tree(tree)
257 }
258 None => b.walk_into(&doc.nodes, "#/body"),
259 };
260 b.link_comments();
261
262 let mut out = json!({
263 "schema_name": "DoclingDocument",
264 "version": SCHEMA_VERSION,
265 "name": doc.name,
266 "origin": {
267 "mimetype": "text/plain",
268 "binary_hash": fnv1a(&doc.name),
269 "filename": doc.name,
270 },
271 "furniture": {
272 "self_ref": "#/furniture",
273 "children": [],
274 "content_layer": "furniture",
275 "name": "_root_",
276 "label": "unspecified",
277 },
278 "body": {
279 "self_ref": "#/body",
280 "children": body,
281 "content_layer": "body",
282 "name": "_root_",
283 "label": "unspecified",
284 },
285 "groups": b.groups,
286 "texts": b.texts,
287 "pictures": b.pictures,
288 "tables": b.tables,
289 "key_value_items": b.key_value_items,
290 "form_items": [],
291 "pages": b.pages.iter().map(|(n, w, h)| {
292 let r2 = |v: f64| (v * 100.0).round() / 100.0;
293 (n.to_string(), json!({
294 "size": { "width": r2(*w), "height": r2(*h) },
295 "page_no": n,
296 }))
297 }).collect::<serde_json::Map<String, Value>>(),
298 });
299
300 clamp_boxes_to_pages(&mut out, &b.pages);
309
310 if !b.field_regions.is_empty() {
315 if let Some(obj) = out.as_object_mut() {
316 let pages = obj.remove("pages");
317 obj.insert("field_regions".into(), Value::Array(b.field_regions));
318 obj.insert("field_items".into(), Value::Array(b.field_items));
319 if let Some(pages) = pages {
320 obj.insert("pages".into(), pages);
321 }
322 }
323 }
324 out
325}
326
327fn classification_meta(classes: &[crate::PictureClass]) -> Value {
334 json!({
335 "classification": {
336 "predictions": classes.iter().map(|c| json!({
337 "confidence": c.confidence as f64,
338 "created_by": "DocumentPictureClassifier",
339 "class_name": c.class_name,
340 })).collect::<Vec<_>>(),
341 },
342 "annotations": [{
343 "kind": "classification",
344 "provenance": "DocumentPictureClassifier",
345 "predicted_classes": classes.iter().map(|c| json!({
346 "class_name": c.class_name,
347 "confidence": c.confidence as f64,
348 })).collect::<Vec<_>>(),
349 }],
350 })
351}
352
353#[allow(clippy::too_many_arguments)]
364fn cell_value(
365 row_span: usize,
366 col_span: usize,
367 start_row: usize,
368 end_row: usize,
369 start_col: usize,
370 end_col: usize,
371 text: String,
372 column_header: bool,
373 row_header: bool,
374 row_section: bool,
375 bbox: Option<[f32; 4]>,
376) -> Value {
377 let mut m = serde_json::Map::with_capacity(12);
378 m.insert("row_span".into(), row_span.into());
379 m.insert("col_span".into(), col_span.into());
380 m.insert("start_row_offset_idx".into(), start_row.into());
381 m.insert("end_row_offset_idx".into(), end_row.into());
382 m.insert("start_col_offset_idx".into(), start_col.into());
383 m.insert("end_col_offset_idx".into(), end_col.into());
384 m.insert("text".into(), Value::String(text));
385 m.insert("column_header".into(), column_header.into());
386 m.insert("row_header".into(), row_header.into());
387 m.insert("row_section".into(), row_section.into());
388 m.insert("fillable".into(), false.into());
389 if let Some(b) = bbox {
390 m.insert(
391 "bbox".into(),
392 json!({
393 "l": b[0], "t": b[1], "r": b[2], "b": b[3],
394 "coord_origin": "TOPLEFT",
395 }),
396 );
397 }
398 Value::Object(m)
399}
400
401fn table_data(t: &Table) -> Value {
404 table_data_with(t, false)
405}
406
407fn table_data_with(t: &Table, raw: bool) -> Value {
410 let cell_text = |s: &str| {
411 if raw {
412 s.to_string()
413 } else {
414 unescape_text(&crate::markdown::strip_hard_breaks(s))
415 }
416 };
417 let mut num_rows = t.rows.len();
418 let mut num_cols = t.rows.iter().map(Vec::len).max().unwrap_or(0);
419 let ragged = t.rows.iter().any(|r| r.len() != num_cols);
427 if let Some(first_class) = t.cells.as_ref().filter(|c| ragged && !c.is_empty()) {
428 for c in first_class {
429 num_rows = num_rows.max(c.start_row + c.row_span);
430 num_cols = num_cols.max(c.start_col + c.col_span);
431 }
432 }
433 let mut grid = Vec::with_capacity(num_rows);
434 let mut cells = Vec::new();
435 let mut slot: Vec<Option<usize>> = vec![None; num_rows * num_cols];
439 if let Some(first_class) = t.cells.as_ref().filter(|c| !c.is_empty()) {
440 for c in first_class {
441 let idx = cells.len();
442 cells.push(cell_value(
443 c.row_span,
444 c.col_span,
445 c.start_row,
446 c.start_row + c.row_span,
447 c.start_col,
448 c.start_col + c.col_span,
449 cell_text(&c.text),
450 c.column_header,
451 c.row_header,
452 c.row_section,
453 c.bbox,
454 ));
455 for r in c.start_row..(c.start_row + c.row_span).min(num_rows) {
456 for k in c.start_col..(c.start_col + c.col_span).min(num_cols) {
457 slot[r * num_cols + k] = Some(idx);
458 }
459 }
460 }
461 for r in 0..num_rows {
462 let mut grid_row = Vec::with_capacity(num_cols);
463 for c in 0..num_cols {
464 grid_row.push(match slot[r * num_cols + c] {
465 Some(i) => cells[i].clone(),
466 None => cell_value(
467 1,
468 1,
469 r,
470 r + 1,
471 c,
472 c + 1,
473 String::new(),
474 false,
475 false,
476 false,
477 None,
478 ),
479 });
480 }
481 grid.push(grid_row);
482 }
483 } else {
484 let s = t.structure.as_ref();
485 let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| -> bool {
486 grid.and_then(|g| g.get(r))
487 .and_then(|row| row.get(c))
488 .copied()
489 .unwrap_or(false)
490 };
491 let anchor_of = |r: usize, c: usize| -> (usize, usize) {
492 let (mut r0, mut c0) = (r, c);
493 while c0 > 0 && flag(s.map(|s| &s.col_continuation), r, c0) {
494 c0 -= 1;
495 }
496 while r0 > 0 && flag(s.map(|s| &s.row_continuation), r0, c0) {
497 r0 -= 1;
498 }
499 (r0, c0)
500 };
501 let anchors: Vec<(usize, usize)> = (0..num_rows)
504 .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
505 .map(|(r, c)| anchor_of(r, c))
506 .collect();
507 let mut extent: Vec<(usize, usize)> = (0..num_rows)
508 .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
509 .collect();
510 for (i, &(ar, ac)) in anchors.iter().enumerate() {
511 let (r, c) = (i / num_cols.max(1), i % num_cols.max(1));
512 let e = &mut extent[ar * num_cols + ac];
513 e.0 = e.0.max(r);
514 e.1 = e.1.max(c);
515 }
516 for (r, row) in t.rows.iter().enumerate() {
517 let mut grid_row = Vec::with_capacity(num_cols);
518 for c in 0..num_cols {
519 let (ar, ac) = anchors[r * num_cols + c];
520 if (ar, ac) == (r, c) {
521 let (er, ec) = extent[r * num_cols + c];
522 let text = row.get(c).map(|s| cell_text(s)).unwrap_or_default();
523 let column_header = match s.filter(|s| !s.col_header.is_empty()) {
524 Some(s) => flag(Some(&s.col_header), r, c),
525 None => r == 0,
526 };
527 slot[r * num_cols + c] = Some(cells.len());
528 cells.push(cell_value(
529 er - r + 1,
530 ec - c + 1,
531 r,
532 er + 1,
533 c,
534 ec + 1,
535 text,
536 column_header,
537 flag(s.map(|s| &s.row_header), r, c),
538 false,
539 None,
540 ));
541 }
542 grid_row.push(match slot[ar * num_cols + ac] {
543 Some(i) => cells[i].clone(),
544 None => Value::Null,
545 });
546 }
547 grid.push(grid_row);
548 }
549 }
550 json!({
551 "table_cells": cells,
552 "num_rows": num_rows,
553 "num_cols": num_cols,
554 "orientation": "rot_0",
555 "grid": grid,
556 })
557}
558
559#[derive(Default)]
560struct Builder {
561 texts: Vec<Value>,
562 groups: Vec<Value>,
563 tables: Vec<Value>,
564 pictures: Vec<Value>,
565 field_regions: Vec<Value>,
566 field_items: Vec<Value>,
567 key_value_items: Vec<Value>,
568 pages: Vec<(usize, f64, f64)>,
572 cur_page: usize,
574 cur_w: f64,
575 cur_h: f64,
576 pending_loc: Option<[u16; 4]>,
579 pending_exact: Option<ExactProv>,
582 pending_siblings: Vec<Value>,
586 pending_after: Vec<Value>,
590 pending_body: Vec<Value>,
594 comment_groups: Vec<String>,
598 last_comment_section: Option<(String, String)>,
603 pending_comments: Vec<(String, Vec<usize>)>,
607}
608
609impl Builder {
610 fn take_prov(&mut self, char_len: usize) -> Value {
616 let prov = self.prov_json(char_len, false);
617 self.pending_exact = None;
618 self.pending_loc = None;
619 prov
620 }
621
622 fn prov_json(&self, char_len: usize, span_over_text: bool) -> Value {
627 let r2 = |v: f64| (v * 100.0).round() / 100.0;
628 if let Some(ExactProv {
629 page_no,
630 bbox: [l, t, r, b],
631 bottom_left,
632 charspan,
633 }) = self.pending_exact
634 {
635 let charspan = if span_over_text {
636 [0, char_len]
637 } else {
638 charspan
639 };
640 return json!([{
641 "page_no": page_no,
642 "bbox": {
643 "l": r2(l), "t": r2(t), "r": r2(r), "b": r2(b),
644 "coord_origin": if bottom_left { "BOTTOMLEFT" } else { "TOPLEFT" },
645 },
646 "charspan": charspan,
647 }]);
648 }
649 let Some([x0, y0, x1, y1]) = self.pending_loc else {
650 return json!([]);
651 };
652 if [x0, y0, x1, y1] == [0, 0, 0, 0] {
656 return json!([{
657 "page_no": self.cur_page,
658 "bbox": { "l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT" },
659 "charspan": [0, char_len],
660 }]);
661 }
662 json!([{
663 "page_no": self.cur_page,
664 "bbox": {
665 "l": r2(x0 as f64 * self.cur_w / 512.0),
666 "t": r2(self.cur_h - y0 as f64 * self.cur_h / 512.0),
667 "r": r2(x1 as f64 * self.cur_w / 512.0),
668 "b": r2(self.cur_h - y1 as f64 * self.cur_h / 512.0),
669 "coord_origin": "BOTTOMLEFT",
670 },
671 "charspan": [0, char_len],
672 }])
673 }
674
675 fn adopt_loc(&mut self, loc: Option<[u16; 4]>) {
678 if self.pending_loc.is_none() && self.cur_page > 0 {
679 self.pending_loc = loc;
680 }
681 }
682
683 fn link_comments(&mut self) {
691 let refs: Vec<(String, Vec<Value>)> = std::mem::take(&mut self.pending_comments)
692 .into_iter()
693 .map(|(item, comments)| {
694 let refs = comments
695 .iter()
696 .filter_map(|i| self.comment_groups.get(*i))
697 .map(|r| json!({ "$ref": r }))
698 .collect();
699 (item, refs)
700 })
701 .collect();
702 for (item, comment_refs) in refs {
703 if comment_refs.is_empty() {
704 continue;
705 }
706 let Some(target) = self.item_mut(&item) else {
707 continue;
708 };
709 let Some(obj) = target.as_object_mut() else {
710 continue;
711 };
712 let tail: Vec<(String, Value)> = obj
713 .iter()
714 .skip_while(|(k, _)| k.as_str() != "prov")
715 .skip(1)
716 .map(|(k, v)| (k.clone(), v.clone()))
717 .collect();
718 for (k, _) in &tail {
719 obj.shift_remove(k);
720 }
721 obj.insert("comments".into(), Value::Array(comment_refs));
722 for (k, v) in tail {
723 obj.insert(k, v);
724 }
725 }
726 }
727
728 fn item_mut(&mut self, self_ref: &str) -> Option<&mut Value> {
730 let idx = ref_index(self_ref)?;
731 let bucket = if self_ref.starts_with("#/texts/") {
732 &mut self.texts
733 } else if self_ref.starts_with("#/tables/") {
734 &mut self.tables
735 } else if self_ref.starts_with("#/pictures/") {
736 &mut self.pictures
737 } else if self_ref.starts_with("#/groups/") {
738 &mut self.groups
739 } else {
740 return None;
741 };
742 bucket.get_mut(idx)
743 }
744
745 fn write_tree(&mut self, tree: &crate::tree::ItemTree) -> Vec<Value> {
749 use crate::tree::TreeKind;
750 let mut refs: Vec<String> = Vec::with_capacity(tree.items.len());
753 let (mut nt, mut ng, mut ntb, mut np, mut nf, mut nk) = (0, 0, 0, 0, 0, 0);
754 for item in &tree.items {
755 if item.deleted {
756 refs.push(String::new());
757 continue;
758 }
759 let r = match &item.kind {
760 TreeKind::Text { .. } | TreeKind::Code { .. } => {
761 nt += 1;
762 format!("#/texts/{}", nt - 1)
763 }
764 TreeKind::Group { .. } => {
765 ng += 1;
766 format!("#/groups/{}", ng - 1)
767 }
768 TreeKind::Table { .. } => {
769 ntb += 1;
770 format!("#/tables/{}", ntb - 1)
771 }
772 TreeKind::Picture { .. } => {
773 np += 1;
774 format!("#/pictures/{}", np - 1)
775 }
776 TreeKind::FieldRegion { items } => {
777 nt += items
780 .iter()
781 .map(|i| {
782 [&i.marker, &i.key, &i.value]
783 .iter()
784 .filter(|p| p.is_some())
785 .count()
786 })
787 .sum::<usize>();
788 nf += 1;
789 format!("#/field_regions/{}", nf - 1)
790 }
791 TreeKind::KeyValueGraph { .. } => {
792 nk += 1;
793 format!("#/key_value_items/{}", nk - 1)
794 }
795 };
796 refs.push(r);
797 }
798 let ref_of = |id: usize| json!({ "$ref": refs[id] });
799 for (id, item) in tree.items.iter().enumerate() {
800 if item.deleted {
801 continue;
802 }
803 let parent = item.parent.map_or("#/body", |p| refs[p].as_str());
804 let children: Vec<Value> = item.children.iter().map(|&c| ref_of(c)).collect();
805 let layer = item.layer.map_or("body", |l| l.value());
806 self.pending_exact = item.prov.as_ref().map(ExactProv::from);
809 let self_ref = match &item.kind {
810 TreeKind::Text {
811 label,
812 text,
813 orig,
814 formatting,
815 hyperlink,
816 level,
817 list,
818 } => {
819 let mut tail = serde_json::Map::new();
822 if let Some(f) = formatting {
823 tail.insert("formatting".into(), formatting_json(f));
824 }
825 if let Some(h) = hyperlink {
826 tail.insert("hyperlink".into(), json!(h));
827 }
828 if let Some(l) = level {
829 tail.insert("level".into(), json!(l));
830 }
831 if let Some(l) = list {
832 tail.insert("enumerated".into(), json!(l.enumerated));
833 tail.insert("marker".into(), json!(l.marker));
834 }
835 let r = format!("#/texts/{}", self.texts.len());
836 let prov = self.take_prov(text.chars().count());
837 let mut item_json = json!({
838 "self_ref": r,
839 "parent": { "$ref": parent },
840 "children": children,
841 "content_layer": layer,
842 "label": label,
843 "prov": prov,
844 });
845 if !item.comments.is_empty() {
848 item_json["comments"] =
849 Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
850 }
851 if let Some(track) = &item.source {
854 item_json["source"] = json!([track_json(track)]);
855 }
856 merge(
857 &mut item_json,
858 json!({
859 "orig": orig.as_deref().unwrap_or(text),
860 "text": text,
861 }),
862 );
863 merge(&mut item_json, Value::Object(tail));
864 self.texts.push(item_json);
865 r
866 }
867 TreeKind::Code {
868 text,
869 orig,
870 language,
871 formatting,
872 hyperlink,
873 } => {
874 let r = format!("#/texts/{}", self.texts.len());
875 let prov = self.take_prov(text.chars().count());
876 let mut item_json = json!({
877 "self_ref": r,
878 "parent": { "$ref": parent },
879 "children": children,
880 "content_layer": layer,
881 "label": "code",
882 "prov": prov,
883 });
884 if !item.comments.is_empty() {
885 item_json["comments"] =
886 Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
887 }
888 merge(
889 &mut item_json,
890 json!({
891 "orig": orig.as_deref().unwrap_or(text),
892 "text": text,
893 }),
894 );
895 if let Some(f) = formatting {
896 item_json["formatting"] = formatting_json(f);
897 }
898 if let Some(h) = hyperlink {
899 item_json["hyperlink"] = json!(h);
900 }
901 merge(
902 &mut item_json,
903 json!({
904 "captions": [],
905 "references": [],
906 "footnotes": [],
907 "code_language": code_language(language.as_deref()),
908 }),
909 );
910 self.texts.push(item_json);
911 r
912 }
913 TreeKind::Group { label, name } => {
914 self.pending_exact = None;
915 let r = format!("#/groups/{}", self.groups.len());
916 self.groups.push(json!({
917 "self_ref": r,
918 "parent": { "$ref": parent },
919 "children": children,
920 "content_layer": layer,
921 "name": name,
922 "label": label,
923 }));
924 r
925 }
926 TreeKind::Table {
927 table,
928 rich_cells,
929 captions,
930 } => {
931 let r = self.add_table_with(table, parent, true);
933 let idx = ref_index(&r).expect("table ref");
934 let t = &mut self.tables[idx];
935 t["children"] = Value::Array(children);
936 t["content_layer"] = json!(layer);
937 t["captions"] = Value::Array(captions.iter().map(|&c| ref_of(c)).collect());
938 for &(row, col, group) in rich_cells {
942 let cell_ref = ref_of(group);
943 let hit = |c: &Value| {
944 c["start_row_offset_idx"] == json!(row)
945 && c["start_col_offset_idx"] == json!(col)
946 };
947 if let Some(cells) = t["data"]["table_cells"].as_array_mut() {
948 for c in cells.iter_mut().filter(|c| hit(c)) {
949 c["ref"] = cell_ref.clone();
950 }
951 }
952 }
953 r
954 }
955 TreeKind::Picture {
956 captions,
957 image,
958 classification,
959 confidence,
960 chart,
961 dpi,
962 } => {
963 let mut meta = classification.as_ref().map(|c| {
968 let mut pred = serde_json::Map::new();
969 if let Some(conf) = confidence {
970 pred.insert("confidence".into(), json!(conf));
971 }
972 pred.insert("class_name".into(), json!(c));
973 json!({ "classification": { "predictions": [pred] } })
974 });
975 if let (Some(m), Some(t)) = (meta.as_mut(), chart) {
976 if !t.rows.is_empty() {
977 m["tabular_chart"] = json!({ "chart_data": table_data(t) });
978 }
979 }
980 let prov = self.take_prov(0);
981 let r = self.push_picture(
982 prov,
983 captions.iter().map(|&c| ref_of(c)).collect(),
984 children,
985 image.as_ref(),
986 meta,
987 parent,
988 );
989 if let Some(idx) = ref_index(&r) {
990 self.pictures[idx]["content_layer"] = json!(layer);
991 if let (Some(dpi), Some(img)) = (dpi, self.pictures[idx].get_mut("image")) {
994 img["dpi"] = json!(dpi);
995 }
996 }
997 r
998 }
999 TreeKind::FieldRegion { items } => {
1000 self.pending_exact = None;
1001 let r = self.add_field_region(items, parent);
1002 if let Some(region) = self.field_regions.last_mut() {
1003 region["content_layer"] = json!(layer);
1004 }
1005 r
1006 }
1007 TreeKind::KeyValueGraph { cells, links } => {
1008 self.pending_exact = None;
1009 let r = self.add_key_value_graph(cells, links, parent);
1010 if let Some(item) = self.key_value_items.last_mut() {
1011 item["content_layer"] = json!(layer);
1012 }
1013 r
1014 }
1015 };
1016 debug_assert_eq!(self_ref, refs[id], "tree item {id} numbered out of order");
1017 }
1018 tree.body.iter().map(|&c| ref_of(c)).collect()
1019 }
1020
1021 fn add_node(&mut self, node: &Node, parent: &str) -> Option<String> {
1022 match node {
1023 Node::Heading { level: 1, text } => {
1024 Some(self.add_text("title", text, parent, json!({})))
1025 }
1026 Node::Heading { level, text } => Some(self.add_text(
1027 "section_header",
1028 text,
1029 parent,
1030 json!({ "level": level.saturating_sub(1) }),
1031 )),
1032 Node::Caption { text, href } => {
1033 let extra = match href {
1034 Some(url) => json!({ "hyperlink": url }),
1035 None => json!({}),
1036 };
1037 Some(self.add_text("caption", text, parent, extra))
1038 }
1039 Node::Paragraph { text } => {
1040 let t = text.trim();
1043 match t.strip_prefix("$$").and_then(|s| s.strip_suffix("$$")) {
1044 Some(inner) if !inner.is_empty() => Some(self.add_formula(inner, parent)),
1045 _ => Some(self.add_text("text", text, parent, json!({}))),
1046 }
1047 }
1048 Node::CheckboxItem { checked, text } => {
1049 let mark = if *checked { "- [x] " } else { "- [ ] " };
1052 Some(self.add_text("text", &format!("{mark}{text}"), parent, json!({})))
1053 }
1054 Node::Code {
1055 language,
1056 text,
1057 orig,
1058 ..
1059 } => Some(self.add_code(text, language.as_deref(), orig.as_deref(), parent)),
1060 Node::Formula {
1063 latex,
1064 orig,
1065 location,
1066 } => {
1067 self.adopt_loc(*location);
1068 Some(self.add_formula_item(latex, orig, parent))
1069 }
1070 Node::CommentSection {
1076 name,
1077 text,
1078 refs_note_text,
1079 grouped,
1080 } => {
1081 if !*grouped {
1082 let child =
1086 self.add_text("text", text, parent, json!({ "content_layer": "notes" }));
1087 self.comment_groups.push(child.clone());
1088 return Some(child);
1089 }
1090 if let Some((_, self_ref)) = self
1091 .last_comment_section
1092 .as_ref()
1093 .filter(|(n, _)| n == name)
1094 .cloned()
1095 {
1096 let child =
1099 self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1100 if let Some(children) =
1101 self.groups[group_index(&self_ref)]["children"].as_array_mut()
1102 {
1103 children.push(json!({ "$ref": child }));
1104 }
1105 self.comment_groups.push(if *refs_note_text {
1106 child
1107 } else {
1108 self_ref.clone()
1109 });
1110 return Some(self_ref);
1111 }
1112 let self_ref = format!("#/groups/{}", self.groups.len());
1113 self.groups.push(Value::Null);
1114 let child =
1115 self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1116 self.groups[group_index(&self_ref)] = json!({
1117 "self_ref": self_ref,
1118 "parent": { "$ref": parent },
1119 "children": [{ "$ref": child }],
1120 "content_layer": "notes",
1121 "name": name,
1122 "label": "comment_section",
1123 });
1124 self.last_comment_section = Some((name.clone(), self_ref.clone()));
1125 self.comment_groups.push(if *refs_note_text {
1126 child
1127 } else {
1128 self_ref.clone()
1129 });
1130 Some(self_ref)
1131 }
1132 Node::Commented { comments, inner } => {
1135 let item = self.add_node(inner, parent)?;
1136 if !comments.is_empty() {
1137 self.pending_comments.push((item.clone(), comments.clone()));
1138 }
1139 Some(item)
1140 }
1141 Node::Table(t) => Some(self.add_table(t, parent)),
1142 Node::Picture {
1143 caption,
1144 caption_href,
1145 image,
1146 classification,
1147 caption_parent,
1148 } => Some(self.add_picture(
1149 caption.as_deref(),
1150 caption_href.as_deref(),
1151 image.as_ref(),
1152 classification.as_deref().map(classification_meta),
1153 parent,
1154 *caption_parent,
1155 )),
1156 Node::Chart {
1161 kind,
1162 table,
1163 caption,
1164 location,
1165 } => {
1166 self.adopt_loc(*location);
1167 let mut meta = json!({
1168 "classification": { "predictions": [{ "class_name": kind }] },
1169 });
1170 if !table.rows.is_empty() {
1171 meta["tabular_chart"] = json!({ "chart_data": table_data(table) });
1172 }
1173 let mut captions = Vec::new();
1179 if let Some(cap) = caption.as_deref().filter(|c| !c.is_empty()) {
1180 let prov = self.prov_json(unescape_text(cap).chars().count(), true);
1181 let cap_ref = self.add_text_with("caption", cap, parent, json!({}), prov);
1182 self.pending_siblings.push(json!({ "$ref": cap_ref }));
1183 captions.push(json!({ "$ref": cap_ref }));
1184 }
1185 let prov = self.take_prov(0);
1186 Some(self.push_picture(prov, captions, Vec::new(), None, Some(meta), parent))
1187 }
1188 Node::DoclangOnly(_) => None,
1190 Node::Group {
1191 label,
1192 name,
1193 layer,
1194 children,
1195 } => Some(self.add_group(label, name.as_deref(), *layer, children, parent)),
1196 Node::FieldRegion { items } => Some(self.add_field_region(items, parent)),
1197 Node::KeyValueGraph { cells, links } => {
1198 Some(self.add_key_value_graph(cells, links, parent))
1199 }
1200 Node::InlineGroup { md_text, .. } => {
1203 Some(self.add_text("text", md_text, parent, json!({})))
1204 }
1205 Node::TextDump(text) => Some(self.add_text("text", text, parent, json!({}))),
1207 Node::Furniture {
1213 layer: ContentLayer::Notes,
1214 inner,
1215 } => {
1216 let item = self.add_node(inner, parent)?;
1217 self.set_layer(&item, "notes");
1218 Some(item)
1219 }
1220 Node::Furniture { .. } => None,
1221 Node::PageFurniture { .. } => None,
1222 Node::Located { location, inner } => {
1227 if self.cur_page > 0 {
1228 self.pending_loc = Some(*location);
1229 }
1230 let r = self.add_node(inner, parent);
1231 self.pending_loc = None;
1232 r
1233 }
1234 Node::Prov {
1235 page_no,
1236 bbox,
1237 charspan,
1238 inner,
1239 ..
1240 } => {
1241 self.pending_exact = Some(ExactProv {
1242 page_no: *page_no,
1243 bbox: bbox.map(f64::from),
1244 bottom_left: false,
1245 charspan: *charspan,
1246 });
1247 let r = self.add_node(inner, parent);
1248 self.pending_exact = None;
1249 r
1250 }
1251 Node::PageBreak => None,
1253 Node::PageInfo {
1256 page_no,
1257 width,
1258 height,
1259 } => {
1260 self.cur_page = *page_no;
1261 self.cur_w = *width as f64;
1262 self.cur_h = *height as f64;
1263 if *page_no > 0 {
1264 self.pages.push((*page_no, self.cur_w, self.cur_h));
1265 }
1266 None
1267 }
1268 Node::ListItem { .. } => None,
1270 }
1271 }
1272
1273 fn add_field_region(&mut self, items: &[crate::FieldItem], parent: &str) -> String {
1277 let self_ref = format!("#/field_regions/{}", self.field_regions.len());
1278 self.field_regions.push(Value::Null);
1279 let region_index = self.field_regions.len() - 1;
1280 let mut item_refs = Vec::new();
1281 for item in items {
1282 item_refs.push(json!({ "$ref": self.add_field_item(item, &self_ref) }));
1283 }
1284 self.field_regions[region_index] = json!({
1285 "self_ref": self_ref,
1286 "parent": { "$ref": parent },
1287 "children": item_refs,
1288 "content_layer": "body",
1289 "label": "field_region",
1290 "prov": [],
1291 });
1292 self_ref
1293 }
1294
1295 fn add_key_value_graph(
1299 &mut self,
1300 cells: &[crate::GraphCell],
1301 links: &[crate::GraphLink],
1302 parent: &str,
1303 ) -> String {
1304 let self_ref = format!("#/key_value_items/{}", self.key_value_items.len());
1305 let cells: Vec<Value> = cells
1306 .iter()
1307 .map(|c| {
1308 json!({
1309 "label": c.label,
1310 "cell_id": c.cell_id,
1311 "text": c.text,
1312 "orig": c.orig,
1313 })
1314 })
1315 .collect();
1316 let links: Vec<Value> = links
1317 .iter()
1318 .map(|l| {
1319 json!({
1320 "label": l.label,
1321 "source_cell_id": l.source_cell_id,
1322 "target_cell_id": l.target_cell_id,
1323 })
1324 })
1325 .collect();
1326 self.key_value_items.push(json!({
1327 "self_ref": self_ref,
1328 "parent": { "$ref": parent },
1329 "children": [],
1330 "content_layer": "body",
1331 "label": "key_value_region",
1332 "prov": [],
1333 "captions": [],
1334 "references": [],
1335 "footnotes": [],
1336 "graph": { "cells": cells, "links": links },
1337 }));
1338 self_ref
1339 }
1340
1341 fn add_field_item(&mut self, item: &crate::FieldItem, parent: &str) -> String {
1342 let self_ref = format!("#/field_items/{}", self.field_items.len());
1343 self.field_items.push(Value::Null);
1344 let item_index = self.field_items.len() - 1;
1345 let mut child_refs = Vec::new();
1346 for (label, text) in [
1347 ("marker", &item.marker),
1348 ("field_key", &item.key),
1349 ("field_value", &item.value),
1350 ] {
1351 if let Some(text) = text {
1352 let extra = match (label, &item.value_kind) {
1355 ("field_value", Some(kind)) => json!({ "kind": kind }),
1356 _ => json!({}),
1357 };
1358 child_refs.push(json!({ "$ref": self.add_text(label, text, &self_ref, extra) }));
1359 }
1360 }
1361 self.field_items[item_index] = json!({
1362 "self_ref": self_ref,
1363 "parent": { "$ref": parent },
1364 "children": child_refs,
1365 "content_layer": "body",
1366 "label": "field_item",
1367 "prov": [],
1368 });
1369 self_ref
1370 }
1371
1372 fn set_layer(&mut self, self_ref: &str, layer: &str) {
1376 let bucket = match self_ref.split('/').nth(1) {
1377 Some("texts") => &mut self.texts,
1378 Some("tables") => &mut self.tables,
1379 Some("pictures") => &mut self.pictures,
1380 Some("groups") => &mut self.groups,
1381 _ => return,
1382 };
1383 if let Some(item) = self_ref
1384 .rsplit('/')
1385 .next()
1386 .and_then(|i| i.parse::<usize>().ok())
1387 .and_then(|i| bucket.get_mut(i))
1388 {
1389 item["content_layer"] = json!(layer);
1390 }
1391 }
1392
1393 fn add_text(&mut self, label: &str, text: &str, parent: &str, extra: Value) -> String {
1394 let prov = self.take_prov(unescape_text(text).chars().count());
1395 self.add_text_with(label, text, parent, extra, prov)
1396 }
1397
1398 fn add_text_with(
1401 &mut self,
1402 label: &str,
1403 text: &str,
1404 parent: &str,
1405 extra: Value,
1406 prov: Value,
1407 ) -> String {
1408 let self_ref = format!("#/texts/{}", self.texts.len());
1409 let raw = unescape_text(text);
1410 let mut item = json!({
1411 "self_ref": self_ref,
1412 "parent": { "$ref": parent },
1413 "children": [],
1414 "content_layer": "body",
1415 "label": label,
1416 "prov": prov,
1417 "orig": raw,
1418 "text": raw,
1419 });
1420 merge(&mut item, extra);
1421 self.texts.push(item);
1422 self_ref
1423 }
1424
1425 fn add_formula(&mut self, latex: &str, parent: &str) -> String {
1428 let self_ref = format!("#/texts/{}", self.texts.len());
1429 let prov = self.take_prov(latex.chars().count());
1430 self.texts.push(json!({
1431 "self_ref": self_ref,
1432 "parent": { "$ref": parent },
1433 "children": [],
1434 "content_layer": "body",
1435 "label": "formula",
1436 "prov": prov,
1437 "orig": latex,
1438 "text": latex,
1439 }));
1440 self_ref
1441 }
1442
1443 fn add_formula_item(&mut self, latex: &str, orig: &str, parent: &str) -> String {
1447 let self_ref = format!("#/texts/{}", self.texts.len());
1448 let prov = self.take_prov(latex.chars().count());
1449 self.texts.push(json!({
1450 "self_ref": self_ref,
1451 "parent": { "$ref": parent },
1452 "children": [],
1453 "content_layer": "body",
1454 "label": "formula",
1455 "prov": prov,
1456 "orig": orig,
1457 "text": latex,
1458 }));
1459 self_ref
1460 }
1461
1462 fn add_code(
1463 &mut self,
1464 text: &str,
1465 language: Option<&str>,
1466 orig: Option<&str>,
1467 parent: &str,
1468 ) -> String {
1469 let self_ref = format!("#/texts/{}", self.texts.len());
1470 let raw = unescape_text(text);
1471 let prov = self.take_prov(raw.chars().count());
1472 self.texts.push(json!({
1473 "self_ref": self_ref,
1474 "parent": { "$ref": parent },
1475 "children": [],
1476 "content_layer": "body",
1477 "label": "code",
1478 "prov": prov,
1479 "orig": orig.map(unescape_text).unwrap_or_else(|| raw.clone()),
1482 "text": raw,
1483 "captions": [],
1484 "references": [],
1485 "footnotes": [],
1486 "code_language": code_language(language),
1487 }));
1488 self_ref
1489 }
1490
1491 fn add_list(&mut self, items: &[Node], parent: &str) -> String {
1494 let self_ref = format!("#/groups/{}", self.groups.len());
1495 self.groups.push(Value::Null);
1497 let base = level_of(&items[0]);
1498 let mut children = Vec::new();
1499 let mut i = 0;
1500 while i < items.len() {
1501 if !matches!(items[i], Node::ListItem { .. }) {
1504 i += 1;
1505 continue;
1506 }
1507 let lvl = level_of(&items[i]);
1508 if lvl > base {
1509 i += 1;
1511 continue;
1512 }
1513 let item_ref = self.add_list_item(&items[i], &self_ref);
1514 let mut j = i + 1;
1516 while j < items.len() && level_of(&items[j]) > base {
1517 j += 1;
1518 }
1519 if j > i + 1 {
1520 let mut nested = Vec::new();
1521 self.add_sibling_lists(&items[i + 1..j], &item_ref, &mut nested);
1522 if let Some(idx) = ref_index(&item_ref) {
1524 self.texts[idx]["children"]
1525 .as_array_mut()
1526 .unwrap()
1527 .extend(nested);
1528 }
1529 }
1530 children.push(json!({ "$ref": item_ref }));
1531 i = j;
1532 }
1533 self.groups[group_index(&self_ref)] = json!({
1534 "self_ref": self_ref,
1535 "parent": { "$ref": parent },
1536 "children": children,
1537 "content_layer": "body",
1538 "name": "list",
1539 "label": "list",
1540 });
1541 self_ref
1542 }
1543
1544 fn add_list_item(&mut self, node: &Node, parent: &str) -> String {
1545 let Node::ListItem {
1546 ordered,
1547 number,
1548 text,
1549 location,
1550 ..
1551 } = node
1552 else {
1553 unreachable!()
1554 };
1555 self.adopt_loc(*location);
1556 let self_ref = format!("#/texts/{}", self.texts.len());
1557 let raw = unescape_text(text);
1558 let prov = self.take_prov(raw.chars().count());
1559 let marker = if *ordered {
1560 format!("{number}.")
1561 } else {
1562 "-".to_string()
1563 };
1564 self.texts.push(json!({
1565 "self_ref": self_ref,
1566 "parent": { "$ref": parent },
1567 "children": [],
1568 "content_layer": "body",
1569 "label": "list_item",
1570 "prov": prov,
1571 "orig": raw,
1572 "text": raw,
1573 "enumerated": ordered,
1574 "marker": marker,
1575 }));
1576 self_ref
1577 }
1578
1579 fn add_table(&mut self, t: &Table, parent: &str) -> String {
1580 self.add_table_with(t, parent, false)
1581 }
1582
1583 fn add_table_with(&mut self, t: &Table, parent: &str, raw: bool) -> String {
1586 let self_ref = format!("#/tables/{}", self.tables.len());
1587 self.adopt_loc(t.location);
1588 let prov = self.take_prov(0);
1589 let (captions, children) = match t.caption.as_deref().filter(|c| !c.is_empty()) {
1593 Some(cap) => self.add_caption(cap, json!({}), &self_ref, parent, t.caption_parent),
1594 None => (Vec::new(), Vec::new()),
1595 };
1596 let data = table_data_with(t, raw);
1597 self.tables.push(json!({
1598 "self_ref": self_ref,
1599 "parent": { "$ref": parent },
1600 "children": children,
1601 "content_layer": "body",
1602 "label": "table",
1603 "prov": prov,
1604 "captions": captions,
1605 "references": [],
1606 "footnotes": [],
1607 "data": data,
1608 "annotations": [],
1609 }));
1610 self_ref
1611 }
1612
1613 fn add_caption(
1619 &mut self,
1620 text: &str,
1621 extra: Value,
1622 self_ref: &str,
1623 parent: &str,
1624 choice: CaptionParent,
1625 ) -> (Vec<Value>, Vec<Value>) {
1626 let cap_parent = match choice {
1631 CaptionParent::Item => self_ref,
1632 CaptionParent::Container | CaptionParent::ContainerAfter => parent,
1633 CaptionParent::Body => "#/body",
1634 };
1635 let cap_ref = json!({ "$ref": self.add_text("caption", text, cap_parent, extra) });
1636 match choice {
1637 CaptionParent::Item => return (vec![cap_ref.clone()], vec![cap_ref]),
1638 CaptionParent::Container => self.pending_siblings.push(cap_ref.clone()),
1641 CaptionParent::Body if parent == "#/body" => {
1642 self.pending_siblings.push(cap_ref.clone())
1643 }
1644 CaptionParent::ContainerAfter => self.pending_after.push(cap_ref.clone()),
1645 CaptionParent::Body => self.pending_body.push(cap_ref.clone()),
1648 }
1649 (vec![cap_ref], Vec::new())
1650 }
1651
1652 fn add_picture(
1655 &mut self,
1656 caption: Option<&str>,
1657 caption_href: Option<&str>,
1658 image: Option<&crate::PictureImage>,
1659 meta: Option<Value>,
1660 parent: &str,
1661 caption_parent: CaptionParent,
1662 ) -> String {
1663 let self_ref = format!("#/pictures/{}", self.pictures.len());
1664 let prov = self.take_prov(0);
1667 let (captions, children) = match caption.filter(|c| !c.is_empty()) {
1668 Some(cap) => {
1669 let extra = match caption_href {
1673 Some(href) => json!({ "hyperlink": href }),
1674 None => json!({}),
1675 };
1676 self.add_caption(cap, extra, &self_ref, parent, caption_parent)
1677 }
1678 None => (Vec::new(), Vec::new()),
1679 };
1680 self.push_picture(prov, captions, children, image, meta, parent)
1681 }
1682
1683 fn push_picture(
1686 &mut self,
1687 prov: Value,
1688 captions: Vec<Value>,
1689 children: Vec<Value>,
1690 image: Option<&crate::PictureImage>,
1691 meta: Option<Value>,
1692 parent: &str,
1693 ) -> String {
1694 let self_ref = format!("#/pictures/{}", self.pictures.len());
1695 let annotations = meta
1699 .as_ref()
1700 .and_then(|m| m.get("annotations").cloned())
1701 .unwrap_or_else(|| json!([]));
1702 let meta = meta.map(|mut m| {
1703 if let Some(obj) = m.as_object_mut() {
1704 obj.remove("annotations");
1705 }
1706 m
1707 });
1708 let mut item = match meta {
1712 Some(meta) => json!({
1713 "self_ref": self_ref,
1714 "parent": { "$ref": parent },
1715 "children": children,
1716 "content_layer": "body",
1717 "meta": meta,
1718 "label": "picture",
1719 "prov": prov,
1720 "captions": captions,
1721 "references": [],
1722 "footnotes": [],
1723 "annotations": annotations,
1724 }),
1725 None => json!({
1726 "self_ref": self_ref,
1727 "parent": { "$ref": parent },
1728 "children": children,
1729 "content_layer": "body",
1730 "label": "picture",
1731 "prov": prov,
1732 "captions": captions,
1733 "references": [],
1734 "footnotes": [],
1735 "annotations": annotations,
1736 }),
1737 };
1738 if let Some(img) = image {
1743 let image = json!({
1744 "mimetype": img.mimetype,
1745 "dpi": 72,
1746 "size": { "width": img.width as f64, "height": img.height as f64 },
1747 "uri": img.data_uri(),
1748 });
1749 if let Some(obj) = item.as_object_mut() {
1750 let annotations = obj.remove("annotations").unwrap_or_else(|| json!([]));
1751 obj.insert("image".into(), image);
1752 obj.insert("annotations".into(), annotations);
1753 }
1754 }
1755 self.pictures.push(item);
1756 self_ref
1757 }
1758
1759 fn add_group(
1760 &mut self,
1761 label: &str,
1762 name: Option<&str>,
1763 layer: Option<ContentLayer>,
1764 nodes: &[Node],
1765 parent: &str,
1766 ) -> String {
1767 let self_ref = format!("#/groups/{}", self.groups.len());
1768 self.groups.push(Value::Null);
1769 let mark = (
1773 self.texts.len(),
1774 self.tables.len(),
1775 self.pictures.len(),
1776 self.groups.len(),
1777 );
1778 let children = self.walk_into(nodes, &self_ref);
1779 let name = name.unwrap_or(if label == "inline" { "group" } else { label });
1780 let content_layer = layer.map_or("body", |l| l.value());
1781 self.groups[group_index(&self_ref)] = json!({
1782 "self_ref": self_ref,
1783 "parent": { "$ref": parent },
1784 "children": children,
1785 "content_layer": content_layer,
1786 "name": name,
1787 "label": label,
1788 });
1789 if layer.is_some() {
1790 let (t, tb, p, g) = mark;
1791 for item in self.texts[t..]
1792 .iter_mut()
1793 .chain(self.tables[tb..].iter_mut())
1794 .chain(self.pictures[p..].iter_mut())
1795 .chain(self.groups[g..].iter_mut())
1796 {
1797 if let Some(obj) = item.as_object_mut() {
1798 obj.insert("content_layer".into(), json!(content_layer));
1799 }
1800 }
1801 }
1802 self_ref
1803 }
1804
1805 fn walk_into(&mut self, nodes: &[Node], parent: &str) -> Vec<Value> {
1808 let seqs: Option<Vec<usize>> = nodes
1813 .iter()
1814 .map(|n| match n {
1815 Node::Prov { seq: Some(s), .. } => Some(*s),
1816 _ => None,
1817 })
1818 .collect();
1819 if let Some(seqs) = seqs.filter(|s| !s.is_empty()) {
1820 let mut order: Vec<usize> = (0..nodes.len()).collect();
1821 order.sort_by_key(|&i| seqs[i]);
1822 let mut slots: Vec<Vec<Value>> = vec![Vec::new(); nodes.len()];
1823 for i in order {
1824 if let Some(r) = self.add_node(&nodes[i], parent) {
1825 slots[i].append(&mut self.pending_siblings);
1826 slots[i].push(json!({ "$ref": r }));
1827 slots[i].append(&mut self.pending_after);
1828 }
1829 if parent == "#/body" {
1830 slots[i].append(&mut self.pending_body);
1831 }
1832 }
1833 return slots.into_iter().flatten().collect();
1834 }
1835 let mut children = Vec::new();
1836 let mut i = 0;
1837 while i < nodes.len() {
1838 if matches!(nodes[i], Node::ListItem { .. }) {
1839 let start = i;
1840 i += 1;
1841 loop {
1842 match nodes.get(i) {
1843 Some(Node::ListItem { .. }) => i += 1,
1844 Some(Node::Paragraph { text })
1847 if text.is_empty()
1848 && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
1849 {
1850 i += 1
1851 }
1852 _ => break,
1853 }
1854 }
1855 self.add_sibling_lists(&nodes[start..i], parent, &mut children);
1856 } else {
1857 if let Some(r) = self.add_node(&nodes[i], parent) {
1858 children.append(&mut self.pending_siblings);
1859 children.push(json!({ "$ref": r }));
1860 children.append(&mut self.pending_after);
1861 }
1862 i += 1;
1863 }
1864 if parent == "#/body" {
1867 children.append(&mut self.pending_body);
1868 }
1869 }
1870 children
1871 }
1872
1873 fn add_sibling_lists(&mut self, run: &[Node], parent: &str, out: &mut Vec<Value>) {
1878 let base = level_of(&run[0]);
1879 let mut seg = 0;
1880 for k in 0..run.len() {
1881 let Node::ListItem {
1882 first_in_list,
1883 level,
1884 ..
1885 } = &run[k]
1886 else {
1887 continue;
1888 };
1889 if *level != base {
1890 continue; }
1892 if k > seg && *first_in_list {
1893 out.push(json!({ "$ref": self.add_list(&run[seg..k], parent) }));
1894 seg = k;
1895 }
1896 }
1897 out.push(json!({ "$ref": self.add_list(&run[seg..], parent) }));
1898 }
1899}
1900
1901fn level_of(node: &Node) -> u8 {
1902 match node {
1903 Node::ListItem { level, .. } => *level,
1904 _ => 0,
1905 }
1906}
1907
1908fn group_index(self_ref: &str) -> usize {
1909 self_ref.rsplit('/').next().unwrap().parse().unwrap()
1910}
1911
1912fn ref_index(self_ref: &str) -> Option<usize> {
1913 self_ref.rsplit('/').next()?.parse().ok()
1914}
1915
1916fn merge(target: &mut Value, extra: Value) {
1918 if let (Some(t), Some(e)) = (target.as_object_mut(), extra.as_object()) {
1919 for (k, v) in e {
1920 t.insert(k.clone(), v.clone());
1921 }
1922 }
1923}
1924
1925fn unescape_text(s: &str) -> String {
1927 s.replace("<", "<")
1928 .replace(">", ">")
1929 .replace("&", "&")
1930 .replace("\\_", "_")
1931}
1932
1933fn fnv1a(s: &str) -> u64 {
1936 let mut h: u64 = 0xcbf29ce484222325;
1937 for b in s.bytes() {
1938 h ^= b as u64;
1939 h = h.wrapping_mul(0x100000001b3);
1940 }
1941 h
1942}
1943
1944#[cfg(test)]
1945mod tests {
1946 use crate::{
1947 CaptionParent, ContentLayer, DoclingDocument, ImageMode, Node, PictureImage, Table,
1948 };
1949 use serde_json::Value;
1950
1951 fn cell_at(text: &str, row: usize, col: usize, col_span: usize) -> crate::TableCell {
1952 crate::TableCell {
1953 text: text.into(),
1954 bbox: None,
1955 start_row: row,
1956 start_col: col,
1957 row_span: 1,
1958 col_span,
1959 column_header: row == 0,
1960 row_header: false,
1961 row_section: false,
1962 }
1963 }
1964
1965 #[test]
1971 fn ragged_rows_take_their_grid_from_first_class_cells() {
1972 let cells = vec![
1973 cell_at("h0", 0, 0, 1),
1974 cell_at("h2", 0, 2, 1),
1975 cell_at("wide", 1, 0, 3),
1976 ];
1977 let export = |rows: Vec<Vec<String>>| -> Value {
1978 let mut doc = DoclingDocument::new("t");
1979 doc.push(Node::Table(Table {
1980 rows,
1981 cells: Some(cells.clone()),
1982 ..Table::default()
1983 }));
1984 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
1985 v["tables"][0]["data"].clone()
1986 };
1987 let data = export(vec![
1989 vec!["h0".into(), "h2".into()],
1990 vec!["wide".into(), "wide".into(), "wide".into()],
1991 ]);
1992 assert_eq!(data["num_rows"], 2);
1993 assert_eq!(data["num_cols"], 3);
1994 assert_eq!(data["table_cells"].as_array().unwrap().len(), 3);
1995 let row0: Vec<&str> = data["grid"][0]
1996 .as_array()
1997 .unwrap()
1998 .iter()
1999 .map(|c| c["text"].as_str().unwrap())
2000 .collect();
2001 assert_eq!(row0, ["h0", "", "h2"]);
2002 assert_eq!(data["table_cells"][2]["col_span"], 3);
2003 let data = export(vec![
2006 vec!["h0".into(), "h2".into()],
2007 vec!["wide".into(), "wide".into()],
2008 ]);
2009 assert_eq!(data["num_cols"], 2);
2010 assert_eq!(data["grid"][0].as_array().unwrap().len(), 2);
2011 }
2012
2013 fn doc_with_image() -> DoclingDocument {
2014 let mut doc = DoclingDocument::new("t");
2015 doc.push(Node::Picture {
2016 caption: Some("Fig 1".into()),
2017 caption_href: None,
2018 image: Some(PictureImage {
2019 mimetype: "image/png".into(),
2020 width: 4,
2021 height: 2,
2022 data: b"foobar".to_vec(),
2023 }),
2024 classification: None,
2025 caption_parent: Default::default(),
2026 });
2027 doc
2028 }
2029
2030 #[test]
2035 fn notes_layer_items_reach_the_json_but_furniture_does_not() {
2036 let mut doc = DoclingDocument::new("t");
2037 doc.push(Node::Heading {
2038 level: 1,
2039 text: "Slide One".into(),
2040 });
2041 doc.push(Node::Furniture {
2042 layer: ContentLayer::Notes,
2043 inner: Box::new(Node::Located {
2044 location: [0, 0, 0, 0],
2045 inner: Box::new(Node::Paragraph {
2046 text: "Speaker note for slide 1.".into(),
2047 }),
2048 }),
2049 });
2050 doc.push(Node::Furniture {
2051 layer: ContentLayer::Furniture,
2052 inner: Box::new(Node::Paragraph {
2053 text: "page header".into(),
2054 }),
2055 });
2056
2057 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2058 let texts = v["texts"].as_array().unwrap();
2059 assert_eq!(
2060 texts
2061 .iter()
2062 .map(|t| (
2063 t["label"].as_str().unwrap(),
2064 t["content_layer"].as_str().unwrap(),
2065 t["text"].as_str().unwrap()
2066 ))
2067 .collect::<Vec<_>>(),
2068 vec![
2069 ("title", "body", "Slide One"),
2070 ("text", "notes", "Speaker note for slide 1."),
2071 ],
2072 "the note is carried on its own layer; the furniture is not carried"
2073 );
2074 assert_eq!(doc.export_to_markdown(), "# Slide One\n");
2076 }
2077
2078 #[test]
2084 fn continuation_flags_become_spanning_cells() {
2085 let mut doc = DoclingDocument::new("t");
2086 let rows = vec![
2088 vec!["merged".to_string(), "merged".into(), "merged".into()],
2089 vec!["merged".to_string(), "merged".into(), "merged".into()],
2090 vec!["a".to_string(), "b".into(), "c".into()],
2091 ];
2092 doc.push(Node::Table(crate::Table {
2093 rows,
2094 location: None,
2095 structure: Some(crate::TableStructure {
2096 header_row: vec![true, false, false],
2097 col_continuation: vec![
2098 vec![false, true, true],
2099 vec![false, true, true],
2100 vec![false, false, false],
2101 ],
2102 row_continuation: vec![
2103 vec![false, false, false],
2104 vec![true, true, true],
2105 vec![false, false, false],
2106 ],
2107 row_header: Vec::new(),
2108 col_header: Vec::new(),
2109 }),
2110 cell_blocks: None,
2111 cells: None,
2112 caption: None,
2113 caption_parent: Default::default(),
2114 }));
2115 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2116 let data = &v["tables"][0]["data"];
2117 assert_eq!(data["num_rows"], 3);
2118 assert_eq!(data["num_cols"], 3);
2119 let cells = data["table_cells"].as_array().unwrap();
2120 assert_eq!(
2121 cells.len(),
2122 4,
2123 "one cell for the range, three for the plain row"
2124 );
2125 assert_eq!(
2126 cells[0],
2127 serde_json::json!({
2128 "row_span": 2, "col_span": 3,
2129 "start_row_offset_idx": 0, "end_row_offset_idx": 2,
2130 "start_col_offset_idx": 0, "end_col_offset_idx": 3,
2131 "text": "merged", "column_header": true, "row_header": false,
2132 "row_section": false, "fillable": false,
2133 })
2134 );
2135 assert_eq!(cells[1]["text"], "a");
2136 assert_eq!(cells[1]["row_span"], 1);
2137 assert_eq!(cells[1]["column_header"], false);
2138 let grid = data["grid"].as_array().unwrap();
2140 assert_eq!(grid.len(), 3);
2141 for (r, row) in grid.iter().take(2).enumerate() {
2142 for (c, cell) in row.as_array().unwrap().iter().enumerate() {
2143 assert_eq!(*cell, cells[0], "grid[{r}][{c}]");
2144 }
2145 }
2146 assert_eq!(grid[2][2]["text"], "c");
2147 }
2148
2149 #[test]
2155 fn exact_provenance_pages_and_chart_captions_follow_docling() {
2156 let mut doc = DoclingDocument::new("t");
2157 doc.push(Node::PageInfo {
2158 page_no: 1,
2159 width: 3.0,
2160 height: 4.0,
2161 });
2162 let table = crate::Table {
2163 rows: vec![vec!["a".to_string(), "b".into()]],
2164 ..Default::default()
2165 };
2166 doc.push(Node::Group {
2167 label: "sheet".into(),
2168 name: Some("Data".into()),
2169 layer: None,
2170 children: vec![
2171 Node::Prov {
2176 page_no: 1,
2177 bbox: [0.0, 0.0, 3.0, 4.0],
2178 charspan: [0, 0],
2179 seq: Some(1),
2180 inner: Box::new(Node::Table(table.clone())),
2181 },
2182 Node::Prov {
2183 page_no: 1,
2184 bbox: [0.0, 1.0, 1.0, 1.0],
2185 charspan: [0, 0],
2186 seq: Some(0),
2187 inner: Box::new(Node::Chart {
2188 kind: "bar_chart".into(),
2189 table,
2190 caption: Some("Sales".into()),
2191 location: Some([0, 128, 170, 128]),
2192 }),
2193 },
2194 ],
2195 });
2196 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2197 assert_eq!(
2198 v["pages"],
2199 serde_json::json!({"1": {"size": {"width": 3.0, "height": 4.0}, "page_no": 1}})
2200 );
2201 assert_eq!(
2202 v["tables"][0]["prov"],
2203 serde_json::json!([{
2204 "page_no": 1,
2205 "bbox": {"l": 0.0, "t": 0.0, "r": 3.0, "b": 4.0, "coord_origin": "TOPLEFT"},
2206 "charspan": [0, 0],
2207 }])
2208 );
2209 assert_eq!(v["tables"][0]["data"]["orientation"], "rot_0");
2210 let sheet = &v["groups"][0];
2213 assert_eq!(
2214 sheet["children"],
2215 serde_json::json!([
2216 {"$ref": "#/tables/0"}, {"$ref": "#/texts/0"}, {"$ref": "#/pictures/0"}
2217 ])
2218 );
2219 let cap = &v["texts"][0];
2220 assert_eq!(cap["label"], "caption");
2221 assert_eq!(cap["parent"], serde_json::json!({"$ref": "#/groups/0"}));
2222 assert_eq!(cap["prov"][0]["charspan"], serde_json::json!([0, 5]));
2223 assert_eq!(cap["prov"][0]["bbox"]["b"], 1.0);
2224 let pic = &v["pictures"][0];
2225 assert_eq!(pic["captions"], serde_json::json!([{"$ref": "#/texts/0"}]));
2226 assert_eq!(pic["prov"][0]["charspan"], serde_json::json!([0, 0]));
2227 assert_eq!(pic["prov"][0]["bbox"]["coord_origin"], "TOPLEFT");
2228 assert_eq!(
2229 pic["meta"]["classification"]["predictions"][0]["class_name"],
2230 "bar_chart"
2231 );
2232 assert_eq!(pic["meta"]["tabular_chart"]["chart_data"]["num_cols"], 2);
2233 }
2234
2235 #[test]
2239 fn a_zero_location_is_a_zero_bbox_not_the_whole_page() {
2240 let mut doc = DoclingDocument::new("t");
2241 doc.push(Node::PageInfo {
2242 page_no: 1,
2243 width: 12192000.0,
2244 height: 6858000.0,
2245 });
2246 doc.push(Node::Furniture {
2247 layer: ContentLayer::Notes,
2248 inner: Box::new(Node::Located {
2249 location: [0, 0, 0, 0],
2250 inner: Box::new(Node::Paragraph {
2251 text: "a note".into(),
2252 }),
2253 }),
2254 });
2255 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2256 let prov = &v["texts"][0]["prov"][0];
2257 assert_eq!(prov["page_no"], 1);
2258 assert_eq!(prov["charspan"], serde_json::json!([0, 6]));
2259 assert_eq!(
2260 prov["bbox"],
2261 serde_json::json!({"l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT"})
2262 );
2263 assert_eq!(
2265 v["pages"]["1"]["size"],
2266 serde_json::json!({"width": 12192000.0, "height": 6858000.0})
2267 );
2268 }
2269
2270 #[test]
2276 fn page_markers_produce_pages_and_prov() {
2277 let mut doc = DoclingDocument::new("t");
2278 doc.push(Node::PageInfo {
2279 page_no: 1,
2280 width: 512.0,
2281 height: 1024.0,
2282 });
2283 doc.push(Node::Located {
2284 location: [128, 64, 256, 128], inner: Box::new(Node::Paragraph {
2286 text: "hello".into(),
2287 }),
2288 });
2289 doc.push(Node::Table(Table {
2290 rows: vec![vec!["a".into()]],
2291 location: Some([0, 0, 512, 512]),
2292 ..Table::default()
2293 }));
2294 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2295 assert_eq!(v["pages"]["1"]["page_no"], 1);
2296 assert_eq!(v["pages"]["1"]["size"]["width"], 512.0);
2297 assert_eq!(v["pages"]["1"]["size"]["height"], 1024.0);
2298 let prov = &v["texts"][0]["prov"][0];
2301 assert_eq!(prov["page_no"], 1);
2302 assert_eq!(prov["bbox"]["l"], 128.0);
2303 assert_eq!(prov["bbox"]["t"], 896.0);
2304 assert_eq!(prov["bbox"]["r"], 256.0);
2305 assert_eq!(prov["bbox"]["b"], 768.0);
2306 assert_eq!(prov["bbox"]["coord_origin"], "BOTTOMLEFT");
2307 assert_eq!(prov["charspan"][1], 5);
2308 let tprov = &v["tables"][0]["prov"][0];
2310 assert_eq!(tprov["bbox"]["t"], 1024.0);
2311 assert_eq!(tprov["bbox"]["b"], 0.0);
2312 assert_eq!(tprov["charspan"][1], 0);
2313
2314 let mut plain = DoclingDocument::new("t");
2316 plain.push(Node::Located {
2317 location: [1, 2, 3, 4],
2318 inner: Box::new(Node::Paragraph { text: "x".into() }),
2319 });
2320 let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
2321 assert_eq!(v["pages"], serde_json::json!({}));
2322 assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
2323 }
2324
2325 #[test]
2326 fn picture_image_in_markdown_modes_and_json() {
2327 let doc = doc_with_image();
2328 assert!(doc.export_to_markdown().contains("<!-- image -->"));
2330 let (md, files) = doc.export_to_markdown_with_images(ImageMode::Embedded, "artifacts");
2332 assert!(
2333 md.contains(""),
2334 "got:\n{md}"
2335 );
2336 assert!(files.is_empty());
2337 let (md, files) = doc.export_to_markdown_with_images(ImageMode::Referenced, "artifacts");
2339 assert!(
2340 md.contains(""),
2341 "got:\n{md}"
2342 );
2343 assert_eq!(
2344 files,
2345 vec![("artifacts/image_000000.png".to_string(), b"foobar".to_vec())]
2346 );
2347 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2350 assert_eq!(v["pictures"][0]["image"]["mimetype"], "image/png");
2351 assert_eq!(v["pictures"][0]["image"]["size"]["width"], 4.0);
2352 let keys: Vec<&str> = v["pictures"][0]
2353 .as_object()
2354 .unwrap()
2355 .keys()
2356 .map(String::as_str)
2357 .collect();
2358 assert_eq!(&keys[keys.len() - 2..], ["image", "annotations"]);
2359 assert_eq!(
2360 v["pictures"][0]["image"]["uri"],
2361 "data:image/png;base64,Zm9vYmFy"
2362 );
2363 }
2364
2365 #[test]
2366 fn exports_docling_schema() {
2367 let mut doc = DoclingDocument::new("t");
2368 doc.push(Node::Heading {
2369 level: 1,
2370 text: "Title".into(),
2371 });
2372 doc.push(Node::Heading {
2373 level: 2,
2374 text: "Sec".into(),
2375 });
2376 doc.push(Node::Paragraph {
2377 text: "Body & more".into(),
2378 }); doc.push(Node::ListItem {
2380 ordered: false,
2381 number: 0,
2382 first_in_list: true,
2383 text: "one".into(),
2384 level: 0,
2385 marker: None,
2386 location: None,
2387 dclx: None,
2388 href: None,
2389 layer: None,
2390 });
2391 doc.push(Node::ListItem {
2392 ordered: false,
2393 number: 0,
2394 first_in_list: false,
2395 text: "two".into(),
2396 level: 0,
2397 marker: None,
2398 location: None,
2399 dclx: None,
2400 href: None,
2401 layer: None,
2402 });
2403 doc.push(Node::Table(Table {
2404 rows: vec![vec!["A".into(), "B".into()]],
2405 location: None,
2406 structure: None,
2407 cell_blocks: None,
2408 cells: None,
2409 caption: None,
2410 caption_parent: Default::default(),
2411 }));
2412
2413 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2414 assert_eq!(v["schema_name"], "DoclingDocument");
2415 assert_eq!(v["version"], "1.10.0");
2416 assert_eq!(v["texts"][0]["label"], "title");
2417 assert_eq!(v["texts"][1]["label"], "section_header");
2418 assert_eq!(v["texts"][1]["level"], 1); assert_eq!(v["texts"][2]["text"], "Body & more"); assert_eq!(v["groups"][0]["label"], "list");
2422 assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
2423 assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
2424 assert_eq!(v["texts"][3]["marker"], "-");
2425 assert_eq!(v["tables"][0]["data"]["num_cols"], 2);
2427 assert_eq!(v["tables"][0]["data"]["grid"][0][0]["column_header"], true);
2428 }
2429 #[test]
2433 fn a_layered_group_stamps_its_whole_subtree() {
2434 let doc = DoclingDocument {
2435 name: "s".into(),
2436 nodes: vec![
2437 Node::Group {
2438 label: "sheet".into(),
2439 name: Some("Sheet1".into()),
2440 layer: None,
2441 children: vec![Node::Paragraph {
2442 text: "visible".into(),
2443 }],
2444 },
2445 Node::Group {
2446 label: "sheet".into(),
2447 name: Some("Sheet2".into()),
2448 layer: Some(ContentLayer::Invisible),
2449 children: vec![Node::Paragraph {
2450 text: "hidden".into(),
2451 }],
2452 },
2453 ],
2454 ..DoclingDocument::new("s")
2455 };
2456 let v = crate::json::to_json(&doc);
2457 assert_eq!(v["groups"][0]["label"], "sheet");
2458 assert_eq!(v["groups"][0]["name"], "Sheet1");
2459 assert_eq!(v["groups"][0]["content_layer"], "body");
2460 assert_eq!(v["texts"][0]["content_layer"], "body");
2461 assert_eq!(v["groups"][1]["name"], "Sheet2");
2462 assert_eq!(v["groups"][1]["content_layer"], "invisible");
2463 assert_eq!(v["texts"][1]["content_layer"], "invisible");
2464 assert_eq!(v["groups"][1]["children"][0]["$ref"], "#/texts/1");
2466 assert_eq!(v["body"]["children"][1]["$ref"], "#/groups/1");
2467 }
2468
2469 #[test]
2479 fn deleted_items_comment_refs_and_chart_meta_in_the_tree() {
2480 use crate::tree::{ItemTree, TreeKind};
2481 let mut t = ItemTree::default();
2482 let text = |txt: &str| TreeKind::Text {
2483 label: "text".into(),
2484 text: txt.into(),
2485 orig: None,
2486 formatting: None,
2487 hyperlink: None,
2488 level: None,
2489 list: None,
2490 };
2491 let a = t.add(None, None, text("a"));
2492 let blank = t.add(None, None, text(""));
2493 let b = t.add(None, None, text("b"));
2494 t.delete(blank);
2495 let group = t.add(
2496 None,
2497 Some(ContentLayer::Notes),
2498 TreeKind::Group {
2499 label: "comment_section".into(),
2500 name: "comment-0".into(),
2501 },
2502 );
2503 t.add(Some(group), Some(ContentLayer::Notes), text("note"));
2504 t.items[a].comments.push(group);
2505 t.add(
2506 None,
2507 None,
2508 TreeKind::Picture {
2509 captions: Vec::new(),
2510 image: None,
2511 classification: Some("bar_chart".into()),
2512 confidence: None,
2513 chart: Some(Table {
2514 rows: vec![vec!["".into(), "s".into()], vec!["c".into(), "1".into()]],
2515 ..Table::default()
2516 }),
2517 dpi: None,
2518 },
2519 );
2520 assert_eq!(t.last_text(), Some(4), "the note; the blank is skipped");
2521 assert_eq!(t.bucket_index(b), 1, "numbered past the deleted item");
2522 let mut doc = DoclingDocument::new("t");
2523 doc.tree = Some(t);
2524 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2525 let texts = v["texts"].as_array().unwrap();
2526 assert_eq!(texts.len(), 3);
2527 assert_eq!(texts[1]["text"], "b");
2528 assert_eq!(texts[1]["self_ref"], "#/texts/1");
2529 assert_eq!(
2530 v["body"]["children"],
2531 serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}, {"$ref": "#/groups/0"}, {"$ref": "#/pictures/0"}])
2532 );
2533 let keys: Vec<&str> = texts[0]
2534 .as_object()
2535 .unwrap()
2536 .keys()
2537 .map(String::as_str)
2538 .collect();
2539 assert_eq!(
2540 keys,
2541 vec![
2542 "self_ref",
2543 "parent",
2544 "children",
2545 "content_layer",
2546 "label",
2547 "prov",
2548 "comments",
2549 "orig",
2550 "text"
2551 ]
2552 );
2553 assert_eq!(
2554 texts[0]["comments"],
2555 serde_json::json!([{"$ref": "#/groups/0"}])
2556 );
2557 assert!(texts[1].get("comments").is_none());
2558 let meta = &v["pictures"][0]["meta"];
2559 assert_eq!(
2560 meta["classification"]["predictions"][0]["class_name"],
2561 "bar_chart"
2562 );
2563 assert_eq!(meta["tabular_chart"]["chart_data"]["num_rows"], 2);
2564 }
2565
2566 #[test]
2572 fn tree_items_carry_exact_provenance_and_dpi() {
2573 use crate::tree::{ItemTree, TreeKind, TreeProv};
2574 let text = |label: &str, t: &str| TreeKind::Text {
2575 label: label.into(),
2576 text: t.into(),
2577 orig: None,
2578 formatting: None,
2579 hyperlink: None,
2580 level: None,
2581 list: None,
2582 };
2583 let mut t = ItemTree::default();
2584 let slide = t.add(
2585 None,
2586 None,
2587 TreeKind::Group {
2588 label: "chapter".into(),
2589 name: "slide-0".into(),
2590 },
2591 );
2592 t.add_with_prov(
2593 Some(slide),
2594 None,
2595 text("paragraph", "héllo"),
2596 TreeProv {
2597 page_no: 1,
2598 bbox: [914400.0, 1828800.0, 2743200.0, 457200.0],
2599 bottom_left: true,
2600 charspan: [0, 5],
2601 },
2602 );
2603 t.add_with_prov(
2604 Some(slide),
2605 None,
2606 TreeKind::Picture {
2607 captions: Vec::new(),
2608 image: Some(crate::PictureImage {
2609 mimetype: "image/png".into(),
2610 width: 2,
2611 height: 2,
2612 data: vec![0],
2613 }),
2614 classification: None,
2615 confidence: None,
2616 chart: None,
2617 dpi: Some(300),
2618 },
2619 TreeProv {
2620 page_no: 1,
2621 bbox: [0.0; 4],
2622 bottom_left: false,
2623 charspan: [0, 0],
2624 },
2625 );
2626 t.add(
2627 Some(slide),
2628 Some(ContentLayer::Notes),
2629 text("text", "no geometry"),
2630 );
2631 let mut doc = DoclingDocument::new("t");
2632 doc.push(Node::PageInfo {
2633 page_no: 1,
2634 width: 9144000.0,
2635 height: 6858000.0,
2636 });
2637 doc.tree = Some(t);
2638 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2639 assert_eq!(
2640 v["texts"][0]["prov"],
2641 serde_json::json!([{
2642 "page_no": 1,
2643 "bbox": { "l": 914400.0, "t": 1828800.0, "r": 2743200.0, "b": 457200.0, "coord_origin": "BOTTOMLEFT" },
2644 "charspan": [0, 5],
2645 }])
2646 );
2647 assert_eq!(v["texts"][0]["label"], "paragraph");
2648 assert_eq!(
2649 v["pictures"][0]["prov"][0]["bbox"]["coord_origin"],
2650 "TOPLEFT"
2651 );
2652 assert_eq!(v["pictures"][0]["image"]["dpi"], 300);
2653 assert_eq!(v["texts"][1]["prov"], serde_json::json!([]));
2654 assert_eq!(v["texts"][1]["content_layer"], "notes");
2655 assert_eq!(v["pages"]["1"]["size"]["width"], 9144000.0);
2656 assert_eq!(v["pages"]["1"]["page_no"], 1);
2657 }
2658
2659 #[test]
2664 fn provenance_boxes_are_clamped_to_their_page() {
2665 let mut doc = DoclingDocument::new("t");
2666 doc.push(Node::PageInfo {
2667 page_no: 1,
2668 width: 10.0,
2669 height: 8.0,
2670 });
2671 doc.push(Node::Prov {
2672 page_no: 1,
2673 bbox: [-1.0, 2.0, 12.0, 9.5],
2674 charspan: [0, 1],
2675 seq: None,
2676 inner: Box::new(Node::Paragraph { text: "x".into() }),
2677 });
2678 let mut table = Table {
2679 rows: vec![vec!["a".into()]],
2680 ..Table::default()
2681 };
2682 table.cells = Some(vec![crate::TableCell {
2683 text: "a".into(),
2684 bbox: Some([1.0, 1.0, 11.0, 9.0]),
2685 start_row: 0,
2686 start_col: 0,
2687 row_span: 1,
2688 col_span: 1,
2689 column_header: false,
2690 row_header: false,
2691 row_section: false,
2692 }]);
2693 doc.push(Node::Prov {
2694 page_no: 1,
2695 bbox: [0.0, 0.0, 10.0, 8.0],
2696 charspan: [0, 0],
2697 seq: None,
2698 inner: Box::new(Node::Table(table)),
2699 });
2700 doc.push(Node::Prov {
2701 page_no: 7,
2702 bbox: [-5.0, 0.0, 50.0, 50.0],
2703 charspan: [0, 1],
2704 seq: None,
2705 inner: Box::new(Node::Paragraph { text: "y".into() }),
2706 });
2707 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2708 assert_eq!(
2709 v["texts"][0]["prov"][0]["bbox"],
2710 serde_json::json!({ "l": 0.0, "t": 2.0, "r": 10.0, "b": 8.0, "coord_origin": "TOPLEFT" })
2711 );
2712 let cell = &v["tables"][0]["data"]["table_cells"][0]["bbox"];
2713 assert_eq!(
2714 (cell["l"].as_f64(), cell["r"].as_f64(), cell["b"].as_f64()),
2715 (Some(1.0), Some(10.0), Some(8.0))
2716 );
2717 assert_eq!(v["tables"][0]["data"]["grid"][0][0]["bbox"]["r"], 10.0);
2718 assert_eq!(
2719 v["texts"][1]["prov"][0]["bbox"]["r"], 50.0,
2720 "page 7 is not described"
2721 );
2722 }
2723
2724 #[test]
2725 fn a_backend_item_tree_is_written_verbatim() {
2726 use crate::tree::{Formatting, ItemTree, ListMeta, TreeKind};
2727 let mut t = ItemTree::default();
2728 let text = |label: &str, txt: &str| TreeKind::Text {
2729 label: label.into(),
2730 text: txt.into(),
2731 orig: None,
2732 formatting: None,
2733 hyperlink: None,
2734 level: None,
2735 list: None,
2736 };
2737 let title = t.add(None, Some(ContentLayer::Furniture), text("title", "Page"));
2738 let h = t.add(None, None, text("title", "Heading"));
2739 let group = t.add(
2740 Some(h),
2741 None,
2742 TreeKind::Group {
2743 label: "inline".into(),
2744 name: "group".into(),
2745 },
2746 );
2747 t.add(
2748 Some(group),
2749 None,
2750 TreeKind::Text {
2751 label: "text".into(),
2752 text: "bold".into(),
2753 orig: None,
2754 formatting: Some(Formatting {
2755 bold: true,
2756 ..Formatting::default()
2757 }),
2758 hyperlink: Some("https://example.com/".into()),
2759 level: None,
2760 list: None,
2761 },
2762 );
2763 t.add(
2764 Some(group),
2765 None,
2766 TreeKind::Code {
2767 text: "x = 1".into(),
2768 orig: None,
2769 language: Some("python".into()),
2770 formatting: None,
2771 hyperlink: None,
2772 },
2773 );
2774 let sub = t.add(
2775 Some(h),
2776 None,
2777 TreeKind::Text {
2778 label: "section_header".into(),
2779 text: "Sub".into(),
2780 orig: Some("Sub\u{2019}".into()),
2781 formatting: None,
2782 hyperlink: None,
2783 level: Some(1),
2784 list: None,
2785 },
2786 );
2787 t.add(
2788 Some(sub),
2789 None,
2790 TreeKind::Text {
2791 label: "list_item".into(),
2792 text: "item".into(),
2793 orig: None,
2794 formatting: None,
2795 hyperlink: None,
2796 level: None,
2797 list: Some(ListMeta {
2798 enumerated: true,
2799 marker: "3.".into(),
2800 }),
2801 },
2802 );
2803 let _region = t.add(
2804 Some(sub),
2805 None,
2806 TreeKind::FieldRegion {
2807 items: vec![crate::FieldItem {
2808 marker: None,
2809 key: Some("Name".into()),
2810 value: Some("Duck".into()),
2811 value_kind: Some("read_only".into()),
2812 }],
2813 },
2814 );
2815 let table = t.add(
2816 Some(sub),
2817 None,
2818 TreeKind::Table {
2819 table: Table {
2820 rows: vec![vec!["a \n<".into(), "b".into()]],
2821 cells: Some(vec![
2822 crate::TableCell {
2823 text: "a \n<".into(),
2824 bbox: None,
2825 start_row: 0,
2826 start_col: 0,
2827 row_span: 3,
2828 col_span: 1,
2829 column_header: false,
2830 row_header: true,
2831 row_section: false,
2832 },
2833 crate::TableCell {
2834 text: "b".into(),
2835 bbox: None,
2836 start_row: 0,
2837 start_col: 1,
2838 row_span: 1,
2839 col_span: 1,
2840 column_header: false,
2841 row_header: false,
2842 row_section: false,
2843 },
2844 ]),
2845 ..Table::default()
2846 },
2847 rich_cells: vec![(0, 1, 0)], captions: Vec::new(),
2849 },
2850 );
2851 let cell_group = t.add(
2852 Some(table),
2853 None,
2854 TreeKind::Group {
2855 label: "unspecified".into(),
2856 name: "rich_cell_group_1_0_0".into(),
2857 },
2858 );
2859 if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
2860 *rich_cells = vec![(0, 1, cell_group)];
2861 }
2862 let after = t.add(Some(sub), None, text("text", "after the region"));
2863 let _ = (title, after);
2864
2865 let doc = DoclingDocument {
2866 tree: Some(t),
2867 ..DoclingDocument::new("t")
2868 };
2869 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2870 let texts: Vec<&str> = v["texts"]
2872 .as_array()
2873 .unwrap()
2874 .iter()
2875 .map(|t| t["text"].as_str().unwrap())
2876 .collect();
2877 assert_eq!(
2878 texts,
2879 [
2880 "Page",
2881 "Heading",
2882 "bold",
2883 "x = 1",
2884 "Sub",
2885 "item",
2886 "Name",
2887 "Duck",
2888 "after the region"
2889 ]
2890 );
2891 assert_eq!(
2892 v["body"]["children"],
2893 serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}])
2894 );
2895 assert_eq!(v["texts"][0]["content_layer"], "furniture");
2896 assert_eq!(
2897 v["texts"][1]["children"],
2898 serde_json::json!([{"$ref": "#/groups/0"}, {"$ref": "#/texts/4"}])
2899 );
2900 let bold = &v["texts"][2];
2901 assert_eq!(bold["parent"]["$ref"], "#/groups/0");
2902 let keys: Vec<&str> = bold
2903 .as_object()
2904 .unwrap()
2905 .keys()
2906 .map(String::as_str)
2907 .collect();
2908 assert_eq!(
2909 keys,
2910 [
2911 "self_ref",
2912 "parent",
2913 "children",
2914 "content_layer",
2915 "label",
2916 "prov",
2917 "orig",
2918 "text",
2919 "formatting",
2920 "hyperlink"
2921 ]
2922 );
2923 assert_eq!(
2924 bold["formatting"],
2925 serde_json::json!({"bold": true, "italic": false, "underline": false, "strikethrough": false, "script": "baseline"})
2926 );
2927 let code = &v["texts"][3];
2928 assert_eq!(code["label"], "code");
2929 assert_eq!(code["code_language"], "Python");
2930 let sub = &v["texts"][4];
2931 assert_eq!(sub["orig"], "Sub\u{2019}");
2932 assert_eq!(sub["level"], 1);
2933 let item = &v["texts"][5];
2934 let keys: Vec<&str> = item
2935 .as_object()
2936 .unwrap()
2937 .keys()
2938 .map(String::as_str)
2939 .collect();
2940 assert_eq!(
2941 keys,
2942 [
2943 "self_ref",
2944 "parent",
2945 "children",
2946 "content_layer",
2947 "label",
2948 "prov",
2949 "orig",
2950 "text",
2951 "enumerated",
2952 "marker"
2953 ]
2954 );
2955 assert_eq!(item["marker"], "3.");
2956 assert_eq!(v["texts"][7]["kind"], "read_only");
2957 assert_eq!(v["field_regions"][0]["parent"]["$ref"], "#/texts/4");
2958 let table = &v["tables"][0];
2959 assert_eq!(
2960 table["children"],
2961 serde_json::json!([{"$ref": "#/groups/1"}])
2962 );
2963 let cells = table["data"]["table_cells"].as_array().unwrap();
2964 assert_eq!(
2965 cells[0]["text"], "a \n<",
2966 "raw cell text is written verbatim"
2967 );
2968 assert_eq!(
2969 cells[0]["end_row_offset_idx"], 3,
2970 "declared spans are not clamped"
2971 );
2972 assert_eq!(cells[1]["ref"], serde_json::json!({"$ref": "#/groups/1"}));
2973 assert!(cells[0].get("ref").is_none());
2974 assert!(
2975 table["data"]["grid"][0][1].get("ref").is_none(),
2976 "the grid shows plain cells"
2977 );
2978 assert_eq!(v["groups"][1]["name"], "rich_cell_group_1_0_0");
2979 }
2980
2981 #[test]
2985 fn a_comment_section_can_be_referenced_by_its_note_text() {
2986 let doc = DoclingDocument {
2987 name: "c".into(),
2988 nodes: vec![
2989 Node::Commented {
2990 comments: vec![0],
2991 inner: Box::new(Node::Paragraph {
2992 text: "annotated".into(),
2993 }),
2994 },
2995 Node::CommentSection {
2996 name: "comment-Sheet1-A1".into(),
2997 text: "[author: A]: note".into(),
2998 refs_note_text: true,
2999 grouped: true,
3000 },
3001 ],
3002 ..DoclingDocument::new("c")
3003 };
3004 let v = crate::json::to_json(&doc);
3005 assert_eq!(v["groups"][0]["name"], "comment-Sheet1-A1");
3006 assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/texts/1");
3007 }
3008
3009 #[test]
3013 fn comment_sections_link_back_to_their_items() {
3014 let doc = DoclingDocument {
3015 name: "c".into(),
3016 nodes: vec![
3017 Node::Commented {
3018 comments: vec![0],
3019 inner: Box::new(Node::Paragraph {
3020 text: "annotated".into(),
3021 }),
3022 },
3023 Node::Paragraph {
3024 text: "plain".into(),
3025 },
3026 Node::CommentSection {
3027 name: "comment-7".into(),
3028 text: "[time: t]: note".into(),
3029 refs_note_text: false,
3030 grouped: true,
3031 },
3032 ],
3033 ..DoclingDocument::new("c")
3034 };
3035 let v = crate::json::to_json(&doc);
3036 assert_eq!(v["groups"][0]["label"], "comment_section");
3038 assert_eq!(v["groups"][0]["name"], "comment-7");
3039 assert_eq!(v["groups"][0]["content_layer"], "notes");
3040 assert_eq!(v["groups"][0]["children"][0]["$ref"], "#/texts/2");
3041 assert_eq!(v["texts"][2]["content_layer"], "notes");
3042 assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/groups/0");
3044 assert!(v["texts"][1].get("comments").is_none());
3045 let keys: Vec<&str> = v["texts"][0]
3047 .as_object()
3048 .unwrap()
3049 .keys()
3050 .map(String::as_str)
3051 .collect();
3052 assert_eq!(
3053 &keys[keys.len() - 4..],
3054 &["prov", "comments", "orig", "text"]
3055 );
3056 }
3057
3058 fn picture(caption: &str, caption_parent: CaptionParent) -> Node {
3059 Node::Picture {
3060 caption: Some(caption.into()),
3061 caption_href: None,
3062 image: None,
3063 classification: None,
3064 caption_parent,
3065 }
3066 }
3067
3068 fn group(children: Vec<Node>) -> Node {
3069 Node::Group {
3070 label: "section".into(),
3071 name: None,
3072 layer: None,
3073 children,
3074 }
3075 }
3076
3077 fn refs(v: &Value) -> Vec<&str> {
3078 v.as_array()
3079 .unwrap()
3080 .iter()
3081 .map(|r| r["$ref"].as_str().unwrap())
3082 .collect()
3083 }
3084
3085 #[test]
3090 fn a_body_caption_follows_the_enclosing_top_level_item() {
3091 let mut doc = DoclingDocument::new("t");
3092 doc.push(picture("top", CaptionParent::Body));
3093 doc.push(group(vec![
3094 Node::Paragraph { text: "p".into() },
3095 picture("nested", CaptionParent::Body),
3096 ]));
3097 doc.push(Node::Paragraph {
3098 text: "after".into(),
3099 });
3100 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3101 assert_eq!(
3102 refs(&v["body"]["children"]),
3103 [
3104 "#/texts/0",
3105 "#/pictures/0",
3106 "#/groups/0",
3107 "#/texts/2",
3108 "#/texts/3"
3109 ]
3110 );
3111 assert_eq!(
3112 refs(&v["groups"][0]["children"]),
3113 ["#/texts/1", "#/pictures/1"]
3114 );
3115 for (cap, pic) in [(0, 0), (2, 1)] {
3116 assert_eq!(v["texts"][cap]["label"], "caption");
3117 assert_eq!(v["texts"][cap]["parent"]["$ref"], "#/body");
3118 assert_eq!(
3119 refs(&v["pictures"][pic]["captions"]),
3120 [format!("#/texts/{cap}")]
3121 );
3122 assert_eq!(v["pictures"][pic]["children"], serde_json::json!([]));
3123 }
3124 }
3125
3126 #[test]
3129 fn an_item_caption_is_the_items_first_child() {
3130 let mut doc = DoclingDocument::new("t");
3131 doc.push(picture("fig", CaptionParent::Item));
3132 doc.push(Node::Table(Table {
3133 rows: vec![vec!["a".into()]],
3134 caption: Some("tab".into()),
3135 caption_parent: CaptionParent::Item,
3136 ..Table::default()
3137 }));
3138 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3139 assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/tables/0"]);
3140 assert_eq!(v["texts"][0]["parent"]["$ref"], "#/pictures/0");
3141 assert_eq!(refs(&v["pictures"][0]["children"]), ["#/texts/0"]);
3142 assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
3143 assert_eq!(v["texts"][1]["parent"]["$ref"], "#/tables/0");
3144 assert_eq!(refs(&v["tables"][0]["children"]), ["#/texts/1"]);
3145 assert_eq!(refs(&v["tables"][0]["captions"]), ["#/texts/1"]);
3146 }
3147
3148 #[test]
3152 fn a_container_caption_is_the_items_sibling() {
3153 let mut doc = DoclingDocument::new("t");
3154 doc.push(group(vec![
3155 picture("chart", CaptionParent::Container),
3156 Node::Table(Table {
3157 rows: vec![vec!["a".into()]],
3158 caption: Some("figcaption".into()),
3159 caption_parent: CaptionParent::ContainerAfter,
3160 ..Table::default()
3161 }),
3162 ]));
3163 let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3164 assert_eq!(refs(&v["body"]["children"]), ["#/groups/0"]);
3165 assert_eq!(
3166 refs(&v["groups"][0]["children"]),
3167 ["#/texts/0", "#/pictures/0", "#/tables/0", "#/texts/1"]
3168 );
3169 assert_eq!(v["texts"][0]["parent"]["$ref"], "#/groups/0");
3170 assert_eq!(v["texts"][1]["parent"]["$ref"], "#/groups/0");
3171 assert_eq!(v["pictures"][0]["children"], serde_json::json!([]));
3172 assert_eq!(v["tables"][0]["children"], serde_json::json!([]));
3173 }
3174}