-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathtest_docling_doc.py
More file actions
2724 lines (2222 loc) · 94 KB
/
Copy pathtest_docling_doc.py
File metadata and controls
2724 lines (2222 loc) · 94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import itertools
import os
import re
import warnings
from collections import deque
from copy import deepcopy
from io import BytesIO
from pathlib import Path
from typing import Optional, Union
from unittest.mock import Mock
import pytest
import yaml
from PIL import Image as PILImage
from pydantic import AnyUrl, BaseModel, ValidationError
from docling_core.types.doc import (
BoundingBox,
CodeItem,
ContentLayer,
CoordOrigin,
DocItem,
DocItemLabel,
DoclingDocument,
DocumentOrigin,
FloatingItem,
Formatting,
FormItem,
FormulaItem,
GraphCell,
GraphCellLabel,
GraphData,
GraphLink,
GraphLinkLabel,
GroupLabel,
ImageRef,
ImageRefMode,
KeyValueItem,
ListItem,
NodeItem,
Orientation,
PictureItem,
PictureMeta,
ProvenanceItem,
RefItem,
RichTableCell,
SectionHeaderItem,
Size,
TableCell,
TableData,
TableItem,
TabularChartMetaField,
TextItem,
TitleItem,
)
from docling_core.types.doc.document import (
CURRENT_VERSION,
FieldHeadingItem,
FieldItem,
FieldRegionItem,
FieldValueItem,
PageItem,
)
from docling_core.types.doc.webvtt import WebVTTFile
from docling_core.utils.settings import settings
from .test_data_gen_flag import GEN_TEST_DATA
def test_doc_origin():
DocumentOrigin(
mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
filename="myfile.pdf",
binary_hash="50115d582a0897fe1dd520a6876ec3f9321690ed0f6cfdc99a8d09019be073e8",
)
def test_overlaps_horizontally():
# Overlapping horizontally
bbox1 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2 = BoundingBox(l=5, t=5, r=15, b=15, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.overlaps_horizontally(bbox2) is True
# No overlap horizontally (disjoint on the right)
bbox3 = BoundingBox(l=11, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.overlaps_horizontally(bbox3) is False
# No overlap horizontally (disjoint on the left)
bbox4 = BoundingBox(l=-10, t=0, r=-1, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.overlaps_horizontally(bbox4) is False
# Full containment
bbox5 = BoundingBox(l=2, t=2, r=8, b=8, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.overlaps_horizontally(bbox5) is True
# Edge touching (no overlap)
bbox6 = BoundingBox(l=10, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.overlaps_horizontally(bbox6) is False
def test_overlaps_vertically():
page_height = 300
# Same CoordOrigin (TOPLEFT)
bbox1 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2 = BoundingBox(l=5, t=5, r=15, b=15, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.overlaps_vertically(bbox2) is True
bbox1_ = bbox1.to_bottom_left_origin(page_height=page_height)
bbox2_ = bbox2.to_bottom_left_origin(page_height=page_height)
assert bbox1_.overlaps_vertically(bbox2_) is True
bbox3 = BoundingBox(l=0, t=11, r=10, b=20, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.overlaps_vertically(bbox3) is False
bbox3_ = bbox3.to_bottom_left_origin(page_height=page_height)
assert bbox1_.overlaps_vertically(bbox3_) is False
# Same CoordOrigin (BOTTOMLEFT)
bbox4 = BoundingBox(l=0, b=20, r=10, t=30, coord_origin=CoordOrigin.BOTTOMLEFT)
bbox5 = BoundingBox(l=5, b=15, r=15, t=25, coord_origin=CoordOrigin.BOTTOMLEFT)
assert bbox4.overlaps_vertically(bbox5) is True
bbox4_ = bbox4.to_top_left_origin(page_height=page_height)
bbox5_ = bbox5.to_top_left_origin(page_height=page_height)
assert bbox4_.overlaps_vertically(bbox5_) is True
bbox6 = BoundingBox(l=0, b=31, r=10, t=40, coord_origin=CoordOrigin.BOTTOMLEFT)
assert bbox4.overlaps_vertically(bbox6) is False
bbox6_ = bbox6.to_top_left_origin(page_height=page_height)
assert bbox4_.overlaps_vertically(bbox6_) is False
# Different CoordOrigin
with pytest.raises(ValueError):
bbox1.overlaps_vertically(bbox4)
def test_add_picture_supports_chart_label():
doc = DoclingDocument(name="Chart Doc")
chart = doc.add_picture(label=DocItemLabel.CHART)
picture = doc.add_picture()
assert chart.label == DocItemLabel.CHART
assert picture.label == DocItemLabel.PICTURE
assert doc.pictures == [chart, picture]
def test_insert_picture_supports_chart_label():
doc = DoclingDocument(name="Chart Doc")
text = doc.add_text(label=DocItemLabel.TEXT, text="before chart")
chart = doc.insert_picture(sibling=text, label=DocItemLabel.CHART)
assert chart.label == DocItemLabel.CHART
assert doc.pictures == [chart]
assert doc.body.children[1] == chart.get_ref()
def test_chart_picture_tabular_meta_exports_to_markdown_by_default():
doc = DoclingDocument(name="Chart Doc")
chart = doc.add_picture(label=DocItemLabel.CHART)
chart.meta = PictureMeta(
tabular_chart=TabularChartMetaField(
chart_data=TableData(
num_rows=3,
num_cols=2,
table_cells=[
TableCell(
text="Quarter",
start_row_offset_idx=0,
end_row_offset_idx=1,
start_col_offset_idx=0,
end_col_offset_idx=1,
column_header=True,
),
TableCell(
text="Revenue",
start_row_offset_idx=0,
end_row_offset_idx=1,
start_col_offset_idx=1,
end_col_offset_idx=2,
column_header=True,
),
TableCell(
text="Q1",
start_row_offset_idx=1,
end_row_offset_idx=2,
start_col_offset_idx=0,
end_col_offset_idx=1,
),
TableCell(
text="12.3",
start_row_offset_idx=1,
end_row_offset_idx=2,
start_col_offset_idx=1,
end_col_offset_idx=2,
),
TableCell(
text="Q2",
start_row_offset_idx=2,
end_row_offset_idx=3,
start_col_offset_idx=0,
end_col_offset_idx=1,
),
TableCell(
text="14.2",
start_row_offset_idx=2,
end_row_offset_idx=3,
start_col_offset_idx=1,
end_col_offset_idx=2,
),
],
)
)
)
markdown = doc.export_to_markdown()
assert "<!-- image -->" in markdown
assert "| Quarter | Revenue |" in markdown
assert "| Q1 | 12.3 |" in markdown
assert "| Q2 | 14.2 |" in markdown
markdown_without_chart_table = doc.export_to_markdown(enable_chart_tables=False)
assert "| Quarter | Revenue |" not in markdown_without_chart_table
assert "| Q1 | 12.3 |" not in markdown_without_chart_table
html = doc.export_to_html()
assert "<th>Quarter</th><th>Revenue</th>" in html
assert "<td>12.3</td>" in html
html_without_chart_table = doc.export_to_html(enable_chart_tables=False)
assert "<th>Quarter</th><th>Revenue</th>" not in html_without_chart_table
assert "<td>12.3</td>" not in html_without_chart_table
def test_intersection_area_with():
page_height = 300
# Overlapping bounding boxes (TOPLEFT)
bbox1 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2 = BoundingBox(l=5, t=5, r=15, b=15, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.intersection_area_with(bbox2) - 25.0) < 1.0e-3
bbox1_ = bbox1.to_bottom_left_origin(page_height=page_height)
bbox2_ = bbox2.to_bottom_left_origin(page_height=page_height)
assert abs(bbox1_.intersection_area_with(bbox2_) - 25.0) < 1.0e-3
# Non-overlapping bounding boxes (TOPLEFT)
bbox3 = BoundingBox(l=11, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.intersection_area_with(bbox3) - 0.0) < 1.0e-3
# Touching edges (no intersection, TOPLEFT)
bbox4 = BoundingBox(l=10, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.intersection_area_with(bbox4) - 0.0) < 1.0e-3
# Fully contained (TOPLEFT)
bbox5 = BoundingBox(l=2, t=2, r=8, b=8, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.intersection_area_with(bbox5) - 36.0) < 1.0e-3
# Overlapping bounding boxes (BOTTOMLEFT)
bbox6 = BoundingBox(l=0, t=10, r=10, b=0, coord_origin=CoordOrigin.BOTTOMLEFT)
bbox7 = BoundingBox(l=5, t=15, r=15, b=5, coord_origin=CoordOrigin.BOTTOMLEFT)
assert abs(bbox6.intersection_area_with(bbox7) - 25.0) < 1.0e-3
# Different CoordOrigins (raises ValueError)
with pytest.raises(ValueError):
bbox1.intersection_area_with(bbox6)
def test_x_overlap_with():
bbox1 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2 = BoundingBox(l=5, t=0, r=15, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.x_overlap_with(bbox2) - 5.0) < 1.0e-3
# No overlap (disjoint right)
bbox3 = BoundingBox(l=11, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.x_overlap_with(bbox3) - 0.0) < 1.0e-3
# No overlap (disjoint left)
bbox4 = BoundingBox(l=-10, t=0, r=-1, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.x_overlap_with(bbox4) - 0.0) < 1.0e-3
# Touching edges
bbox5 = BoundingBox(l=10, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.x_overlap_with(bbox5) - 0.0) < 1.0e-3
# Full containment
bbox6 = BoundingBox(l=2, t=0, r=8, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.x_overlap_with(bbox6) - 6.0) < 1.0e-3
# Identical boxes
bbox7 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.x_overlap_with(bbox7) - 10.0) < 1.0e-3
# Different CoordOrigin
bbox_bl = BoundingBox(l=0, t=10, r=10, b=0, coord_origin=CoordOrigin.BOTTOMLEFT)
with pytest.raises(ValueError):
bbox1.x_overlap_with(bbox_bl)
def test_y_overlap_with():
# TOPLEFT origin
bbox1_tl = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2_tl = BoundingBox(l=0, t=5, r=10, b=15, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1_tl.y_overlap_with(bbox2_tl) - 5.0) < 1.0e-3
# No overlap (disjoint below)
bbox3_tl = BoundingBox(l=0, t=11, r=10, b=20, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1_tl.y_overlap_with(bbox3_tl) - 0.0) < 1.0e-3
# Touching edges
bbox4_tl = BoundingBox(l=0, t=10, r=10, b=20, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1_tl.y_overlap_with(bbox4_tl) - 0.0) < 1.0e-3
# Full containment
bbox5_tl = BoundingBox(l=0, t=2, r=10, b=8, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1_tl.y_overlap_with(bbox5_tl) - 6.0) < 1.0e-3
# BOTTOMLEFT origin
bbox1_bl = BoundingBox(l=0, b=0, r=10, t=10, coord_origin=CoordOrigin.BOTTOMLEFT)
bbox2_bl = BoundingBox(l=0, b=5, r=10, t=15, coord_origin=CoordOrigin.BOTTOMLEFT)
assert abs(bbox1_bl.y_overlap_with(bbox2_bl) - 5.0) < 1.0e-3
# No overlap (disjoint above)
bbox3_bl = BoundingBox(l=0, b=11, r=10, t=20, coord_origin=CoordOrigin.BOTTOMLEFT)
assert abs(bbox1_bl.y_overlap_with(bbox3_bl) - 0.0) < 1.0e-3
# Touching edges
bbox4_bl = BoundingBox(l=0, b=10, r=10, t=20, coord_origin=CoordOrigin.BOTTOMLEFT)
assert abs(bbox1_bl.y_overlap_with(bbox4_bl) - 0.0) < 1.0e-3
# Full containment
bbox5_bl = BoundingBox(l=0, b=2, r=10, t=8, coord_origin=CoordOrigin.BOTTOMLEFT)
assert abs(bbox1_bl.y_overlap_with(bbox5_bl) - 6.0) < 1.0e-3
# Different CoordOrigin
with pytest.raises(ValueError):
bbox1_tl.y_overlap_with(bbox1_bl)
def test_union_area_with():
# Overlapping (TOPLEFT)
bbox1 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT) # Area 100
bbox2 = BoundingBox(l=5, t=5, r=15, b=15, coord_origin=CoordOrigin.TOPLEFT) # Area 100
# Intersection area 25
# Union area = 100 + 100 - 25 = 175
assert abs(bbox1.union_area_with(bbox2) - 175.0) < 1.0e-3
# Non-overlapping (TOPLEFT)
bbox3 = BoundingBox(l=20, t=0, r=30, b=10, coord_origin=CoordOrigin.TOPLEFT) # Area 100
# Union area = 100 + 100 - 0 = 200
assert abs(bbox1.union_area_with(bbox3) - 200.0) < 1.0e-3
# Touching edges (TOPLEFT)
bbox4 = BoundingBox(l=10, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT) # Area 100
# Union area = 100 + 100 - 0 = 200
assert abs(bbox1.union_area_with(bbox4) - 200.0) < 1.0e-3
# Full containment (TOPLEFT)
bbox5 = BoundingBox(l=2, t=2, r=8, b=8, coord_origin=CoordOrigin.TOPLEFT) # Area 36
# Union area = 100 + 36 - 36 = 100
assert abs(bbox1.union_area_with(bbox5) - 100.0) < 1.0e-3
# Overlapping (BOTTOMLEFT)
bbox6 = BoundingBox(l=0, b=0, r=10, t=10, coord_origin=CoordOrigin.BOTTOMLEFT) # Area 100
bbox7 = BoundingBox(l=5, b=5, r=15, t=15, coord_origin=CoordOrigin.BOTTOMLEFT) # Area 100
# Intersection area 25
# Union area = 100 + 100 - 25 = 175
assert abs(bbox6.union_area_with(bbox7) - 175.0) < 1.0e-3
# Different CoordOrigin
with pytest.raises(ValueError):
bbox1.union_area_with(bbox6)
def test_x_union_with():
bbox1 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2 = BoundingBox(l=5, t=0, r=15, b=10, coord_origin=CoordOrigin.TOPLEFT)
# x_union = max(10, 15) - min(0, 5) = 15 - 0 = 15
assert abs(bbox1.x_union_with(bbox2) - 15.0) < 1.0e-3
# No overlap (disjoint)
bbox3 = BoundingBox(l=20, t=0, r=30, b=10, coord_origin=CoordOrigin.TOPLEFT)
# x_union = max(10, 30) - min(0, 20) = 30 - 0 = 30
assert abs(bbox1.x_union_with(bbox3) - 30.0) < 1.0e-3
# Touching edges
bbox4 = BoundingBox(l=10, t=0, r=20, b=10, coord_origin=CoordOrigin.TOPLEFT)
# x_union = max(10, 20) - min(0, 10) = 20 - 0 = 20
assert abs(bbox1.x_union_with(bbox4) - 20.0) < 1.0e-3
# Full containment
bbox5 = BoundingBox(l=2, t=0, r=8, b=10, coord_origin=CoordOrigin.TOPLEFT)
# x_union = max(10, 8) - min(0, 2) = 10 - 0 = 10
assert abs(bbox1.x_union_with(bbox5) - 10.0) < 1.0e-3
# Identical boxes
bbox6 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
assert abs(bbox1.x_union_with(bbox6) - 10.0) < 1.0e-3
# Different CoordOrigin
bbox_bl = BoundingBox(l=0, t=10, r=10, b=0, coord_origin=CoordOrigin.BOTTOMLEFT)
with pytest.raises(ValueError):
bbox1.x_union_with(bbox_bl)
def test_y_union_with():
bbox1_tl = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2_tl = BoundingBox(l=0, t=5, r=10, b=15, coord_origin=CoordOrigin.TOPLEFT)
# y_union = max(10, 15) - min(0, 5) = 15 - 0 = 15
assert abs(bbox1_tl.y_union_with(bbox2_tl) - 15.0) < 1.0e-3
# No overlap (disjoint below)
bbox3_tl = BoundingBox(l=0, t=20, r=10, b=30, coord_origin=CoordOrigin.TOPLEFT)
# y_union = max(10, 30) - min(0, 20) = 30 - 0 = 30
assert abs(bbox1_tl.y_union_with(bbox3_tl) - 30.0) < 1.0e-3
# Touching edges
bbox4_tl = BoundingBox(l=0, t=10, r=10, b=20, coord_origin=CoordOrigin.TOPLEFT)
# y_union = max(10, 20) - min(0, 10) = 20 - 0 = 20
assert abs(bbox1_tl.y_union_with(bbox4_tl) - 20.0) < 1.0e-3
# Full containment
bbox5_tl = BoundingBox(l=0, t=2, r=10, b=8, coord_origin=CoordOrigin.TOPLEFT)
# y_union = max(10, 8) - min(0, 2) = 10 - 0 = 10
assert abs(bbox1_tl.y_union_with(bbox5_tl) - 10.0) < 1.0e-3
# BOTTOMLEFT origin
bbox1_bl = BoundingBox(l=0, b=0, r=10, t=10, coord_origin=CoordOrigin.BOTTOMLEFT)
bbox2_bl = BoundingBox(l=0, b=5, r=10, t=15, coord_origin=CoordOrigin.BOTTOMLEFT)
# y_union = max(10, 15) - min(0, 5) = 15 - 0 = 15
assert abs(bbox1_bl.y_union_with(bbox2_bl) - 15.0) < 1.0e-3
# No overlap (disjoint above)
bbox3_bl = BoundingBox(l=0, b=20, r=10, t=30, coord_origin=CoordOrigin.BOTTOMLEFT)
# y_union = max(10, 30) - min(0, 20) = 30 - 0 = 30
assert abs(bbox1_bl.y_union_with(bbox3_bl) - 30.0) < 1.0e-3
# Touching edges
bbox4_bl = BoundingBox(l=0, b=10, r=10, t=20, coord_origin=CoordOrigin.BOTTOMLEFT)
# y_union = max(10, 20) - min(0, 10) = 20 - 0 = 20
assert abs(bbox1_bl.y_union_with(bbox4_bl) - 20.0) < 1.0e-3
# Full containment
bbox5_bl = BoundingBox(l=0, b=2, r=10, t=8, coord_origin=CoordOrigin.BOTTOMLEFT)
# y_union = max(10, 8) - min(0, 2) = 10 - 0 = 10
assert abs(bbox1_bl.y_union_with(bbox5_bl) - 10.0) < 1.0e-3
# Different CoordOrigin
with pytest.raises(ValueError):
bbox1_tl.y_union_with(bbox1_bl)
def test_orientation():
page_height = 300
# Same CoordOrigin (TOPLEFT)
bbox1 = BoundingBox(l=0, t=0, r=10, b=10, coord_origin=CoordOrigin.TOPLEFT)
bbox2 = BoundingBox(l=5, t=5, r=15, b=15, coord_origin=CoordOrigin.TOPLEFT)
bbox3 = BoundingBox(l=11, t=5, r=15, b=15, coord_origin=CoordOrigin.TOPLEFT)
bbox4 = BoundingBox(l=0, t=11, r=10, b=15, coord_origin=CoordOrigin.TOPLEFT)
assert bbox1.is_left_of(bbox2) is True
assert bbox1.is_strictly_left_of(bbox2) is False
assert bbox1.is_strictly_left_of(bbox3) is True
bbox1_ = bbox1.to_bottom_left_origin(page_height=page_height)
bbox2_ = bbox2.to_bottom_left_origin(page_height=page_height)
bbox3.to_bottom_left_origin(page_height=page_height)
bbox4_ = bbox4.to_bottom_left_origin(page_height=page_height)
assert bbox1.is_above(bbox2) is True
assert bbox1_.is_above(bbox2_) is True
assert bbox1.is_strictly_above(bbox4) is True
assert bbox1_.is_strictly_above(bbox4_) is True
def test_docitems():
# Iterative function to find all subclasses
def find_all_subclasses_iterative(base_class):
subclasses = deque([base_class]) # Use a deque for efficient popping from the front
all_subclasses = []
while subclasses:
current_class = subclasses.popleft() # Get the next class to process
for subclass in current_class.__subclasses__():
all_subclasses.append(subclass)
subclasses.append(subclass) # Add the subclass for further exploration
return all_subclasses
def serialise(obj):
return yaml.safe_dump(obj.model_dump(mode="json", by_alias=True))
def write(name: str, serialisation: str):
with open(f"./test/data/docling_document/unit/{name}.yaml", "w", encoding="utf-8") as fw:
fw.write(serialisation)
def read(name: str):
with open(f"./test/data/docling_document/unit/{name}.yaml", encoding="utf-8") as fr:
gold = fr.read()
return yaml.safe_load(gold)
def verify(dc, obj):
pred = serialise(obj).strip()
if dc is KeyValueItem or dc is FormItem:
write(dc.__name__, pred)
pred = yaml.safe_load(pred)
# print(f"\t{dc.__name__}:\n {pred}")
gold = read(dc.__name__)
assert pred == gold, f"pred!=gold for {dc.__name__}"
# Iterate over the derived classes of the BaseClass
derived_classes = find_all_subclasses_iterative(DocItem)
for dc in derived_classes:
if dc is TextItem:
obj = dc(
text="whatever",
orig="whatever",
label=DocItemLabel.TEXT,
self_ref="#",
)
verify(dc, obj)
elif dc is ListItem:
obj = dc(
text="whatever",
orig="whatever",
marker="(1)",
enumerated=True,
self_ref="#",
)
verify(dc, obj)
elif dc is FloatingItem:
obj = dc(
label=DocItemLabel.TEXT,
self_ref="#",
)
verify(dc, obj)
elif dc is KeyValueItem:
graph = GraphData(
cells=[
GraphCell(
label=GraphCellLabel.KEY,
cell_id=0,
text="number",
orig="#",
),
GraphCell(
label=GraphCellLabel.VALUE,
cell_id=1,
text="1",
orig="1",
),
],
links=[
GraphLink(
label=GraphLinkLabel.TO_VALUE,
source_cell_id=0,
target_cell_id=1,
),
GraphLink(label=GraphLinkLabel.TO_KEY, source_cell_id=1, target_cell_id=0),
],
)
obj = dc(
label=DocItemLabel.KEY_VALUE_REGION,
graph=graph,
self_ref="#",
)
verify(dc, obj)
elif dc is FormItem:
graph = GraphData(
cells=[
GraphCell(
label=GraphCellLabel.KEY,
cell_id=0,
text="number",
orig="#",
),
GraphCell(
label=GraphCellLabel.VALUE,
cell_id=1,
text="1",
orig="1",
),
],
links=[
GraphLink(
label=GraphLinkLabel.TO_VALUE,
source_cell_id=0,
target_cell_id=1,
),
GraphLink(label=GraphLinkLabel.TO_KEY, source_cell_id=1, target_cell_id=0),
],
)
obj = dc(
label=DocItemLabel.FORM,
graph=graph,
self_ref="#",
)
verify(dc, obj)
elif dc is TitleItem:
obj = dc(
text="whatever",
orig="whatever",
label=DocItemLabel.TITLE,
self_ref="#",
)
verify(dc, obj)
elif dc is SectionHeaderItem:
obj = dc(
text="whatever",
orig="whatever",
label=DocItemLabel.SECTION_HEADER,
self_ref="#",
level=2,
)
verify(dc, obj)
elif dc is PictureItem:
obj = dc(
self_ref="#",
)
verify(dc, obj)
elif dc is TableItem:
obj = dc(
self_ref="#",
data=TableData(num_rows=3, num_cols=5, table_cells=[]),
)
verify(dc, obj)
elif dc is CodeItem:
obj = dc(
self_ref="#",
orig="whatever",
text="print(Hello World!)",
code_language="Python",
)
verify(dc, obj)
elif dc is FormulaItem:
obj = dc(
self_ref="#",
orig="whatever",
text="E=mc^2",
)
verify(dc, obj)
elif dc is FieldRegionItem:
obj = dc(
self_ref="#",
)
verify(dc, obj)
elif dc is FieldItem:
obj = dc(
self_ref="#",
)
verify(dc, obj)
elif dc is FieldValueItem:
obj = dc(
self_ref="#",
orig="whatever",
text="whatever",
kind="fillable",
)
verify(dc, obj)
elif dc is FieldHeadingItem:
obj = dc(
text="whatever",
orig="whatever",
label=DocItemLabel.FIELD_HEADING,
self_ref="#",
level=2,
)
verify(dc, obj)
elif dc is GraphData: # we skip this on purpose
continue
else:
raise RuntimeError(f"New derived class detected {dc.__name__}")
def test_reference_doc():
filename = "test/data/doc/dummy_doc.yaml"
# Read YAML file of manual reference doc
with open(filename, encoding="utf-8") as fp:
dict_from_yaml = yaml.safe_load(fp)
doc = DoclingDocument.model_validate(dict_from_yaml)
# Objects can be accessed
text_item = doc.texts[0]
# access members
text_item.text
text_item.prov[0].page_no
# Objects that are references need explicit resolution for now:
obj = doc.texts[2] # Text item with parent
parent = obj.parent.resolve(doc=doc) # it is a figure
obj2 = parent.children[0].resolve(doc=doc) # Child of figure must be the same as obj
assert obj == obj2
assert obj is obj2
# Iterate all elements
for item, level in doc.iterate_items():
_ = f"Item: {item} at level {level}"
# print(f"Item: {item} at level {level}")
# Serialize and reload
_test_serialize_and_reload(doc)
# Call Export methods
_test_export_methods(doc, filename=filename)
def test_parse_doc():
filename = "test/data/doc/2206.01062.yaml"
with open(filename, encoding="utf-8") as fp:
dict_from_yaml = yaml.safe_load(fp)
doc = DoclingDocument.model_validate(dict_from_yaml)
page_break = "<!-- page break -->"
_test_export_methods(doc, filename=filename, page_break_placeholder=page_break)
_test_serialize_and_reload(doc)
def test_construct_doc(sample_doc):
filename = "test/data/doc/constructed_document.yaml"
assert sample_doc.validate_tree(sample_doc.body)
# check that deprecation warning for furniture has been raised.
with pytest.warns(DeprecationWarning, match="deprecated"):
assert sample_doc.validate_tree(sample_doc.furniture)
_test_export_methods(sample_doc, filename=filename)
_test_serialize_and_reload(sample_doc)
def test_construct_bad_doc():
filename = "test/data/doc/bad_doc.yaml"
doc = _construct_bad_doc()
with pytest.raises(ValueError):
doc.validate_tree(doc.body, raise_on_error=True)
with pytest.raises(ValueError):
_test_export_methods(doc, filename=filename)
with pytest.raises(ValueError):
_test_serialize_and_reload(doc)
def _test_serialize_and_reload(doc):
### Serialize and deserialize stuff
yaml_dump = yaml.safe_dump(doc.model_dump(mode="json", by_alias=True))
# print(f"\n\n{yaml_dump}")
doc_reload = DoclingDocument.model_validate(yaml.safe_load(yaml_dump))
yaml_dump_reload = yaml.safe_dump(doc_reload.model_dump(mode="json", by_alias=True))
assert yaml_dump == yaml_dump_reload, "yaml_dump!=yaml_dump_reload"
"""
for item, level in doc.iterate_items():
if isinstance(item, PictureItem):
_ = item.get_image(doc)
assert doc_reload == doc # must be equal
"""
assert doc_reload is not doc # can't be identical
def _verify_regression_test(pred: str, filename: str, ext: str):
if os.path.exists(filename + f".{ext}") and not GEN_TEST_DATA:
with open(filename + f".{ext}", encoding="utf-8") as fr:
gt_true = fr.read().rstrip()
assert gt_true == pred, f"Does not pass regression-test for {filename}.{ext}\n\n{gt_true}\n\n{pred}"
else:
with open(filename + f".{ext}", "w", encoding="utf-8") as fw:
fw.write(f"{pred}\n")
def _test_export_methods(doc: DoclingDocument, filename: str, page_break_placeholder: Optional[str] = None):
# Iterate all elements
et_pred = doc.export_to_element_tree()
_verify_regression_test(et_pred, filename=filename, ext="et")
# Export stuff
md_pred = doc.export_to_markdown()
_verify_regression_test(md_pred, filename=filename, ext="md")
if page_break_placeholder is not None:
md_pred = doc.export_to_markdown(page_break_placeholder=page_break_placeholder)
_verify_regression_test(md_pred, filename=filename, ext="paged.md")
# Test sHTML export ...
html_pred = doc.export_to_html()
_verify_regression_test(html_pred, filename=filename, ext="html")
# Test DocTags export ...
dt_pred = doc.export_to_doctags()
_verify_regression_test(dt_pred, filename=filename, ext="dt")
dt_min_pred = doc.export_to_doctags(minified=True)
_verify_regression_test(dt_min_pred, filename=filename, ext="min.dt")
# Test pages parameter in DocTags export
if doc.pages: # Only test if document has pages
first_page = min(doc.pages.keys())
second_page = first_page + 1
if second_page in doc.pages: # Only test if document has at least 2 pages
dt_pages_pred = doc.export_to_doctags(pages={first_page, second_page})
# print(dt_pages_pred)
_verify_regression_test(dt_pages_pred, filename=filename, ext="pages.dt")
# Test WebVTT export ...
# Note: Documents without TrackSource will result in empty WebVTT, but this is valid
vtt_pred = doc.export_to_vtt()
_verify_regression_test(vtt_pred, filename=filename, ext="vtt")
parsed = WebVTTFile.parse(vtt_pred)
assert isinstance(parsed, WebVTTFile)
assert not parsed.cue_blocks
# Test Tables export ...
for table in doc.tables:
table.export_to_markdown()
table.export_to_html(doc)
table.export_to_dataframe(doc)
table.export_to_doctags(doc)
# Test Images export ...
for fig in doc.pictures:
fig.export_to_doctags(doc)
def _construct_bad_doc():
doc = DoclingDocument(name="Bad doc")
title = doc.add_text(label=DocItemLabel.TITLE, text="This is the title")
group = doc.add_group(parent=title, name="chapter 1")
text = doc.add_text(
parent=group,
label=DocItemLabel.SECTION_HEADER,
text="This is the first section",
)
# Bend the parent of an element to be another.
text.parent = title.get_ref()
return doc
def test_pil_image():
doc = DoclingDocument(name="Untitled 1")
fig_image = PILImage.new(mode="RGB", size=(2, 2), color=(0, 0, 0))
doc.add_picture(image=ImageRef.from_pil(image=fig_image, dpi=72))
### Serialize and deserialize the document
yaml_dump = yaml.safe_dump(doc.model_dump(mode="json", by_alias=True))
doc_reload = DoclingDocument.model_validate(yaml.safe_load(yaml_dump))
reloaded_fig = doc_reload.pictures[0]
reloaded_image = reloaded_fig.image.pil_image
assert isinstance(reloaded_image, PILImage.Image)
assert reloaded_image.size == fig_image.size
assert reloaded_image.mode == fig_image.mode
assert reloaded_image.tobytes() == fig_image.tobytes()
def test_image_ref():
data_uri = {
"dpi": 72,
"mimetype": "image/png",
"size": {"width": 10, "height": 11},
"uri": "file:///tests/data/image.png",
}
image = ImageRef.model_validate(data_uri)
assert isinstance(image.uri, AnyUrl)
assert image.uri.scheme == "file"
assert image.uri.path == "/tests/data/image.png"
data_path = {
"dpi": 72,
"mimetype": "image/png",
"size": {"width": 10, "height": 11},
"uri": "./tests/data/image.png",
}
image = ImageRef.model_validate(data_path)
assert isinstance(image.uri, Path)
def test_image_ref_blocks_file_scheme():
"""Test that file:// URI scheme is blocked."""
fig_image = PILImage.new(mode="RGB", size=(2, 2), color=(0, 0, 0))
image_ref = ImageRef.from_pil(image=fig_image, dpi=72)
image_ref.uri = AnyUrl("file:///tmp/test.png")
with pytest.raises(ValueError, match="file:// URI scheme is not enabled"):
_ = image_ref.pil_image
def test_image_ref_blocks_oversized_base64():
"""Test that oversized base64 data URIs are blocked."""
import base64
large_bytes = b"X" * (28 * 1024 * 1024)
large_data = base64.b64encode(large_bytes).decode("ascii")
data_uri = f"data:image/png;base64,{large_data}"
image_ref = ImageRef(
dpi=72,
mimetype="image/png",
size=Size(width=100, height=100),
uri=AnyUrl(data_uri)
)
with pytest.raises(ValueError, match="exceeds size limit"):
_ = image_ref.pil_image
def test_image_ref_accepts_valid_base64():
"""Test that valid base64 data URIs within size limit work correctly."""
import base64
from io import BytesIO
fig_image = PILImage.new(mode="RGB", size=(1, 1), color=(255, 0, 0))
# Convert to base64 data URI
buffer = BytesIO()
fig_image.save(buffer, format="PNG")
img_bytes = buffer.getvalue()
img_base64 = base64.b64encode(img_bytes).decode("ascii")
data_uri = f"data:image/png;base64,{img_base64}"
# Create ImageRef with data URI
image_ref = ImageRef(
dpi=72,
mimetype="image/png",
size=Size(width=1, height=1),
uri=AnyUrl(data_uri)
)
# Should successfully decode the image
decoded_image = image_ref.pil_image
assert isinstance(decoded_image, PILImage.Image)
assert decoded_image.size == (1, 1)
assert decoded_image.mode == "RGB"
def test_file_uri_allowed_with_env_var():
"""Test that file:// URIs work when enabled via settings."""
test_img_path = Path("/tmp/test_docling_env.png")
img = PILImage.new("RGB", (100, 100), color="red")
img.save(test_img_path)
orig_allow_image_file_uri = settings.allow_image_file_uri
try:
settings.allow_image_file_uri = True
image_ref = ImageRef(
dpi=72,
mimetype="image/png",
size=Size(width=100, height=100),
uri=AnyUrl(f"file://{test_img_path}"),
)
pil_img = image_ref.pil_image
assert pil_img is not None
assert pil_img.size == (100, 100)
assert pil_img.mode == "RGB"
finally:
test_img_path.unlink(missing_ok=True)
settings.allow_image_file_uri = orig_allow_image_file_uri
def test_file_uri_blocked_by_default():
"""Test that file:// URIs are blocked by default."""