-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathdoclang.py
More file actions
2066 lines (1820 loc) · 81.7 KB
/
Copy pathdoclang.py
File metadata and controls
2066 lines (1820 loc) · 81.7 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
"""Define classes for DocLang serialization.
Aligned to the DocLang specification version ``_DOCLANG_VERSION``.
"""
import copy
import re
import warnings
import xml.etree.ElementTree as ET
from collections.abc import Callable
from enum import Enum
from itertools import groupby
from pathlib import Path
from typing import Annotated, Any, Optional, Union, cast
from defusedxml.ElementTree import fromstring
from defusedxml.minidom import parseString
from pydantic import BaseModel, Field, PrivateAttr
from pydantic.networks import AnyUrl
from typing_extensions import override
from docling_core.transforms.serializer._doclang_utils import (
_DOCLANG_LABEL_UNDEFINED,
_DOCLANG_META_TAG_DESCRIPTION,
_DOCLANG_META_TAG_SMILES,
_DOCLANG_META_TAG_SUMMARY,
_DOCLANG_VERSION,
DOCLANG_DFLT_RESOLUTION,
DOCLANG_NAMESPACE,
DocLangAttributeKey,
DocLangAttributeValue,
DocLangToken,
DocLangVocabulary,
_append_textual_fragment,
_code_language_label_from_doclang,
_code_language_label_to_doclang,
_create_location_tokens_for_bbox,
_create_location_tokens_for_item,
_merge_table_data,
_picture_classification_label_from_doclang,
_picture_classification_label_to_doclang,
_provenance_with_charspan,
_thread_table_merge_offset,
_wrap,
_wrap_field_kv_markup_if_needed,
_wrap_in_field_item_if_needed,
_wrap_in_field_region_if_needed,
_wrap_token,
_xml_error_context,
)
from docling_core.transforms.serializer.base import (
BaseAnnotationSerializer,
BaseDocSerializer,
BaseFallbackSerializer,
BaseFormSerializer,
BaseInlineSerializer,
BaseKeyValueSerializer,
BaseListSerializer,
BaseMetaSerializer,
BasePictureSerializer,
BaseTableSerializer,
BaseTextSerializer,
SerializationResult,
)
from docling_core.transforms.serializer.common import (
CommonParams,
DocSerializer,
_PageBreakNode,
create_ser_result,
)
from docling_core.types.doc import (
BaseMeta,
BoundingBox,
CodeItem,
ContentLayer,
DescriptionMetaField,
DocItem,
DoclingDocument,
FloatingItem,
Formatting,
FormItem,
InlineGroup,
KeyValueItem,
ListGroup,
ListItem,
MetaFieldName,
MoleculeMetaField,
NodeItem,
PictureClassificationMetaField,
PictureClassificationPrediction,
PictureItem,
PictureMeta,
ProvenanceItem,
Script,
SectionHeaderItem,
Size,
SummaryMetaField,
TableCell,
TableData,
TableItem,
TabularChartMetaField,
TextItem,
)
from docling_core.types.doc.base import CoordOrigin, ImageRefMode
from docling_core.types.doc.document import (
FieldHeadingItem,
FieldItem,
FieldRegionItem,
FieldValueItem,
FormulaItem,
GroupItem,
RichTableCell,
TitleItem,
)
from docling_core.types.doc.labels import (
CodeLanguageLabel,
DocItemLabel,
GroupLabel,
PictureClassificationLabel,
)
from docling_core.types.doc.utils import get_text_direction
__all__ = [
"ContentType",
"DocLangDocSerializer",
"DocLangParams",
"DocLangVocabulary",
"EscapeMode",
"LabelMode",
"LayerMode",
"WrapMode",
]
def _create_page_break_markup(node: _PageBreakNode) -> str:
"""Return the internal page-break placeholder replaced in ``serialize_doc``."""
return f"#_#_DOCLING_DOC_PAGE_BREAK_{node.prev_page}_{node.next_page}_#_#"
def _suppress_document_page_break(
doc_serializer: BaseDocSerializer,
*,
prev_page: int,
next_page: int,
) -> None:
"""Skip a duplicate document-level page break already emitted by list/table threading."""
if isinstance(doc_serializer, DocLangDocSerializer):
doc_serializer._suppressed_page_breaks.add((prev_page, next_page))
def _allocate_thread_id(doc_serializer: BaseDocSerializer, node: NodeItem) -> str:
"""Allocate a document-scoped positive ``thread_id`` in reading order."""
if isinstance(doc_serializer, DocLangDocSerializer):
return doc_serializer.allocate_thread_id(node)
raise TypeError("DocLang threading requires DocLangDocSerializer")
def _primary_page_no(node: NodeItem) -> Optional[int]:
"""Return the primary page number for a document item, if known."""
if isinstance(node, DocItem) and node.prov:
return node.prov[0].page_no
return None
class EscapeMode(str, Enum):
"""XML escape mode for DocLang output."""
ALWAYS = "always" # wrap all text in CDATA
AUTO = "auto" # wrap text in CDATA only if it contains special characters
class WrapMode(str, Enum):
"""Explicit content-wrapper mode for DocLang output."""
ALWAYS = "always" # wrap all text in an explicit wrapper element
AUTO = "auto" # wrap text with leading/trailing whitespace or newlines
class LayerMode(str, Enum):
"""Content-layer element emission mode for DocLang output."""
ALWAYS = "always" # always include the layer element
AUTO = "auto" # include layer only when it differs from the default
class LabelMode(str, Enum):
"""Element-head label emission mode for DocLang output."""
ALWAYS = "always" # always emit label, using ``undefined`` when absent
AUTO = "auto" # emit label only when present and not ``undefined``
class ContentType(str, Enum):
"""Content type for DocLang output."""
REF_CAPTION = "ref_caption"
REF_FOOTNOTE = "ref_footnote"
TEXT_CODE = "text_code"
TEXT_FORMULA = "text_formula"
TEXT_OTHER = "text_other"
TABLE = "table"
CHART = "chart"
TABLE_CELL = "table_cell"
PICTURE = "picture"
CHEMISTRY = "chemistry"
_DEFAULT_CONTENT_TYPES: set[ContentType] = set(ContentType)
def _advanced_field(*, detail: str = "") -> Any:
"""Build a Pydantic ``Field`` for advanced ``DocLangParams`` members."""
description = "Advanced parameter, meant for internal use."
if detail:
description = f"{description} {detail}"
return Field(description=description)
class DocLangParams(CommonParams):
"""DocLang-specific serialization parameters independent of DocLang."""
# Override parent's layers to default to all ContentLayers
layers: set[ContentLayer] = set(ContentLayer)
# Advanced parameters (meant for internal use):
# Geometry & content controls (aligned with DocLang defaults)
xsize: Annotated[int, _advanced_field()] = DOCLANG_DFLT_RESOLUTION
ysize: Annotated[int, _advanced_field()] = DOCLANG_DFLT_RESOLUTION
add_location: Annotated[bool, _advanced_field()] = True
add_table_cell_location: Annotated[bool, _advanced_field()] = False
add_referenced_caption: Annotated[bool, _advanced_field()] = True
add_referenced_footnote: Annotated[bool, _advanced_field()] = True
add_page_break: Annotated[bool, _advanced_field()] = True
add_content: Annotated[bool, _advanced_field()] = True
content_types: Annotated[
set[ContentType],
_advanced_field(detail="Types of content to serialize (only relevant if add_content is True)."),
] = _DEFAULT_CONTENT_TYPES
layer_mode: Annotated[LayerMode, _advanced_field()] = LayerMode.AUTO
emit_picture_layer: Annotated[
bool,
_advanced_field(detail="Whether to emit `<layer .../>` in picture element heads."),
] = True
# DocLang formatting
pretty_indentation: Annotated[
Optional[str],
_advanced_field(detail='None means minimized serialization, "" means no indentation.'),
] = 2 * " "
preserve_empty_non_selfclosing: Annotated[bool, _advanced_field()] = True
suppress_empty_elements: Annotated[
bool,
_advanced_field(
detail=(
"When True, elements that produce no serialized body content are completely "
"omitted rather than emitting an empty open/close tag pair or a head-only "
"shell (e.g. layer/thread/location metadata without text). When "
"``content_types`` excludes an item's body type, head-only shells are "
"suppressed as well."
),
),
] = False
escape_mode: Annotated[
EscapeMode,
_advanced_field(detail="XML compliance: escape special characters in text content."),
] = EscapeMode.AUTO
content_wrapping_mode: Annotated[WrapMode, _advanced_field()] = WrapMode.AUTO
image_mode: Annotated[ImageRefMode, _advanced_field()] = ImageRefMode.PLACEHOLDER
include_namespace: Annotated[bool, _advanced_field()] = False
include_version: Annotated[bool, _advanced_field()] = True
use_virtual_text: Annotated[
bool,
_advanced_field(detail="When True, the <text> wrapper is omitted whenever allowed."),
] = True
label_mode: Annotated[LabelMode, _advanced_field()] = LabelMode.AUTO
interpret_code_unknown_as_other: Annotated[
bool,
_advanced_field(
detail="When False, CodeLanguageLabel.UNKNOWN maps to undefined; when True, to other.",
),
] = False
def _text_item_content_type_active(item: TextItem, params: DocLangParams) -> bool:
"""Return whether the item's primary text content type is enabled in ``params``."""
if isinstance(item, CodeItem):
return ContentType.TEXT_CODE in params.content_types
if isinstance(item, FormulaItem):
return ContentType.TEXT_FORMULA in params.content_types
return ContentType.TEXT_OTHER in params.content_types
def _create_layer_token(
*,
item: DocItem,
params: DocLangParams,
) -> str:
"""Create `<layer value="..."/>` in element head."""
if isinstance(item, PictureItem) and not params.emit_picture_layer:
return ""
if params.layer_mode == LayerMode.ALWAYS or (
params.layer_mode == LayerMode.AUTO and item.content_layer != ContentLayer.BODY
):
return DocLangVocabulary._create_selfclosing_token(
token=DocLangToken.LAYER,
attrs={DocLangAttributeKey.VALUE: item.content_layer.value},
)
return ""
def _create_label_token(*, value: str) -> str:
"""Emit `<label value="..."/>` for element head (e.g. code language)."""
safe = value.replace("&", "&").replace('"', """)
return DocLangVocabulary._create_selfclosing_token(
token=DocLangToken.LABEL,
attrs={DocLangAttributeKey.VALUE: safe},
)
def _create_src_token(*, uri: str) -> str:
"""Emit `<src uri="..."/>` in the picture-specific body sequence (v0.6)."""
safe = uri.replace("&", "&").replace('"', """)
return DocLangVocabulary._create_selfclosing_token(
token=DocLangToken.SRC,
attrs={DocLangAttributeKey.URI: safe},
)
def _create_href_token(*, uri: str) -> str:
"""Emit `<href uri="..."/>` in element head."""
safe = uri.replace("&", "&").replace('"', """)
return DocLangVocabulary._create_selfclosing_token(
token=DocLangToken.HREF,
attrs={DocLangAttributeKey.URI: safe},
)
def _text_item_hyperlink_uri(item: DocItem) -> Optional[str]:
if isinstance(item, TextItem) and item.hyperlink is not None:
return str(item.hyperlink)
return None
def _element_head_prefix(
*,
item: DocItem,
doc: DoclingDocument,
params: DocLangParams,
label_value: Optional[str] = None,
caption_text: Optional[str] = None,
custom_text: Optional[str] = None,
include_href: bool = True,
thread_id: Optional[str] = None,
) -> str:
"""Emit element-head property elements in XSD order (label → thread → href → layer → location → caption → custom)."""
parts: list[str] = []
if label_value:
parts.append(_create_label_token(value=label_value))
if thread_id:
parts.append(DocLangVocabulary._create_threading_token(thread_id=thread_id))
if include_href and (href_uri := _text_item_hyperlink_uri(item)):
parts.append(_create_href_token(uri=href_uri))
if layer_token := _create_layer_token(item=item, params=params):
parts.append(layer_token)
if params.add_location:
if loc := _create_location_tokens_for_item(item=item, doc=doc, xres=params.xsize, yres=params.ysize):
parts.append(loc)
if caption_text:
parts.append(caption_text)
if custom_text:
parts.append(custom_text)
return "".join(parts)
def _serialize_floating_caption_head(
*,
item: FloatingItem,
doc_serializer: BaseDocSerializer,
doc: DoclingDocument,
params: DocLangParams,
**kwargs: Any,
) -> str:
"""Serialize referenced caption(s) for inclusion in the host element head."""
if not params.add_referenced_caption or not item.captions:
return ""
cap_res = doc_serializer.serialize_captions(item=item, **kwargs)
return cap_res.text or ""
def _element_label_for_serialization(
*,
raw_label: Optional[str],
params: DocLangParams,
) -> Optional[str]:
"""Resolve element-head ``<label>`` emission per ``params.label_mode``."""
if params.label_mode == LabelMode.ALWAYS:
return raw_label if raw_label is not None else _DOCLANG_LABEL_UNDEFINED
# AUTO: emit only when a label is present and not ``undefined``.
if raw_label is None or raw_label == _DOCLANG_LABEL_UNDEFINED:
return None
return raw_label
def _picture_classification_label_value(item: PictureItem) -> Optional[str]:
"""Picture type label for element head (raw ``class_name`` from the main prediction)."""
if item.meta and item.meta.classification:
class_name = item.meta.classification.get_main_prediction().class_name
return _picture_classification_label_to_doclang(class_name)
return None
def _serialize_item_custom_head(
*,
item: NodeItem,
doc_serializer: BaseDocSerializer,
params: DocLangParams,
**kwargs: Any,
) -> str:
"""Serialize item meta as ``<custom>`` for element head (v0.5)."""
if not isinstance(item, DocItem) or not item.meta:
return ""
meta_res = doc_serializer.serialize_meta(item=item, **kwargs)
return meta_res.text or ""
def _get_delim(*, params: DocLangParams) -> str:
"""Return record delimiter based on ``pretty_indentation``."""
return "" if params.pretty_indentation is None else "\n"
def _escape_text(text: str, params: DocLangParams) -> str:
do_wrap = params.content_wrapping_mode == WrapMode.ALWAYS or (
params.content_wrapping_mode == WrapMode.AUTO and (text != text.strip() or "\n" in text)
)
if params.escape_mode == EscapeMode.ALWAYS or (
params.escape_mode == EscapeMode.AUTO and any(c in text for c in ['"', "'", "&", "<", ">"])
):
text = f"<![CDATA[{text}]]>"
if do_wrap:
# text = f'<{el_str} xml:space="preserve">{text}</{el_str}>'
text = _wrap(text=text, wrap_tag=DocLangToken.CONTENT.value)
return text
def _list_item_segment_sibling(child: NodeItem) -> bool:
"""True when ``child`` is serialized as a sibling in the same ``<ldiv>`` segment."""
return isinstance(child, ListGroup | PictureItem)
def _list_item_has_segment_siblings(*, item: ListItem, doc: DoclingDocument) -> bool:
"""True when markup besides the list item text is emitted in the same ldiv segment."""
for child_ref in item.children:
if _list_item_segment_sibling(child_ref.resolve(doc)):
return True
parent = item.parent.resolve(doc) if item.parent else None
if isinstance(parent, ListGroup):
seen_self = False
for child_ref in parent.children:
child = child_ref.resolve(doc)
if child is item:
seen_self = True
continue
if seen_self and isinstance(child, ListGroup):
return True
return False
class DocLangListSerializer(BaseModel, BaseListSerializer):
"""DocLang-specific list serializer."""
indent: int = 4
@override
def serialize(
self,
*,
item: ListGroup,
doc_serializer: "BaseDocSerializer",
doc: DoclingDocument,
list_level: int = 0,
is_inline_scope: bool = False,
visited: Optional[set[str]] = None, # refs of visited items
**kwargs: Any,
) -> SerializationResult:
"""Serialize a ``ListGroup`` into DocLang markup.
This emits list containers (``<ordered_list>``/``<unordered_list>``) and
serializes children explicitly. Nested ``ListGroup`` items are emitted as
siblings, and individual list items are not wrapped here. The text
serializer is responsible for wrapping list item content (as
``<ldiv>``), so this serializer remains agnostic of item types.
Args:
item: The list group to serialize.
doc_serializer: The document-level serializer to delegate nested items.
doc: The document that provides item resolution.
list_level: Current nesting depth (0-based).
is_inline_scope: Whether serialization happens in an inline context.
visited: Set of already visited item refs to avoid cycles.
**kwargs: Additional serializer parameters forwarded to ``DocLangParams``.
Returns:
A ``SerializationResult`` containing serialized text and metadata.
"""
my_visited = visited if visited is not None else set()
params = DocLangParams(**kwargs)
# Build list children explicitly. Requirements:
# 1) <list ordered="true|false"></list> can be children of lists.
# 2) Do NOT wrap nested lists into <ldiv>, even if they are
# children of a ListItem in the logical structure.
# 3) Still ensure structural wrappers are preserved even when
# content is suppressed (e.g., add_content=False).
item_results: list[SerializationResult] = []
child_segments: list[tuple[str, Optional[int]]] = []
excluded = doc_serializer.get_excluded_refs(**kwargs)
for child_ref in item.children:
child = child_ref.resolve(doc)
# If a nested list group is present directly under this list group,
# emit it as a sibling (no <list_item> wrapper).
if isinstance(child, ListGroup):
if child.self_ref in my_visited or child.self_ref in excluded:
continue
my_visited.add(child.self_ref)
sub_res = doc_serializer.serialize(
item=child,
list_level=list_level + 1,
is_inline_scope=is_inline_scope,
visited=my_visited,
**kwargs,
)
if sub_res.text:
child_segments.append((sub_res.text, None))
item_results.append(sub_res)
continue
# Normal case: ListItem under ListGroup
if not isinstance(child, ListItem):
continue
if child.self_ref in my_visited or child.self_ref in excluded:
continue
my_visited.add(child.self_ref)
# Serialize the list item content; wrapping is handled by the text
# serializer (as <ldiv>), not here.
child_res = doc_serializer.serialize(
item=child,
list_level=list_level + 1,
is_inline_scope=is_inline_scope,
visited=my_visited,
**kwargs,
)
item_results.append(child_res)
if child_res.text:
child_segments.append((child_res.text, _primary_page_no(child)))
# After the <ldiv>, append nested lists and pictures (children of this
# ListItem) as siblings at the same level (not wrapped in <ldiv>).
for subref in child.children:
sub = subref.resolve(doc)
if not _list_item_segment_sibling(sub):
continue
if sub.self_ref in my_visited or sub.self_ref in excluded:
continue
my_visited.add(sub.self_ref)
sub_res = doc_serializer.serialize(
item=sub,
list_level=list_level + 1,
is_inline_scope=is_inline_scope,
visited=my_visited,
**kwargs,
)
if sub_res.text:
child_segments.append((sub_res.text, _primary_page_no(sub) if isinstance(sub, DocItem) else None))
item_results.append(sub_res)
delim = _get_delim(params=params)
if not child_segments:
return create_ser_result(text="", span_source=item_results)
ordered = item.first_item_is_enumerated(doc)
list_close = f"</{DocLangToken.LIST.value}>"
spans_pages = any(
child_segments[i][1] is not None
and child_segments[i + 1][1] is not None
and child_segments[i][1] != child_segments[i + 1][1]
for i in range(len(child_segments) - 1)
)
if not spans_pages:
child_texts = [text for text, _ in child_segments if text]
text_res = delim.join(child_texts)
text_res = f"{text_res}{delim}"
open_token = (
DocLangVocabulary._create_list_token(ordered=True)
if ordered
else DocLangVocabulary._create_list_token(ordered=False)
)
text_res = _wrap_token(text=text_res, open_token=open_token)
return create_ser_result(text=text_res, span_source=item_results)
thread_id = _allocate_thread_id(doc_serializer, item)
out_parts: list[str] = []
current_block: list[str] = []
current_page: Optional[int] = None
for text, page_no in child_segments:
if current_block and page_no is not None and current_page is not None and page_no != current_page:
list_open = DocLangVocabulary._create_list_token(
ordered=ordered
) + DocLangVocabulary._create_threading_token(thread_id=thread_id)
block_text = delim.join(current_block)
out_parts.append(f"{list_open}{block_text}{delim}{list_close}")
pb = _PageBreakNode(
self_ref=f"#/pb/{len(out_parts)}",
prev_page=current_page,
next_page=page_no,
)
_suppress_document_page_break(
doc_serializer,
prev_page=current_page,
next_page=page_no,
)
out_parts.append(_create_page_break_markup(pb))
current_block = []
if text:
current_block.append(text)
if page_no is not None:
current_page = page_no
if current_block:
list_open = DocLangVocabulary._create_list_token(
ordered=ordered
) + DocLangVocabulary._create_threading_token(thread_id=thread_id)
block_text = delim.join(current_block)
out_parts.append(f"{list_open}{block_text}{delim}{list_close}")
return create_ser_result(text="".join(out_parts), span_source=item_results)
class DocLangTextSerializer(BaseModel, BaseTextSerializer):
"""DocLang-specific text item serializer using `<location>` tokens."""
@override
def serialize(
self,
*,
item: "TextItem",
doc_serializer: BaseDocSerializer,
doc: DoclingDocument,
is_inline_scope: bool = False,
visited: Optional[set[str]] = None,
**kwargs: Any,
) -> SerializationResult:
"""Serialize a text item to DocLang format.
Handles multi-provenance items by splitting them into per-provenance items,
serializing each separately, and merging the results.
Args:
item: The text item to serialize.
doc_serializer: The document serializer instance.
doc: The DoclingDocument being serialized.
visited: Set of already visited item references.
**kwargs: Additional keyword arguments.
Returns:
SerializationResult containing the serialized text and span mappings.
"""
if len(item.prov) > 1 and not isinstance(item, ListItem):
# Split multi-provenance items into per-provenance fragments linked by
# a shared thread_id; insert page breaks when page_no changes.
# List items are not split here; cross-page lists are handled at list-group level.
thread_id = _allocate_thread_id(doc_serializer, item)
res: list[SerializationResult] = []
for idp, prov_ in enumerate(item.prov):
item_ = copy.deepcopy(item)
item_.prov = [prov_]
item_.text = item.orig[prov_.charspan[0] : prov_.charspan[1]] # it must be `orig`, not `text` here!
item_.orig = item.orig[prov_.charspan[0] : prov_.charspan[1]]
item_.prov[0].charspan = (0, len(item_.orig))
# marker field should be cleared on subsequent split parts
if idp > 0 and isinstance(item_, ListItem):
item_.marker = ""
tres: SerializationResult = self._serialize_single_item(
item=item_,
doc_serializer=doc_serializer,
doc=doc,
visited=visited,
is_inline_scope=is_inline_scope,
thread_id=thread_id,
**kwargs,
)
res.append(tres)
out_parts: list[str] = []
for idp, tres in enumerate(res):
if idp > 0 and item.prov[idp - 1].page_no != item.prov[idp].page_no:
pb = _PageBreakNode(
self_ref=f"#/pb/{idp}",
prev_page=item.prov[idp - 1].page_no,
next_page=item.prov[idp].page_no,
)
_suppress_document_page_break(
doc_serializer,
prev_page=item.prov[idp - 1].page_no,
next_page=item.prov[idp].page_no,
)
out_parts.append(_create_page_break_markup(pb))
out_parts.append(tres.text)
return create_ser_result(text="".join(out_parts), span_source=res)
else:
return self._serialize_single_item(
item=item,
doc_serializer=doc_serializer,
doc=doc,
visited=visited,
is_inline_scope=is_inline_scope,
**kwargs,
)
def _should_skip_location_for_list_item(self, *, item: ListItem, doc: DoclingDocument) -> bool:
"""Check if location tokens should be skipped for a ListItem.
Returns True if the ListItem has empty text, provenance, and its first
child is an InlineGroup (which will handle location tokens itself).
"""
if not item.text and item.prov and item.children:
first_child_ref = item.children[0]
first_child_item = first_child_ref.resolve(doc)
return isinstance(first_child_item, InlineGroup)
return False
def _list_item_has_segment_siblings(self, *, item: ListItem, doc: DoclingDocument) -> bool:
"""True when markup besides the list item text is emitted in the same ldiv segment."""
return _list_item_has_segment_siblings(item=item, doc=doc)
def _determine_list_item_wrapper(
self, *, item: ListItem, doc: DoclingDocument, use_virtual_text: bool = True
) -> tuple[Optional[str], Optional[DocLangToken]]:
"""Determine the wrapper token for a ListItem.
Args:
item: The ListItem to determine wrapper for.
doc: The document containing the item.
use_virtual_text: If True, omit ``<text>`` when the ldiv segment contains
only that text (DocLang v0.4 virtual text mode).
Returns:
Tuple of (wrap_open_token, tok) where wrap_open_token is the opening tag
string or None, and tok is the DocLangToken or None.
"""
if item.text:
if use_virtual_text and not self._list_item_has_segment_siblings(item=item, doc=doc):
return None, None
tok = DocLangToken.TEXT
return f"<{tok.value}>", tok
elif not item.text and item.prov and item.children:
# Check if first child is InlineGroup (rich text case)
first_child_ref = item.children[0]
first_child_item = first_child_ref.resolve(doc)
if isinstance(first_child_item, InlineGroup):
# First child is InlineGroup: don't wrap, let InlineGroup handle it
# InlineSerializer will use parent ListItem's provenance for location tokens
return None, None
else:
# Other children with bbox: wrap in <group>
tok = DocLangToken.GROUP
return f"<{tok.value}>", tok
else:
return None, None
def _serialize_single_item( # noqa: C901
self,
*,
item: "TextItem",
doc_serializer: BaseDocSerializer,
doc: DoclingDocument,
is_inline_scope: bool = False,
visited: Optional[set[str]] = None,
thread_id: Optional[str] = None,
**kwargs: Any,
) -> SerializationResult:
"""Serialize a ``TextItem`` into DocLang markup.
Depending on parameters, emits meta blocks, location tokens, and the
item's textual content (prefixing code language for ``CodeItem``). For
floating items, captions may be appended. The result can be wrapped in a
tag derived from the item's label when applicable.
Args:
item: The text-like item to serialize.
doc_serializer: The document-level serializer for delegating nested items.
doc: The document used to resolve references and children.
visited: Set of already visited item refs to avoid cycles.
**kwargs: Additional serializer parameters forwarded to ``DocLangParams``.
Returns:
A ``SerializationResult`` with the serialized text and span source.
"""
my_visited = visited if visited is not None else set()
params = DocLangParams(**kwargs)
# Determine wrapper open-token for this item using DocLang vocabulary.
# - TitleItem: use <heading level="1"> ... </heading>.
# - SectionHeaderItem: use <heading level="N+1"> ... </heading> where N is SectionHeaderItem.level.
# - Other text-like items: map the label to an DocLangToken; for
# list items, this maps to <ldiv> and keeps the text serializer
# free of type-based special casing.
wrap_open_token: Optional[str]
tok: DocLangToken | None = None
if isinstance(item, TitleItem):
wrap_open_token = DocLangVocabulary._create_heading_token(level=1)
elif isinstance(item, SectionHeaderItem):
wrap_open_token = DocLangVocabulary._create_heading_token(level=item.level + 1)
elif isinstance(item, ListItem):
wrap_open_token, tok = self._determine_list_item_wrapper(
item=item, doc=doc, use_virtual_text=params.use_virtual_text
)
elif isinstance(item, CodeItem):
tok = DocLangToken.CODE
wrap_open_token = f"<{tok.value}>"
elif isinstance(item, TextItem) and item.label in [
DocItemLabel.CHECKBOX_SELECTED,
DocItemLabel.CHECKBOX_UNSELECTED,
]:
if item.parent and isinstance((parent_item := item.parent.resolve(doc)), TextItem) and not parent_item.text:
# skip re-wrapping if already in a text item
wrap_open_token = None
else:
tok = DocLangToken.TEXT
wrap_open_token = f"<{tok.value}>"
elif isinstance(item, TextItem) and item.label == DocItemLabel.CAPTION:
# v0.5: <caption> is only valid in a host element head, not top-level.
tok = DocLangToken.TEXT
wrap_open_token = f"<{tok.value}>"
elif isinstance(item, TextItem) and (
tok := {
DocItemLabel.FIELD_KEY: DocLangToken.FIELD_KEY,
DocItemLabel.FIELD_VALUE: DocLangToken.FIELD_VALUE,
DocItemLabel.FIELD_HEADING: DocLangToken.FIELD_HEADING,
DocItemLabel.FIELD_HINT: DocLangToken.FIELD_HINT,
DocItemLabel.MARKER: DocLangToken.MARKER,
}.get(item.label)
):
wrap_open_token = f"<{tok.value}>"
if isinstance(item, FieldValueItem) and item.kind != "read_only":
wrap_open_token = f'<{tok.value} class="{item.kind}">'
elif isinstance(item, FieldHeadingItem):
wrap_open_token = DocLangVocabulary._create_field_heading_token(level=item.level)
elif isinstance(item, TextItem) and (
item.label
in [ # FIXME: Catch all ...
DocItemLabel.EMPTY_VALUE, # FIXME: this might need to become a FormItem with only a value key!
DocItemLabel.HANDWRITTEN_TEXT,
DocItemLabel.PARAGRAPH,
DocItemLabel.REFERENCE,
DocItemLabel.GRADING_SCALE,
]
):
tok = DocLangToken.TEXT
wrap_open_token = f"<{tok.value}>"
else:
label_value = str(item.label)
try:
tok = DocLangToken(label_value)
wrap_open_token = f"<{tok.value}>"
except ValueError:
raise ValueError(f"Unsupported DocLang token for label '{label_value}'")
parts: list[str] = []
# For ListItems, emit <ldiv> as a separate delimiter element before content
ldiv_element = ""
if isinstance(item, ListItem):
if item.marker:
marker_text = _escape_text(item.marker, params)
marker_element = _wrap(text=marker_text, wrap_tag=DocLangToken.MARKER.value)
ldiv_element = _wrap(text=marker_element, wrap_tag=DocLangToken.LDIV.value)
else:
# Empty ldiv (self-closing)
ldiv_element = DocLangVocabulary._create_selfclosing_token(token=DocLangToken.LDIV)
custom_head = _serialize_item_custom_head(item=item, doc_serializer=doc_serializer, params=params, **kwargs)
# Skip adding location tokens if this is a ListItem with InlineGroup child
# (InlineSerializer will handle location tokens using parent's provenance)
skip_location = isinstance(item, ListItem) and self._should_skip_location_for_list_item(item=item, doc=doc)
code_label: Optional[str] = None
if isinstance(item, CodeItem):
code_label = _element_label_for_serialization(
raw_label=_code_language_label_to_doclang(
item.code_language,
interpret_unknown_as_other=params.interpret_code_unknown_as_other,
),
params=params,
)
include_href = not is_inline_scope
if not skip_location:
parts.append(
_element_head_prefix(
item=item,
doc=doc,
params=params,
label_value=code_label,
custom_text=custom_head or None,
include_href=include_href,
thread_id=thread_id,
)
)
else:
if code_label:
parts.append(_create_label_token(value=code_label))
if thread_id:
parts.append(DocLangVocabulary._create_threading_token(thread_id=thread_id))
if include_href and (href_uri := _text_item_hyperlink_uri(item)):
parts.append(_create_href_token(uri=href_uri))
if layer_token := _create_layer_token(item=item, params=params):
parts.append(layer_token)
if custom_head:
parts.append(custom_head)
text_part = ""
if (
(isinstance(item, CodeItem) and ContentType.TEXT_CODE in params.content_types)
or (isinstance(item, FormulaItem) and ContentType.TEXT_FORMULA in params.content_types)
or (not isinstance(item, CodeItem | FormulaItem) and ContentType.TEXT_OTHER in params.content_types)
):
if item.children and not item.text:
# Check if first child is InlineGroup - if so, only serialize that as text content
first_child_ref = item.children[0]
first_child_item = first_child_ref.resolve(doc)
if isinstance(first_child_item, InlineGroup):
# Only serialize the first child (InlineGroup) as the text content
# Other children are hierarchical subordinates and will be serialized separately
text_part = doc_serializer.serialize(item=first_child_item, visited=my_visited, **kwargs).text
else:
# Serialize all children as text content
sub_parts: list[str] = []
for child_ref in item.children:
child_item = child_ref.resolve(doc)
if isinstance(item, ListItem) and _list_item_segment_sibling(child_item):
continue
sub_parts.append(doc_serializer.serialize(item=child_item, visited=my_visited, **kwargs).text)
text_part = _get_delim(params=params).join(sub_parts)
else:
text_part = _escape_text(item.text, params)
text_part = doc_serializer.post_process(
text=text_part,
formatting=item.formatting,
hyperlink=None,
)
if item.label == DocItemLabel.HANDWRITTEN_TEXT:
text_part = _wrap(text=text_part, wrap_tag=DocLangToken.HANDWRITING.value)
elif item.label in [
DocItemLabel.CHECKBOX_SELECTED,
DocItemLabel.CHECKBOX_UNSELECTED,
]:
# Add checkbox token before the text
checkbox_token = DocLangVocabulary._create_checkbox_token(
selected=(item.label == DocItemLabel.CHECKBOX_SELECTED)
)
text_part = checkbox_token + text_part
cap_text = ""
if params.add_referenced_caption and isinstance(item, FloatingItem):
cap_text = doc_serializer.serialize_captions(item=item, **kwargs).text
if cap_text:
cap_text = _escape_text(cap_text, params)
ftn_text = ""
if params.add_referenced_footnote and isinstance(item, FloatingItem):
ftn_text = doc_serializer.serialize_footnotes(item=item, **kwargs).text
if ftn_text:
ftn_text = _escape_text(ftn_text, params)
if (
params.suppress_empty_elements
and not _text_item_content_type_active(item, params)
and not text_part
and not cap_text
and not ftn_text
and not (params.add_location and item.prov)
):
return create_ser_result(text="", span_source=item)
if text_part:
parts.append(text_part)
if cap_text:
parts.append(cap_text)