python-doctr 1.0.1__py3-none-any.whl → 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/io/exporters.py ADDED
@@ -0,0 +1,1915 @@
1
+ # Copyright (C) 2021-2026, Mindee.
2
+
3
+ # This program is licensed under the Apache License 2.0.
4
+ # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
+
6
+ import re
7
+ from html import escape as _html_escape
8
+ from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, cast
9
+ from xml.etree import ElementTree as ET
10
+ from xml.etree.ElementTree import Element as ETElement
11
+ from xml.etree.ElementTree import SubElement
12
+
13
+ import numpy as np
14
+
15
+ import doctr
16
+ from doctr.io.figures import FigureEncoder, is_picture_label, picture_regions
17
+ from doctr.utils.common_types import BoundingBox
18
+
19
+ if TYPE_CHECKING: # pragma: no cover
20
+ from doctr.io.elements import Block, Formula, KIEPage, LayoutElement, Line, Page, Table
21
+
22
+ __all__ = [
23
+ "AsciiDocExporter",
24
+ "DocumentExportsMixin",
25
+ "HTMLExporter",
26
+ "KIEPageExportsMixin",
27
+ "MarkdownExporter",
28
+ "PageExportsMixin",
29
+ "TextExporter",
30
+ "XMLExporter",
31
+ "page_reading_order",
32
+ ]
33
+
34
+
35
+ def _export_as(exporters: dict[str, Any], format: str, **kwargs: Any) -> Any:
36
+ fmt = format.strip().lower()
37
+ if fmt not in exporters:
38
+ raise ValueError(f"unsupported export format '{format}', should be one of {sorted(exporters)}")
39
+ return exporters[fmt](**kwargs)
40
+
41
+
42
+ def to_json_safe(value: Any) -> Any:
43
+ """Recursively convert NumPy containers and scalars into built-in Python types.
44
+
45
+ Args:
46
+ value: any exported value
47
+
48
+ Returns:
49
+ the same value with every NumPy array converted to nested tuples and every NumPy scalar to its
50
+ Python equivalent
51
+ """
52
+ if isinstance(value, np.ndarray):
53
+ return value.item() if value.ndim == 0 else tuple(to_json_safe(item) for item in value)
54
+ if isinstance(value, np.generic): # np.float32, np.int64, np.bool_, ...
55
+ return value.item()
56
+ if isinstance(value, dict):
57
+ return {str(key): to_json_safe(item) for key, item in value.items()}
58
+ if isinstance(value, tuple):
59
+ return tuple(to_json_safe(item) for item in value)
60
+ if isinstance(value, (list, set, frozenset)):
61
+ return [to_json_safe(item) for item in value]
62
+ return value
63
+
64
+
65
+ _LIST_LABELS = {"list_item"}
66
+ # Characters / line markers that carry a structural meaning and are escaped to preserve the raw OCR text
67
+ _MD_SPECIAL_CHARS = "\\`*_[]|#<>"
68
+ _MD_LINE_MARKERS = "-+>#=`"
69
+ # Ordered list marker at the start of a line, e.g. "3." or "3)"
70
+ _MD_ORDERED_MARKER = re.compile(r"^(\s*\d{1,9})([.)])(?=\s|$)")
71
+ _ADOC_SPECIAL_CHARS = "\\`*_#^~|+{}<>"
72
+ _ADOC_LINE_MARKERS = "=*.-/+"
73
+
74
+
75
+ def _covering_region_indices(
76
+ geoms: list[Any],
77
+ region_geoms: list[Any],
78
+ min_coverage: float = 0.5,
79
+ region_labels: list[str] | None = None,
80
+ ) -> list[int]:
81
+ """Return the index of the layout region each geometry is assigned to (-1 for none)
82
+
83
+ Same criterion as :func:`doctr.models.reading_order.assign_layout_labels`, on geometries in the same frame.
84
+ """
85
+ from doctr.models.reading_order.base import _covering_regions, _to_boxes
86
+
87
+ if len(region_geoms) == 0 or len(geoms) == 0:
88
+ return [-1] * len(geoms)
89
+ return _covering_regions(_to_boxes(geoms), _to_boxes(region_geoms), min_coverage, region_labels)
90
+
91
+
92
+ def _merge_overlapping_regions(elt_regions: list[int], region_geoms: list[Any], region_labels: list[str]) -> list[int]:
93
+ """Map the layout region of each element (-1 for none) to its group of overlapping regions of the same label"""
94
+ from doctr.models.reading_order.base import _region_groups, _to_boxes
95
+
96
+ if len(region_geoms) < 2:
97
+ return list(elt_regions)
98
+ groups = _region_groups(_to_boxes(region_geoms), region_labels)
99
+ return [groups[reg] if reg >= 0 else reg for reg in elt_regions]
100
+
101
+
102
+ def _is_atomic(element: Any) -> bool:
103
+ """Whether a reading-order element is an item of its own (a table, a formula or a figure), not a text line"""
104
+ from doctr.io.elements import Formula, LayoutElement, Table
105
+
106
+ return isinstance(element, (Table, Formula, LayoutElement))
107
+
108
+
109
+ def _xyxy(geometry: Any) -> tuple[float, float, float, float]:
110
+ """Return the enclosing box (xmin, ymin, xmax, ymax) of a box or a polygon"""
111
+ pts = np.asarray(geometry, dtype=np.float64).reshape(-1, 2)
112
+ return float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())
113
+
114
+
115
+ def _join_caption_lines(lines: list[str]) -> str:
116
+ """Join the lines of a caption, mending the words hyphenated at a line break ("dif-" + "ferent")"""
117
+ text = ""
118
+ for line in (line.strip() for line in lines):
119
+ if not line:
120
+ continue
121
+ if text.endswith("-") and line[0].islower():
122
+ fragment = text[:-1].rsplit(" ", 1)[-1]
123
+ text = text[:-1] + line if fragment.isalpha() and fragment.islower() else text + line
124
+ else:
125
+ text = f"{text} {line}" if text else line
126
+ return text
127
+
128
+
129
+ def _reading_order_signature(page: "Page", direction: str) -> tuple[Any, ...]:
130
+ """Return a cheap fingerprint of a page, used to invalidate the reading-order cache
131
+
132
+ It covers the direction and the identity of the blocks (with their line count), tables, formulas and layout
133
+ regions.
134
+ In-place edits of the words of a line are not detected: drop `_reading_order_cache` after such edits.
135
+ """
136
+ return (
137
+ direction,
138
+ tuple((id(block), len(block.lines)) for block in page.blocks),
139
+ tuple(id(table) for table in getattr(page, "tables", ()) or ()),
140
+ tuple(id(formula) for formula in getattr(page, "formulas", ()) or ()),
141
+ tuple(id(region) for region in getattr(page, "layout", ()) or ()),
142
+ )
143
+
144
+
145
+ def _store_reading_order(page: "Page", signature: tuple[Any, ...], result: tuple[Any, ...]) -> None:
146
+ """Memoize a reading-order result on the page, ignoring pages that reject attribute assignment."""
147
+ try:
148
+ page._reading_order_cache = (signature, result) # type: ignore[attr-defined]
149
+ except AttributeError: # pragma: no cover
150
+ pass
151
+
152
+
153
+ def page_reading_order(
154
+ page: "Page", direction: str = "auto", include_figures: bool = False
155
+ ) -> tuple[list[Any], list[str | None], str]:
156
+ """Linearize the content of a page (blocks, tables, formulas and optionally figures) in reading order
157
+
158
+ The result is cached on the page, so a page exported to several formats is ordered once. The figures always take
159
+ part in the ordering, `include_figures` only controls whether they are returned.
160
+
161
+ Args:
162
+ page: the page to linearize
163
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
164
+ include_figures: whether to return the figure regions too
165
+
166
+ Returns:
167
+ the ordered items, their layout label (None without layout) and the effective reading direction
168
+ """
169
+ from doctr.models.reading_order import ReadingOrderPredictor, deskew_reading_geometries, resolve_reading_segments
170
+
171
+ signature = _reading_order_signature(page, direction)
172
+ cached = getattr(page, "_reading_order_cache", None)
173
+ if cached is not None and cached[0] == signature:
174
+ cached_items, cached_labels, resolved = cached[1]
175
+ return _select_items(list(cached_items), list(cached_labels), resolved, include_figures)
176
+
177
+ lines = [line for block in page.blocks for line in block.lines]
178
+ words = [word for line in lines for word in line.words]
179
+ language = page.language.get("value") if isinstance(page.language, dict) else None
180
+ direction = ReadingOrderPredictor(direction=direction).resolve_direction(
181
+ [word.value for word in words], language=language
182
+ )
183
+ # Lines, tables and figures (as floats) and formulas (in the text flow) are ordered together
184
+ elements: list[Any] = [*lines, *page.tables, *getattr(page, "formulas", []), *picture_regions(page)]
185
+ items: list[Any] = []
186
+ labels: list[str | None] = []
187
+ if len(elements) > 0:
188
+ # De-skew once so labeling, ordering and region grouping share the same upright frame; the page angle is
189
+ # estimated from the word polygons, which carry the detection model's true orientation
190
+ elt_geoms, region_geoms = deskew_reading_geometries(
191
+ [elt.geometry for elt in elements],
192
+ [region.geometry for region in page.layout],
193
+ page_shape=page.dimensions,
194
+ angle_geoms=[word.geometry for word in words],
195
+ )
196
+ region_labels = [region.type for region in page.layout]
197
+ elt_regions = _covering_region_indices(elt_geoms, region_geoms, region_labels=region_labels)
198
+ elt_labels = _element_labels(page, elements, elt_geoms, elt_regions, region_geoms)
199
+ segments = resolve_reading_segments(
200
+ elt_geoms,
201
+ direction=direction,
202
+ labels=[_order_label(elt, label) for elt, label in zip(elements, elt_labels)],
203
+ page_shape=page.dimensions,
204
+ column_voters=_column_voters(elements, elt_geoms, elt_regions, region_geoms, region_labels),
205
+ region_groups=_merge_overlapping_regions(elt_regions, region_geoms, region_labels),
206
+ )
207
+ items, labels = _segments_to_items(page, elements, segments, elt_labels, elt_regions)
208
+ _store_reading_order(page, signature, (items, labels, direction))
209
+ return _select_items(list(items), list(labels), direction, include_figures)
210
+
211
+
212
+ def _element_labels(
213
+ page: "Page", elements: list[Any], elt_geoms: list[Any], elt_regions: list[int], region_geoms: list[Any]
214
+ ) -> list[str | None]:
215
+ """Return the layout label of each element: the label of its layout region (None for none), 'Table' for a table,
216
+ 'Formula' for a formula
217
+
218
+ A figure takes its own type, unless it lies in page furniture (e.g. a logo in the page header): it is then read with
219
+ the furniture, along with its text.
220
+ """
221
+ from doctr.io.elements import Formula, LayoutElement, Table
222
+ from doctr.models.reading_order import layout_label_role
223
+ from doctr.models.reading_order.base import _FURNITURE_ROLES
224
+
225
+ region_labels = [str(region.type) for region in page.layout]
226
+ labels: list[str | None] = [region_labels[reg] if reg >= 0 else None for reg in elt_regions]
227
+ furniture = [reg for reg, label in enumerate(region_labels) if layout_label_role(label) in _FURNITURE_ROLES]
228
+ figures = [idx for idx, elt in enumerate(elements) if isinstance(elt, LayoutElement)]
229
+ in_furniture = _covering_region_indices(
230
+ [elt_geoms[idx] for idx in figures], [region_geoms[reg] for reg in furniture]
231
+ )
232
+ region_index = {id(region): reg for reg, region in enumerate(page.layout)}
233
+ furniture_of_figure: dict[int, str] = {} # figure region index -> label of the furniture holding it
234
+ for idx, reg in zip(figures, in_furniture):
235
+ labels[idx] = region_labels[furniture[reg]] if reg >= 0 else elements[idx].type
236
+ if reg >= 0:
237
+ furniture_of_figure[region_index[id(elements[idx])]] = region_labels[furniture[reg]]
238
+ for idx, elt in enumerate(elements):
239
+ if isinstance(elt, Table):
240
+ labels[idx] = "Table"
241
+ elif isinstance(elt, Formula):
242
+ labels[idx] = "Formula"
243
+ elif not isinstance(elt, LayoutElement) and elt_regions[idx] in furniture_of_figure:
244
+ labels[idx] = furniture_of_figure[elt_regions[idx]]
245
+ return labels
246
+
247
+
248
+ def _order_label(element: Any, label: str | None) -> str | None:
249
+ """Return the label used to order an element: a text line in a table or figure region keeps the label of its
250
+ region, but is grouped into paragraphs like regular text"""
251
+ from doctr.io.elements import LayoutElement, Table
252
+ from doctr.models.reading_order import layout_label_role
253
+ from doctr.models.reading_order.base import _float_text_label
254
+
255
+ if not isinstance(element, (Table, LayoutElement)) and layout_label_role(label) == "float":
256
+ return _float_text_label(str(label))
257
+ return label
258
+
259
+
260
+ def _column_voters(
261
+ elements: list[Any], elt_geoms: list[Any], elt_regions: list[int], region_geoms: list[Any], region_labels: list[str]
262
+ ) -> list[bool]:
263
+ """Return the elements voting in the multi-column detection
264
+
265
+ Page-wide figures and tables do not vote, nor do the text lines of a page-wide table region: its cells (e.g. the
266
+ amounts of a receipt detected as a table) would read as columns.
267
+ """
268
+ from doctr.io.elements import LayoutElement, Table
269
+ from doctr.models.reading_order import normalize_layout_label
270
+ from doctr.models.reading_order.base import _to_boxes
271
+
272
+ boxes = _to_boxes(elt_geoms)
273
+ span = float(boxes[:, 2].max() - boxes[:, 0].min()) or 1.0
274
+ region_boxes = _to_boxes(region_geoms)
275
+ wide_tables = {
276
+ reg
277
+ for reg, (label, box) in enumerate(zip(region_labels, region_boxes))
278
+ if normalize_layout_label(label) == "table" and box[2] - box[0] > 0.5 * span
279
+ }
280
+ return [
281
+ not (box[2] - box[0] > 0.5 * span) if isinstance(elt, (LayoutElement, Table)) else reg not in wide_tables
282
+ for elt, box, reg in zip(elements, boxes, elt_regions)
283
+ ]
284
+
285
+
286
+ def _segments_to_items(
287
+ page: "Page", elements: list[Any], segments: list[list[int]], elt_labels: list[str | None], elt_regions: list[int]
288
+ ) -> tuple[list[Any], list[str | None]]:
289
+ """Turn reading-ordered segments of elements into page items: one block per paragraph, one block per list item
290
+ (a list item wrapped over several lines is one block), tables, formulas and figures as they are
291
+
292
+ The artefacts of a block follow its first line; those of blocks without lines go to the last block.
293
+ """
294
+ from doctr.io.elements import Formula, Table
295
+ from doctr.models.reading_order import normalize_layout_label
296
+
297
+ artefacts = _ArtefactClaims(page.blocks)
298
+ items: list[Any] = []
299
+ labels: list[str | None] = []
300
+ list_region: int | None = None # region of the list item being built
301
+ for run in (run for segment in segments for run in _float_runs(elements, segment)):
302
+ first, label = elements[run[0]], elt_labels[run[0]]
303
+ if _is_atomic(first):
304
+ items.append(first)
305
+ labels.append("Table" if isinstance(first, Table) else "Formula" if isinstance(first, Formula) else label)
306
+ list_region = None
307
+ elif normalize_layout_label(label) in _LIST_LABELS:
308
+ # One bullet per list-item region: consecutive lines of the same region are a single bullet
309
+ for idx in run:
310
+ region = elt_regions[idx]
311
+ if region != -1 and region == list_region:
312
+ items[-1] = artefacts.block([*items[-1].lines, elements[idx]], items[-1].artefacts)
313
+ else:
314
+ items.append(artefacts.block([elements[idx]]))
315
+ labels.append(label)
316
+ list_region = region
317
+ else:
318
+ items.append(artefacts.block([elements[idx] for idx in run]))
319
+ labels.append(label)
320
+ list_region = None
321
+ artefacts.attach_leftovers(items)
322
+ return items, labels
323
+
324
+
325
+ class _ArtefactClaims:
326
+ """Hand the artefacts of the page blocks over to the blocks built in reading order
327
+
328
+ Args:
329
+ blocks: the blocks of the page
330
+ """
331
+
332
+ def __init__(self, blocks: list[Any]) -> None:
333
+ self.owner = {id(line): idx for idx, block in enumerate(blocks) for line in block.lines}
334
+ self.pending = {idx: list(block.artefacts) for idx, block in enumerate(blocks) if block.artefacts}
335
+
336
+ def block(self, lines: list[Any], artefacts: list[Any] | None = None) -> Any:
337
+ """Build a block, which claims the artefacts of the blocks its lines come from (unless already claimed)"""
338
+ from doctr.io.elements import Block
339
+
340
+ claimed = list(artefacts or [])
341
+ for line in lines:
342
+ owner = self.owner.get(id(line))
343
+ if owner is not None and owner in self.pending:
344
+ claimed.extend(self.pending.pop(owner))
345
+ return Block(lines=lines, artefacts=claimed)
346
+
347
+ def attach_leftovers(self, items: list[Any]) -> None:
348
+ """Attach the artefacts of blocks without any line to the last block, so they stay on the page"""
349
+ from doctr.io.elements import Block
350
+
351
+ leftover = [artefact for artefacts in self.pending.values() for artefact in artefacts]
352
+ last_block = next((item for item in reversed(items) if isinstance(item, Block)), None)
353
+ if leftover and last_block is not None:
354
+ last_block.artefacts = [*last_block.artefacts, *leftover]
355
+
356
+
357
+ def _float_runs(elements: list[Any], segment: list[int]) -> list[list[int]]:
358
+ """Split the tables, formulas and figures out of a segment (a figure in page furniture can share one)"""
359
+ runs: list[list[int]] = []
360
+ for idx in segment:
361
+ is_atomic = _is_atomic(elements[idx])
362
+ if runs and not is_atomic and not _is_atomic(elements[runs[-1][-1]]):
363
+ runs[-1].append(idx)
364
+ else:
365
+ runs.append([idx])
366
+ return runs
367
+
368
+
369
+ def _select_items(
370
+ items: list[Any], labels: list[str | None], direction: str, include_figures: bool
371
+ ) -> tuple[list[Any], list[str | None], str]:
372
+ """Drop the figures from a linearization, unless requested"""
373
+ from doctr.io.elements import LayoutElement
374
+
375
+ if include_figures:
376
+ return items, labels, direction
377
+ kept = [(item, label) for item, label in zip(items, labels) if not isinstance(item, LayoutElement)]
378
+ return [item for item, _ in kept], [label for _, label in kept], direction
379
+
380
+
381
+ def _line_render_direction(line: "Line", page_direction: str, auto: bool) -> str:
382
+ """Resolve the direction used to order the words of a line.
383
+
384
+ For vertical pages the words are always read top to bottom. For horizontal pages, when the page direction
385
+ was inferred automatically, the base direction of each line is detected from its own text so that an
386
+ embedded left-to-right run (e.g. a Latin quotation on an Arabic page) keeps its natural word order; when
387
+ the direction is set explicitly, it is applied uniformly to every line.
388
+ """
389
+ if page_direction in ("ttb-rtl", "ttb-ltr") or not auto or len(line.words) <= 1:
390
+ return page_direction
391
+ from doctr.models.reading_order import detect_text_direction
392
+
393
+ return detect_text_direction([word.render() for word in line.words])
394
+
395
+
396
+ def ordered_line_words(line: "Line", direction: str = "ltr", auto: bool = False) -> list[Any]:
397
+ """Return the words of a line in reading order.
398
+
399
+ Args:
400
+ line: the line whose words should be ordered
401
+ direction: the reading direction resolved for the page
402
+ auto: whether the page direction was inferred (each line then gets its own base direction)
403
+
404
+ Returns:
405
+ the words of the line, ordered logically
406
+ """
407
+ direction = _line_render_direction(line, direction, auto)
408
+ if direction in ("ttb-rtl", "ttb-ltr"):
409
+ return sorted(line.words, key=lambda word: float(np.asarray(word.geometry, dtype=np.float64)[..., 1].mean()))
410
+ if direction == "rtl":
411
+ return sorted(line.words, key=lambda word: -float(np.asarray(word.geometry, dtype=np.float64)[..., 0].mean()))
412
+ return list(line.words)
413
+
414
+
415
+ def predictions_in_reading_order(page: "KIEPage", predictions: list[Any], direction: str = "auto") -> list[Any]:
416
+ """Sort the predictions of a single KIE detection class in reading order.
417
+
418
+ Args:
419
+ page: the KIE page the predictions belong to (used for its dimensions and detected language)
420
+ predictions: the predictions of one detection class
421
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
422
+
423
+ Returns:
424
+ the predictions, ordered logically
425
+ """
426
+ from doctr.models.reading_order import ReadingOrderPredictor
427
+
428
+ if len(predictions) < 2:
429
+ return list(predictions)
430
+ language = page.language.get("value") if isinstance(page.language, dict) else None
431
+ order = ReadingOrderPredictor(direction=direction)(
432
+ [prediction.geometry for prediction in predictions],
433
+ texts=[prediction.value for prediction in predictions],
434
+ language=language,
435
+ page_shape=page.dimensions,
436
+ )
437
+ return [predictions[idx] for idx in order]
438
+
439
+
440
+ class _FigurePlan(NamedTuple):
441
+ """Figures of a page to export, by item index"""
442
+
443
+ markup: dict[int, str] # figure markup
444
+ captions: set[int] # captions rendered with their figure
445
+ hidden: set[int] # text left out of the export
446
+
447
+
448
+ class _PageFigures:
449
+ """The figures of a linearized page, in the upright frame of the reading order
450
+
451
+ Args:
452
+ page: the page
453
+ items: the linearized page content, figures included
454
+ labels: the layout label of each item
455
+ """
456
+
457
+ def __init__(self, page: "Page", items: list[Any], labels: list[str | None]) -> None:
458
+ from doctr.io.elements import Block
459
+ from doctr.models.reading_order import deskew_reading_geometries
460
+
461
+ self.items, self.labels = items, labels
462
+ # Same upright frame as the reading order, for the items and the lines of the blocks
463
+ block_lines = [(idx, line) for idx, item in enumerate(items) if isinstance(item, Block) for line in item.lines]
464
+ upright, upright_regions = deskew_reading_geometries(
465
+ [item.geometry for item in items] + [line.geometry for _, line in block_lines],
466
+ [region.geometry for region in page.layout],
467
+ page_shape=page.dimensions,
468
+ angle_geoms=[word.geometry for block in page.blocks for line in block.lines for word in line.words],
469
+ )
470
+ self.boxes = [_xyxy(geom) for geom in upright[: len(items)]]
471
+ self.line_boxes: dict[int, list[tuple[float, ...]]] = {}
472
+ for (owner, _), geom in zip(block_lines, upright[len(items) :]):
473
+ self.line_boxes.setdefault(owner, []).append(_xyxy(geom))
474
+ self.region_of = _covering_region_indices(
475
+ upright[: len(items)], upright_regions, region_labels=[region.type for region in page.layout]
476
+ )
477
+
478
+ def in_furniture(self, fig: int) -> bool:
479
+ """Whether a figure is read with the page furniture"""
480
+ from doctr.models.reading_order import layout_label_role
481
+ from doctr.models.reading_order.base import _FURNITURE_ROLES
482
+
483
+ return layout_label_role(self.labels[fig]) in _FURNITURE_ROLES
484
+
485
+ def without_furniture(self, figs: list[int]) -> tuple[list[int], set[int]]:
486
+ """Leave out the figures read with the page furniture
487
+
488
+ Returns:
489
+ the other figures, and the text of the figures left out
490
+ """
491
+ furniture = [fig for fig in figs if self.in_furniture(fig)]
492
+ return [fig for fig in figs if fig not in furniture], {text for fig in furniture for text in self.text_of(fig)}
493
+
494
+ def _inside(self, idx: int, fig: int) -> bool:
495
+ """Whether each line of a block lies in a figure, by at least half of its area"""
496
+ target = self.boxes[fig]
497
+
498
+ def _coverage(box: tuple[float, ...]) -> float:
499
+ inter = max(min(box[2], target[2]) - max(box[0], target[0]), 0.0) * max(
500
+ min(box[3], target[3]) - max(box[1], target[1]), 0.0
501
+ )
502
+ return inter / max((box[2] - box[0]) * (box[3] - box[1]), 1e-9)
503
+
504
+ return all(_coverage(box) >= 0.5 for box in self.line_boxes.get(idx, [self.boxes[idx]]))
505
+
506
+ def _is_block(self, idx: int) -> bool:
507
+ from doctr.io.elements import Block
508
+
509
+ return 0 <= idx < len(self.items) and isinstance(self.items[idx], Block)
510
+
511
+ def _is_caption(self, idx: int) -> bool:
512
+ from doctr.models.reading_order import normalize_layout_label
513
+
514
+ return self._is_block(idx) and normalize_layout_label(self.labels[idx]) == "caption"
515
+
516
+ def text_of(self, fig: int) -> set[int]:
517
+ """The blocks inside a figure and labeled as part of it (or as furniture, for a figure in furniture)"""
518
+ from doctr.models.reading_order import layout_label_role
519
+ from doctr.models.reading_order.base import _FURNITURE_ROLES
520
+
521
+ in_furniture = self.in_furniture(fig)
522
+ return {
523
+ idx
524
+ for idx in range(len(self.items))
525
+ if self._is_block(idx)
526
+ and (
527
+ is_picture_label(self.labels[idx])
528
+ or (in_furniture and layout_label_role(self.labels[idx]) in _FURNITURE_ROLES)
529
+ )
530
+ and self._inside(idx, fig)
531
+ }
532
+
533
+ def _caption_run(self, start: int) -> tuple[int, ...]:
534
+ """The caption blocks of the caption region of a block (a caption region can span several blocks)"""
535
+ if self.region_of[start] == -1:
536
+ return (start,)
537
+ return tuple(
538
+ idx
539
+ for idx in range(len(self.items))
540
+ if self._is_caption(idx) and self.region_of[idx] == self.region_of[start]
541
+ )
542
+
543
+ def _distance(self, run: tuple[int, ...], target: int) -> float:
544
+ from doctr.models.reading_order.base import _caption_distance
545
+
546
+ run_box = tuple(func(self.boxes[idx][k] for idx in run) for k, func in enumerate((min, min, max, max)))
547
+ return _caption_distance(run_box, self.boxes[target])
548
+
549
+ def _table_without_caption(self, idx: int, run: tuple[int, ...]) -> bool:
550
+ """Whether a table stands next to a caption run, without its own caption on its other side"""
551
+ from doctr.io.elements import Table
552
+
553
+ if not (0 <= idx < len(self.items) and isinstance(self.items[idx], Table)):
554
+ return False
555
+ return not self._is_caption(idx + 1 if idx > run[-1] else idx - 1)
556
+
557
+ def captions(self, figures: list[int]) -> dict[int, tuple[int, ...]]:
558
+ """Pair figures and captions: each caption read right before a figure, or right after the text inside it, goes
559
+ to its closest float (a table without caption competes for it), and each figure keeps its closest caption
560
+
561
+ Args:
562
+ figures: the figures to caption
563
+
564
+ Returns:
565
+ the caption blocks of each captioned figure
566
+ """
567
+ claims: dict[tuple[int, ...], list[int]] = {}
568
+ for fig in figures:
569
+ after = fig + 1
570
+ while self._is_block(after) and not self._is_caption(after) and self._inside(after, fig):
571
+ after += 1
572
+ for cap in (fig - 1, after):
573
+ if self._is_caption(cap):
574
+ claims.setdefault(self._caption_run(cap), []).append(fig)
575
+ captions: dict[int, tuple[int, ...]] = {}
576
+ for run, candidates in claims.items():
577
+ tables = [idx for idx in (run[0] - 1, run[-1] + 1) if self._table_without_caption(idx, run)]
578
+ best = min([*candidates, *tables], key=lambda target: self._distance(run, target))
579
+ if best in tables or (
580
+ best in captions and self._distance(captions[best], best) <= self._distance(run, best)
581
+ ):
582
+ continue
583
+ captions[best] = run
584
+ return captions
585
+
586
+
587
+ class _PageTextExporter:
588
+ """Shared logic of the reading-order-aware text exporters
589
+
590
+ Subclasses define the format specifics: headings, bullets, escaping, line finalization, tables and figures.
591
+ """
592
+
593
+ headings: ClassVar[dict[str, str]] = {}
594
+ bullet: ClassVar[str] = "- "
595
+ block_break: ClassVar[str] = "\n\n"
596
+ page_break: ClassVar[str] = "\n\n"
597
+ # Whether the format can render figures
598
+ supports_figures: ClassVar[bool] = False
599
+ # Rendered for a figure without pixels
600
+ figure_placeholder: ClassVar[str] = ""
601
+
602
+ def escape_text(self, text: str) -> str:
603
+ """Escape the characters carrying a structural meaning in the target format"""
604
+ return text
605
+
606
+ def finalize_line(self, line: str) -> str:
607
+ """Neutralize the block-level markers a line must not start with in the target format"""
608
+ return line
609
+
610
+ def render_table(self, table: "Table", escape: bool = True) -> str:
611
+ """Render a recognized table in the target format"""
612
+ raise NotImplementedError
613
+
614
+ def render_formula(self, formula: "Formula", escape: bool = True) -> str:
615
+ """Render a recognized formula in the target format (its LaTeX source is never escaped as text)"""
616
+ return formula.value
617
+
618
+ def render_figure(self, source: str | None, caption: str | None = None, escape: bool = True) -> str:
619
+ """Render a figure in the target format
620
+
621
+ Args:
622
+ source: the image source (data URI or relative path), None to render the placeholder
623
+ caption: the unescaped caption of the figure, if any
624
+ escape: whether to escape the characters carrying a structural meaning
625
+
626
+ Returns:
627
+ the figure markup
628
+ """
629
+ return self.figure_placeholder
630
+
631
+ def render_heading(self, norm_label: str, lines: list[str], escape: bool = True) -> str:
632
+ """Render a heading in the target format"""
633
+ return self.headings[norm_label] + " ".join(lines)
634
+
635
+ def render_list_item(self, lines: list[str], escape: bool = True) -> str:
636
+ """Render a list item in the target format"""
637
+ text = " ".join(lines)
638
+ return self.bullet + (self.finalize_line(text) if escape else text)
639
+
640
+ def render_list(self, items: list[str]) -> str:
641
+ """Render a list from its rendered items in the target format"""
642
+ return "\n".join(items)
643
+
644
+ def render_paragraph(self, lines: list[str], escape: bool = True) -> str:
645
+ """Render a paragraph in the target format"""
646
+ return "\n".join(self.finalize_line(line) if escape else line for line in lines)
647
+
648
+ def class_header(self, class_name: str, escape: bool = True) -> str:
649
+ """Render the header of a detection class in a KIE export"""
650
+ raise NotImplementedError
651
+
652
+ def _line_text(self, line: "Line", direction: str, escape: bool) -> str:
653
+ """Render the text of a line, ordering the words according to the reading direction."""
654
+ text = " ".join(word.render() for word in ordered_line_words(line, direction))
655
+ return self.escape_text(text) if escape else text
656
+
657
+ def _block_lines(self, block: "Block", direction: str, escape: bool, auto: bool) -> list[str]:
658
+ """Render the non-empty lines of a block"""
659
+ lines = [self._line_text(line, _line_render_direction(line, direction, auto), escape) for line in block.lines]
660
+ return [line for line in lines if line.strip()]
661
+
662
+ def _plan_figures(
663
+ self,
664
+ page: "Page",
665
+ items: list[Any],
666
+ labels: list[str | None],
667
+ encoder: FigureEncoder,
668
+ direction: str,
669
+ escape: bool,
670
+ auto: bool,
671
+ include_furniture: bool = True,
672
+ ) -> "_FigurePlan":
673
+ """Render the figures of a page, with their caption when they carry their pixels
674
+
675
+ Args:
676
+ page: the page to export
677
+ items: the linearized page content, figures included
678
+ labels: the layout label of each item
679
+ encoder: the figure encoder
680
+ direction: the effective reading direction
681
+ escape: whether to escape the characters carrying a structural meaning
682
+ auto: whether the reading direction was detected automatically
683
+ include_furniture: whether page headers, page footers and footnotes are exported
684
+
685
+ Returns:
686
+ the figure markup, the captions rendered with their figure and the text to leave out
687
+ """
688
+ from doctr.io.elements import LayoutElement
689
+
690
+ figure_idcs = [idx for idx, item in enumerate(items) if isinstance(item, LayoutElement)]
691
+ render = self.supports_figures and encoder.enabled
692
+ if not figure_idcs or not (render or not include_furniture):
693
+ return _FigurePlan({}, set(), set())
694
+
695
+ figures = _PageFigures(page, items, labels)
696
+ hidden: set[int] = set()
697
+ if not include_furniture:
698
+ # Figures read with the page furniture are left out with it, along with their text
699
+ figure_idcs, hidden = figures.without_furniture(figure_idcs)
700
+ if not render or not figure_idcs:
701
+ return _FigurePlan({}, set(), hidden)
702
+
703
+ sources = {idx: encoder.source(page, items[idx], rank) for rank, idx in enumerate(figure_idcs, start=1)}
704
+ # Only a figure exported with its pixels makes its text redundant, and takes a caption as alternative text
705
+ shown = [idx for idx in figure_idcs if sources[idx] is not None]
706
+ hidden |= {text for idx in shown for text in figures.text_of(idx)}
707
+ captions = figures.captions(shown)
708
+ markup: dict[int, str] = {}
709
+ consumed: set[int] = set()
710
+ for idx in figure_idcs:
711
+ caption = self._caption_text([items[cap] for cap in captions.get(idx, ())], direction, auto)
712
+ if caption is not None:
713
+ consumed.update(captions[idx])
714
+ markup[idx] = self.render_figure(sources[idx], caption, escape=escape)
715
+ return _FigurePlan(markup, consumed, hidden)
716
+
717
+ def _caption_text(self, blocks: list[Any], direction: str, auto: bool) -> str | None:
718
+ """Join the lines of the caption blocks of a figure into one caption (None without any text)"""
719
+ lines = [line for block in blocks for line in self._block_lines(block, direction, False, auto)]
720
+ return _join_caption_lines(lines) or None
721
+
722
+ def export_page(
723
+ self,
724
+ page: "Page",
725
+ direction: str = "auto",
726
+ escape: bool = True,
727
+ include_furniture: bool = True,
728
+ block_break: str | None = None,
729
+ images: "str | FigureEncoder | None" = "placeholder",
730
+ ) -> str:
731
+ """Export a page, with its content sorted in reading order.
732
+
733
+ Args:
734
+ page: the page to export
735
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
736
+ escape: whether the characters or markers carrying a structural meaning should be neutralized
737
+ include_furniture: whether page headers, page footers and footnotes should be included
738
+ block_break: the string inserted between two blocks (the format-specific default when None)
739
+ images: how to render the figures: 'none', 'placeholder', 'embedded', or a
740
+ :class:`~doctr.io.FigureEncoder` (required for 'referenced')
741
+
742
+ Returns:
743
+ the exported page as a string
744
+ """
745
+ from doctr.io.elements import Formula, LayoutElement, Table
746
+ from doctr.models.reading_order import layout_label_role, normalize_layout_label
747
+ from doctr.models.reading_order.base import _FURNITURE_ROLES
748
+
749
+ auto = direction == "auto"
750
+ encoder = FigureEncoder.resolve(images)
751
+ items, labels, direction = page_reading_order(page, direction, include_figures=True)
752
+ figures, absorbed_captions, figure_text = self._plan_figures(
753
+ page, items, labels, encoder, direction, escape, auto, include_furniture=include_furniture
754
+ )
755
+ parts: list[str] = []
756
+ list_group: list[str] = []
757
+
758
+ def _flush_list() -> None:
759
+ if list_group:
760
+ parts.append(self.render_list(list_group))
761
+ list_group.clear()
762
+
763
+ for index, (item, label) in enumerate(zip(items, labels)):
764
+ if not include_furniture and layout_label_role(label) in _FURNITURE_ROLES:
765
+ continue
766
+ if isinstance(item, LayoutElement):
767
+ if figures.get(index):
768
+ _flush_list()
769
+ parts.append(figures[index])
770
+ continue
771
+ if index in absorbed_captions or index in figure_text:
772
+ continue
773
+ if isinstance(item, (Table, Formula)):
774
+ _flush_list()
775
+ rendered = (
776
+ self.render_table(item, escape=escape)
777
+ if isinstance(item, Table)
778
+ else self.render_formula(item, escape=escape)
779
+ )
780
+ if rendered:
781
+ parts.append(rendered)
782
+ continue
783
+ item_lines = self._block_lines(item, direction, escape, auto)
784
+ if len(item_lines) == 0:
785
+ continue
786
+ norm_label = normalize_layout_label(label)
787
+ if layout_label_role(label) == "float":
788
+ # Text of a table or figure region without structure: one paragraph per row
789
+ _flush_list()
790
+ parts.extend(self.render_paragraph([line], escape) for line in item_lines)
791
+ elif norm_label in self.headings:
792
+ _flush_list()
793
+ parts.append(self.render_heading(norm_label, item_lines, escape))
794
+ elif norm_label in _LIST_LABELS:
795
+ # A list item (possibly wrapped over several lines) renders as a single bullet
796
+ list_group.append(self.render_list_item(item_lines, escape))
797
+ else:
798
+ _flush_list()
799
+ parts.append(self.render_paragraph(item_lines, escape))
800
+ _flush_list()
801
+ return (self.block_break if block_break is None else block_break).join(parts)
802
+
803
+ def export_kie_page(self, page: "KIEPage", direction: str = "auto", escape: bool = True) -> str:
804
+ """Export a KIE page, with the predictions of each class sorted in reading order.
805
+
806
+ Args:
807
+ page: the KIE page to export
808
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
809
+ escape: whether the characters or markers carrying a structural meaning should be neutralized
810
+
811
+ Returns:
812
+ the exported page as a string, with one section per detection class
813
+ """
814
+ parts: list[str] = []
815
+ for class_name, predictions in page.predictions.items():
816
+ if len(predictions) == 0:
817
+ continue
818
+ values = "\n".join(
819
+ self.bullet + (self.finalize_line(self.escape_text(prediction.value)) if escape else prediction.value)
820
+ for prediction in predictions_in_reading_order(page, predictions, direction)
821
+ )
822
+ parts.append(f"{self.class_header(class_name, escape)}\n\n{values}")
823
+ return "\n\n".join(parts)
824
+
825
+ def export_document(self, document: Any, page_break: str | None = None, **kwargs: Any) -> str:
826
+ """Export a document page by page.
827
+
828
+ Args:
829
+ document: the document to export
830
+ page_break: the string inserted between two pages (a format-specific default when None)
831
+ **kwargs: additional keyword arguments passed to the page export
832
+
833
+ Returns:
834
+ the exported document as a string
835
+ """
836
+ from doctr.io.elements import KIEPage
837
+
838
+ page_break = self.page_break if page_break is None else page_break
839
+ return page_break.join(
840
+ self.export_kie_page(page, **kwargs) if isinstance(page, KIEPage) else self.export_page(page, **kwargs)
841
+ for page in document.pages
842
+ )
843
+
844
+
845
+ class TextExporter(_PageTextExporter):
846
+ """Export OCR results to plain text, with the content sorted in reading order.
847
+
848
+ >>> from doctr.io import TextExporter
849
+ >>> text = TextExporter().export_page(page)
850
+ """
851
+
852
+ headings: ClassVar[dict[str, str]] = {}
853
+ bullet: ClassVar[str] = ""
854
+ block_break: ClassVar[str] = "\n\n"
855
+ page_break: ClassVar[str] = "\n\n\n\n"
856
+
857
+ def render_table(self, table: "Table", escape: bool = True) -> str:
858
+ """Render a table as tab-separated values, one line per row"""
859
+ return table.render()
860
+
861
+ def class_header(self, class_name: str, escape: bool = True) -> str:
862
+ return f"{class_name}:"
863
+
864
+
865
+ class MarkdownExporter(_PageTextExporter):
866
+ """Export OCR results to Markdown, with the content sorted in reading order.
867
+
868
+ >>> from doctr.io import MarkdownExporter
869
+ >>> markdown = MarkdownExporter().export_page(page)
870
+ """
871
+
872
+ headings: ClassVar[dict[str, str]] = {"title": "# ", "section_header": "## "}
873
+ bullet: ClassVar[str] = "- "
874
+ page_break: ClassVar[str] = "\n\n---\n\n"
875
+ supports_figures: ClassVar[bool] = True
876
+ figure_placeholder: ClassVar[str] = "<!-- image -->"
877
+
878
+ def escape_text(self, text: str) -> str:
879
+ return "".join(f"\\{char}" if char in _MD_SPECIAL_CHARS else char for char in text)
880
+
881
+ def finalize_line(self, line: str) -> str:
882
+ stripped = line.lstrip()
883
+ if stripped and stripped[0] in _MD_LINE_MARKERS:
884
+ return f"\\{line}" if line[0] != "\\" else line
885
+ # Escape the list delimiter: a backslash before a digit is not a Markdown escape
886
+ return _MD_ORDERED_MARKER.sub(r"\1\\\2", line)
887
+
888
+ def render_table(self, table: "Table", escape: bool = True) -> str:
889
+ """Render a table as a GitHub-flavored Markdown table (first row used as header)"""
890
+ grid = table.to_grid()
891
+ if len(grid) == 0 or len(grid[0]) == 0:
892
+ return ""
893
+
894
+ def _cell(value: str) -> str:
895
+ value = self.escape_text(value) if escape else value.replace("|", "\\|")
896
+ return value.replace("\n", " ").strip()
897
+
898
+ rows = ["| " + " | ".join(_cell(value) for value in row) + " |" for row in grid]
899
+ separator = "| " + " | ".join("---" for _ in grid[0]) + " |"
900
+ return "\n".join([rows[0], separator, *rows[1:]])
901
+
902
+ def render_formula(self, formula: "Formula", escape: bool = True) -> str:
903
+ """Render a formula as display math: `$$`, the LaTeX source and `$$` on their own lines"""
904
+ return f"$$\n{formula.value}\n$$" if formula.value else ""
905
+
906
+ def render_figure(self, source: str | None, caption: str | None = None, escape: bool = True) -> str:
907
+ """Render a figure as an image, with its caption as alt text and as a visible italic line below"""
908
+ if source is None:
909
+ return self.figure_placeholder
910
+ caption = caption or ""
911
+ # The link label delimiters are escaped in any case
912
+ if escape:
913
+ alt = self.escape_text(caption)
914
+ else:
915
+ alt = caption.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]")
916
+ image = f"![{alt}]({source})"
917
+ if not caption:
918
+ return image
919
+ return f"{image}\n\n*{self.escape_text(caption) if escape else caption}*"
920
+
921
+ def class_header(self, class_name: str, escape: bool = True) -> str:
922
+ return f"**{self.escape_text(class_name) if escape else class_name}**"
923
+
924
+
925
+ class AsciiDocExporter(_PageTextExporter):
926
+ """Export OCR results to AsciiDoc, with the content sorted in reading order.
927
+
928
+ >>> from doctr.io import AsciiDocExporter
929
+ >>> asciidoc = AsciiDocExporter().export_page(page)
930
+ """
931
+
932
+ headings: ClassVar[dict[str, str]] = {"title": "== ", "section_header": "=== "}
933
+ bullet: ClassVar[str] = "* "
934
+ page_break: ClassVar[str] = "\n\n<<<\n\n"
935
+ supports_figures: ClassVar[bool] = True
936
+ figure_placeholder: ClassVar[str] = "// image"
937
+
938
+ def escape_text(self, text: str) -> str:
939
+ return "".join(f"\\{char}" if char in _ADOC_SPECIAL_CHARS else char for char in text)
940
+
941
+ def finalize_line(self, line: str) -> str:
942
+ stripped = line.lstrip()
943
+ if stripped and stripped[0] in _ADOC_LINE_MARKERS:
944
+ return f"{{empty}}{line}"
945
+ return line
946
+
947
+ def render_table(self, table: "Table", escape: bool = True) -> str:
948
+ """Render a table as an AsciiDoc table (first row used as header)"""
949
+ grid = table.to_grid()
950
+ if len(grid) == 0 or len(grid[0]) == 0:
951
+ return ""
952
+
953
+ def _row(row: list[str]) -> str:
954
+ return " ".join(
955
+ "|" + (self.escape_text(value) if escape else value.replace("|", "\\|")).replace("\n", " ").strip()
956
+ for value in row
957
+ )
958
+
959
+ return "\n".join(["|===", _row(grid[0]), "", *[_row(row) for row in grid[1:]], "|==="])
960
+
961
+ def render_formula(self, formula: "Formula", escape: bool = True) -> str:
962
+ """Render a formula as a `latexmath` passthrough block"""
963
+ return f"[latexmath]\n++++\n{formula.value}\n++++" if formula.value else ""
964
+
965
+ def render_figure(self, source: str | None, caption: str | None = None, escape: bool = True) -> str:
966
+ """Render a figure as a block image macro, titled with its caption"""
967
+ if source is None:
968
+ return self.figure_placeholder
969
+ if not caption:
970
+ return f"image::{source}[]"
971
+ title = self.escape_text(caption) if escape else caption
972
+ if title.startswith("."): # would open a literal block
973
+ title = "{empty}" + title
974
+ # Quoted, so that commas do not split the alt text into several attributes
975
+ alt = caption.replace('"', '\\"')
976
+ if escape: # attribute references are also substituted in attribute values
977
+ alt = alt.replace("{", "\\{").replace("}", "\\}")
978
+ # The detected caption carries its own label (e.g. "Figure 3:"): disable the automatic "Figure N." prefix
979
+ return f'[caption=""]\n.{title}\nimage::{source}["{alt}"]'
980
+
981
+ def class_header(self, class_name: str, escape: bool = True) -> str:
982
+ return f"*{self.escape_text(class_name) if escape else class_name}*"
983
+
984
+
985
+ class HTMLExporter(_PageTextExporter):
986
+ """Export OCR results to semantic HTML, with the content sorted in reading order.
987
+
988
+ Headings map to `<h1>`/`<h2>`, list items to `<ul><li>`, recognized tables to `<table>`, recognized formulas to
989
+ `<div class="formula">` holding `$$...$$` display math (rendered by MathJax or KaTeX auto-render) and
990
+ paragraphs to `<p>` (with `<br>` between the visual lines of a paragraph). The output is a
991
+ fragment, not a full document: it carries no doctype, `<html>` or charset declaration.
992
+
993
+ .. warning::
994
+ The recognized text is HTML-escaped by default. Passing ``escape=False`` interpolates the OCR
995
+ output into the markup verbatim, so a document containing markup yields active HTML.
996
+ Only disable escaping for output that is never rendered in a browser.
997
+
998
+ >>> from doctr.io import HTMLExporter
999
+ >>> html = HTMLExporter().export_page(page)
1000
+ """
1001
+
1002
+ headings: ClassVar[dict[str, str]] = {"title": "h1", "section_header": "h2"}
1003
+ block_break: ClassVar[str] = "\n"
1004
+ page_break: ClassVar[str] = "\n<hr>\n"
1005
+ supports_figures: ClassVar[bool] = True
1006
+ figure_placeholder: ClassVar[str] = "<!-- image -->"
1007
+
1008
+ def escape_text(self, text: str) -> str:
1009
+ return _html_escape(text, quote=False)
1010
+
1011
+ def render_heading(self, norm_label: str, lines: list[str], escape: bool = True) -> str:
1012
+ tag = self.headings[norm_label]
1013
+ return f"<{tag}>{' '.join(lines)}</{tag}>"
1014
+
1015
+ def render_list_item(self, lines: list[str], escape: bool = True) -> str:
1016
+ return f"<li>{' '.join(lines)}</li>"
1017
+
1018
+ def render_list(self, items: list[str]) -> str:
1019
+ return "<ul>\n" + "\n".join(items) + "\n</ul>"
1020
+
1021
+ def render_paragraph(self, lines: list[str], escape: bool = True) -> str:
1022
+ return "<p>" + "<br>\n".join(lines) + "</p>"
1023
+
1024
+ def render_figure(self, source: str | None, caption: str | None = None, escape: bool = True) -> str:
1025
+ """Render a figure as a `<figure>` element, with its caption as `<figcaption>`"""
1026
+ if source is None:
1027
+ return self.figure_placeholder
1028
+ alt = _html_escape(caption or "", quote=True)
1029
+ figcaption = f"\n<figcaption>{self.escape_text(caption) if escape else caption}</figcaption>" if caption else ""
1030
+ return f'<figure><img src="{_html_escape(source, quote=True)}" alt="{alt}">{figcaption}</figure>'
1031
+
1032
+ def render_formula(self, formula: "Formula", escape: bool = True) -> str:
1033
+ """Render a formula as `$$...$$` display math in a `<div class="formula">`"""
1034
+ if not formula.value:
1035
+ return ""
1036
+ return f'<div class="formula">$${self.escape_text(formula.value) if escape else formula.value}$$</div>'
1037
+
1038
+ def render_table(self, table: "Table", escape: bool = True) -> str:
1039
+ """Render a table as an HTML table (first row used as header). A cell spanning several rows / columns is
1040
+ written with `rowspan` / `colspan` when the positions it covers hold no other text."""
1041
+ grid = table.to_grid()
1042
+ if len(grid) == 0 or len(grid[0]) == 0:
1043
+ return ""
1044
+ num_rows, num_cols = len(grid), len(grid[0])
1045
+
1046
+ # Top-left position -> (row span, column span) of the merged cells, and the positions they cover
1047
+ spans: dict[tuple[int, int], tuple[int, int]] = {}
1048
+ covered: set[tuple[int, int]] = set()
1049
+ # The merge whose top-left comes first (row-major) wins, whatever the order of `table.cells`; with the same
1050
+ # top-left, the one ending first
1051
+ for cell in sorted(table.cells, key=lambda cell: (cell.row_start, cell.col_start, cell.row_end, cell.col_end)):
1052
+ r0, c0 = cell.row_start, cell.col_start
1053
+ r1, c1 = min(cell.row_end, num_rows - 1), min(cell.col_end, num_cols - 1)
1054
+ if r0 < 0 or c0 < 0 or r1 < r0 or c1 < c0 or (r1 == r0 and c1 == c0):
1055
+ continue
1056
+ area = {(r, c) for r in range(r0, r1 + 1) for c in range(c0, c1 + 1)}
1057
+ others = area - {(r0, c0)}
1058
+ # Keep the dense layout when the merge would hide text or cross another merged cell
1059
+ if area & covered or any(pos in spans for pos in area) or any(grid[r][c].strip() for r, c in others):
1060
+ continue
1061
+ spans[(r0, c0)] = (r1 - r0 + 1, c1 - c0 + 1)
1062
+ covered |= others
1063
+
1064
+ # Drop the rows entirely covered by merges from above (no `<tr></tr>`), shrinking the row spans crossing them
1065
+ dropped = {r for r in range(num_rows) if all((r, c) in covered for c in range(num_cols))}
1066
+ if dropped:
1067
+ spans = {
1068
+ (r0, c0): (row_span - sum(r in dropped for r in range(r0, r0 + row_span)), col_span)
1069
+ for (r0, c0), (row_span, col_span) in spans.items()
1070
+ }
1071
+
1072
+ def _cell(value: str, tag: str, position: tuple[int, int]) -> str:
1073
+ content = self.escape_text(value) if escape else value
1074
+ row_span, col_span = spans.get(position, (1, 1))
1075
+ attrs = (f' rowspan="{row_span}"' if row_span > 1 else "") + (
1076
+ f' colspan="{col_span}"' if col_span > 1 else ""
1077
+ )
1078
+ return f"<{tag}{attrs}>{content.strip()}</{tag}>"
1079
+
1080
+ rows = [
1081
+ "<tr>"
1082
+ + "".join(_cell(value, "td" if r else "th", (r, c)) for c, value in enumerate(row) if (r, c) not in covered)
1083
+ + "</tr>"
1084
+ for r, row in enumerate(grid)
1085
+ if r not in dropped
1086
+ ]
1087
+ return "<table>\n" + "\n".join(rows) + "\n</table>"
1088
+
1089
+ def export_kie_page(self, page: "KIEPage", direction: str = "auto", escape: bool = True) -> str:
1090
+ parts: list[str] = []
1091
+ for class_name, predictions in page.predictions.items():
1092
+ if len(predictions) == 0:
1093
+ continue
1094
+ values = "\n".join(
1095
+ f"<li>{self.escape_text(prediction.value) if escape else prediction.value}</li>"
1096
+ for prediction in predictions_in_reading_order(page, predictions, direction)
1097
+ )
1098
+ header = self.escape_text(class_name) if escape else class_name
1099
+ parts.append(f"<h3>{header}</h3>\n<ul>\n{values}\n</ul>")
1100
+ return "\n".join(parts)
1101
+
1102
+
1103
+ def _resolve_hocr_language(language: dict[str, Any]) -> str:
1104
+ """Resolve the language code to use in the hOCR export, falling back to 'en'.
1105
+
1106
+ Args:
1107
+ language: the page language dictionary `{"value": str | None, "confidence": float | None}`
1108
+
1109
+ Returns:
1110
+ the detected language code when available, 'en' otherwise
1111
+ """
1112
+ lang_value = language.get("value") if isinstance(language, dict) else None
1113
+ return lang_value if isinstance(lang_value, str) and len(lang_value) > 0 else "en"
1114
+
1115
+
1116
+ def _hocr_bbox(geometry: BoundingBox, width: int, height: int) -> str:
1117
+ """Format a relative straight bounding box as an absolute hOCR `bbox` property string.
1118
+
1119
+ Args:
1120
+ geometry: the relative bounding box ((xmin, ymin), (xmax, ymax))
1121
+ width: the page width in pixels
1122
+ height: the page height in pixels
1123
+
1124
+ Returns:
1125
+ the hOCR `bbox` property string
1126
+ """
1127
+ (xmin, ymin), (xmax, ymax) = geometry
1128
+ return (
1129
+ f"bbox {int(round(xmin * width))} {int(round(ymin * height))} "
1130
+ f"{int(round(xmax * width))} {int(round(ymax * height))}"
1131
+ )
1132
+
1133
+
1134
+ def _hocr_text_size(geometry: BoundingBox, height: int, dpi: int = 72) -> tuple[int, int]:
1135
+ """Estimate the hOCR `x_size` and `x_fsize` properties from the height of a relative bounding box.
1136
+
1137
+ Args:
1138
+ geometry: the relative bounding box ((xmin, ymin), (xmax, ymax))
1139
+ height: the page height in pixels
1140
+ dpi: the page resolution in dots per inch, used to convert the text height to font points
1141
+
1142
+ Returns:
1143
+ a tuple of the text height in pixels (`x_size`), and the estimated font size in points (`x_fsize`)
1144
+ """
1145
+ (_, ymin), (_, ymax) = geometry
1146
+ x_size = int(round((ymax - ymin) * height))
1147
+ return x_size, int(round(x_size * 72 / dpi))
1148
+
1149
+
1150
+ class XMLExporter:
1151
+ """hOCR (XML) exporter for pages, KIE pages and documents.
1152
+ See the hOCR 1.2 specification for the XML convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
1153
+
1154
+ >>> from doctr.io import XMLExporter
1155
+ >>> xml_bytes, xml_tree = XMLExporter().export_page(page)
1156
+ """
1157
+
1158
+ ocr_capabilities: ClassVar[str] = "ocr_page ocr_carea ocr_par ocr_line ocrx_word ocr_photo ocr_math"
1159
+
1160
+ def _new_document(self, file_title: str, language: str) -> tuple[ETElement, ETElement]:
1161
+ """Create the hOCR root element with its <head>, returning the root and its <body> element."""
1162
+ root = ETElement("html", attrib={"xmlns": "http://www.w3.org/1999/xhtml", "xml:lang": str(language)})
1163
+ head = SubElement(root, "head")
1164
+ SubElement(head, "title").text = file_title
1165
+ SubElement(head, "meta", attrib={"http-equiv": "Content-Type", "content": "text/html; charset=utf-8"})
1166
+ SubElement(
1167
+ head,
1168
+ "meta",
1169
+ attrib={"name": "ocr-system", "content": f"python-doctr {doctr.__version__}"}, # type: ignore[attr-defined]
1170
+ )
1171
+ SubElement(head, "meta", attrib={"name": "ocr-capabilities", "content": self.ocr_capabilities})
1172
+ return root, SubElement(root, "body")
1173
+
1174
+ def _add_table(
1175
+ self, page_div: ETElement, table: "Table", width: int, height: int, table_count: int, dpi: int = 72
1176
+ ) -> int:
1177
+ """Serialize a recognized table as an hOCR text area, with one `ocr_line` per row.
1178
+
1179
+ Args:
1180
+ page_div: the `ocr_page` element the table is appended to
1181
+ table: the table to serialize
1182
+ width: the page width in pixels
1183
+ height: the page height in pixels
1184
+ table_count: the 1-based index of the table on the page
1185
+ dpi: the page resolution in dots per inch, used to estimate font sizes
1186
+
1187
+ Returns:
1188
+ the index of the next table
1189
+ """
1190
+ if len(table.geometry) != 2 or any(len(cell.geometry) != 2 for cell in table.cells):
1191
+ raise TypeError("XML export is only available for straight bounding boxes for now.")
1192
+ table_bbox = _hocr_bbox(table.geometry, width, height) # type: ignore[arg-type]
1193
+ table_div = SubElement(
1194
+ page_div, "div", attrib={"class": "ocr_carea", "id": f"table_{table_count}", "title": table_bbox}
1195
+ )
1196
+ paragraph = SubElement(
1197
+ table_div, "p", attrib={"class": "ocr_par", "id": f"table_par_{table_count}", "title": table_bbox}
1198
+ )
1199
+ rows: dict[int, list[Any]] = {}
1200
+ for cell in table.cells:
1201
+ rows.setdefault(cell.row_start, []).append(cell)
1202
+ for row_idx in sorted(rows):
1203
+ cells = sorted(rows[row_idx], key=lambda cell: cell.col_start)
1204
+ xs = [coord for cell in cells for coord in (cell.geometry[0][0], cell.geometry[1][0])]
1205
+ ys = [coord for cell in cells for coord in (cell.geometry[0][1], cell.geometry[1][1])]
1206
+ row_geometry = ((min(xs), min(ys)), (max(xs), max(ys)))
1207
+ row_bbox = _hocr_bbox(row_geometry, width, height)
1208
+ row_x_size, row_x_fsize = _hocr_text_size(row_geometry, height, dpi)
1209
+ line_span = SubElement(
1210
+ paragraph,
1211
+ "span",
1212
+ attrib={
1213
+ "class": "ocr_line",
1214
+ "id": f"table_{table_count}_row_{row_idx + 1}",
1215
+ "title": (
1216
+ f"{row_bbox}; baseline 0 0; x_size {row_x_size}; x_fsize {row_x_fsize}; "
1217
+ "x_descenders 0; x_ascenders 0"
1218
+ ),
1219
+ },
1220
+ )
1221
+ for col_idx, cell in enumerate(cells):
1222
+ cell_span = SubElement(
1223
+ line_span,
1224
+ "span",
1225
+ attrib={
1226
+ "class": "ocrx_word",
1227
+ "id": f"table_{table_count}_cell_{row_idx + 1}_{col_idx + 1}",
1228
+ "title": (
1229
+ f"{_hocr_bbox(cell.geometry, width, height)}; x_wconf {int(round(cell.confidence * 100))}"
1230
+ ),
1231
+ },
1232
+ )
1233
+ cell_span.text = cell.value
1234
+ return table_count + 1
1235
+
1236
+ def _add_formula(self, page_div: ETElement, formula: "Formula", width: int, height: int, formula_count: int) -> int:
1237
+ """Add a formula as an hOCR text area holding an `ocr_math` element, with its LaTeX source as text
1238
+
1239
+ Args:
1240
+ page_div: the `ocr_page` element
1241
+ formula: the formula
1242
+ width: page width in pixels
1243
+ height: page height in pixels
1244
+ formula_count: 1-based index of the formula on the page
1245
+
1246
+ Returns:
1247
+ the index of the next formula
1248
+ """
1249
+ xmin, ymin, xmax, ymax = _xyxy(formula.geometry)
1250
+ bbox = _hocr_bbox(((xmin, ymin), (xmax, ymax)), width, height)
1251
+ area = SubElement(
1252
+ page_div, "div", attrib={"class": "ocr_carea", "id": f"formula_area_{formula_count}", "title": bbox}
1253
+ )
1254
+ paragraph = SubElement(
1255
+ area, "p", attrib={"class": "ocr_par", "id": f"formula_par_{formula_count}", "title": bbox}
1256
+ )
1257
+ math = SubElement(
1258
+ paragraph,
1259
+ "span",
1260
+ attrib={
1261
+ "class": "ocr_math",
1262
+ "id": f"formula_{formula_count}",
1263
+ "title": f"{bbox}; x_wconf {int(round(formula.confidence * 100))}",
1264
+ },
1265
+ )
1266
+ math.text = formula.value
1267
+ return formula_count + 1
1268
+
1269
+ def _add_figure(
1270
+ self, page_div: ETElement, region: "LayoutElement", width: int, height: int, figure_count: int
1271
+ ) -> int:
1272
+ """Add a figure as an hOCR `ocr_photo` area, with its enclosing box
1273
+
1274
+ Args:
1275
+ page_div: the `ocr_page` element
1276
+ region: the figure region
1277
+ width: page width in pixels
1278
+ height: page height in pixels
1279
+ figure_count: 1-based index of the figure on the page
1280
+
1281
+ Returns:
1282
+ the index of the next figure
1283
+ """
1284
+ xmin, ymin, xmax, ymax = _xyxy(region.geometry)
1285
+ SubElement(
1286
+ page_div,
1287
+ "div",
1288
+ attrib={
1289
+ "class": "ocr_photo",
1290
+ "id": f"figure_{figure_count}",
1291
+ "title": _hocr_bbox(((xmin, ymin), (xmax, ymax)), width, height),
1292
+ },
1293
+ )
1294
+ return figure_count + 1
1295
+
1296
+ def export_page(
1297
+ self,
1298
+ page: "Page",
1299
+ file_title: str = "docTR - XML export (hOCR)",
1300
+ direction: str = "auto",
1301
+ reading_order: bool = True,
1302
+ dpi: int = 72,
1303
+ ) -> tuple[bytes, ET.ElementTree]:
1304
+ """Export a page as hOCR XML, with its content sorted in reading order.
1305
+
1306
+ Figures are exported as `ocr_photo` areas, formulas as `ocr_math` elements holding their LaTeX source.
1307
+
1308
+ Args:
1309
+ page: the page to export
1310
+ file_title: the title of the XML file
1311
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1312
+ reading_order: whether the content should be linearized in reading order. Pass False to serialize
1313
+ `page.blocks`, `page.tables` then `page.formulas` in their raw order.
1314
+ dpi: the page resolution in dots per inch, used to estimate font sizes (`x_size`, `x_fsize`)
1315
+
1316
+ Returns:
1317
+ a tuple of the XML byte string, and its ElementTree
1318
+ """
1319
+ from doctr.io.elements import Formula, LayoutElement, Table
1320
+
1321
+ block_count: int = 1
1322
+ line_count: int = 1
1323
+ word_count: int = 1
1324
+ table_count: int = 1
1325
+ figure_count: int = 1
1326
+ formula_count: int = 1
1327
+ height, width = page.dimensions
1328
+ page_hocr, body = self._new_document(file_title, _resolve_hocr_language(page.language))
1329
+ page_div = SubElement(
1330
+ body,
1331
+ "div",
1332
+ attrib={
1333
+ "class": "ocr_page",
1334
+ "id": f"page_{page.page_idx + 1}",
1335
+ "title": f"image; bbox 0 0 {width} {height}; ppageno 0",
1336
+ },
1337
+ )
1338
+ auto = direction == "auto"
1339
+ if reading_order:
1340
+ items, _, direction = page_reading_order(page, direction, include_figures=True)
1341
+ else:
1342
+ items = [*page.blocks, *page.tables, *page.formulas, *picture_regions(page)]
1343
+ # iterate over the blocks / lines / words and create the XML elements line by line with the attributes
1344
+ for item in items:
1345
+ if isinstance(item, Table):
1346
+ table_count = self._add_table(page_div, item, width, height, table_count, dpi=dpi)
1347
+ continue
1348
+ if isinstance(item, LayoutElement):
1349
+ figure_count = self._add_figure(page_div, item, width, height, figure_count)
1350
+ continue
1351
+ if isinstance(item, Formula):
1352
+ formula_count = self._add_formula(page_div, item, width, height, formula_count)
1353
+ continue
1354
+ block = item
1355
+ if len(block.geometry) != 2:
1356
+ raise TypeError("XML export is only available for straight bounding boxes for now.")
1357
+ block_bbox = _hocr_bbox(block.geometry, width, height)
1358
+ block_div = SubElement(
1359
+ page_div,
1360
+ "div",
1361
+ attrib={"class": "ocr_carea", "id": f"block_{block_count}", "title": block_bbox},
1362
+ )
1363
+ paragraph = SubElement(
1364
+ block_div,
1365
+ "p",
1366
+ attrib={"class": "ocr_par", "id": f"par_{block_count}", "title": block_bbox},
1367
+ )
1368
+ block_count += 1
1369
+ for line in block.lines:
1370
+ # NOTE: baseline, x_descenders, x_ascenders are currently initialized to 0,
1371
+ # while x_size and x_fsize are estimated from the line box height
1372
+ x_size, x_fsize = _hocr_text_size(line.geometry, height, dpi)
1373
+ line_span = SubElement(
1374
+ paragraph,
1375
+ "span",
1376
+ attrib={
1377
+ "class": "ocr_line",
1378
+ "id": f"line_{line_count}",
1379
+ "title": (
1380
+ f"{_hocr_bbox(line.geometry, width, height)}; "
1381
+ f"baseline 0 0; x_size {x_size}; x_fsize {x_fsize}; x_descenders 0; x_ascenders 0"
1382
+ ),
1383
+ },
1384
+ )
1385
+ line_count += 1
1386
+ for word in ordered_line_words(line, direction, auto):
1387
+ word_div = SubElement(
1388
+ line_span,
1389
+ "span",
1390
+ attrib={
1391
+ "class": "ocrx_word",
1392
+ "id": f"word_{word_count}",
1393
+ "title": (
1394
+ f"{_hocr_bbox(word.geometry, width, height)}; "
1395
+ f"x_wconf {int(round(word.confidence * 100))}"
1396
+ ),
1397
+ },
1398
+ )
1399
+ word_div.text = word.value
1400
+ word_count += 1
1401
+ return ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr)
1402
+
1403
+ def export_kie_page(
1404
+ self,
1405
+ page: "KIEPage",
1406
+ file_title: str = "docTR - XML export (hOCR)",
1407
+ direction: str = "auto",
1408
+ reading_order: bool = True,
1409
+ dpi: int = 72,
1410
+ ) -> tuple[bytes, ET.ElementTree]:
1411
+ """Export a KIE page as hOCR XML, with the predictions of each class sorted in reading order.
1412
+
1413
+ Args:
1414
+ page: the KIE page to export
1415
+ file_title: the title of the XML file
1416
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1417
+ reading_order: whether the predictions of each class should be sorted in reading order
1418
+ dpi: the page resolution in dots per inch, used to estimate font sizes (`x_size`, `x_fsize`)
1419
+
1420
+ Returns:
1421
+ a tuple of the XML byte string, and its ElementTree
1422
+ """
1423
+ prediction_count: int = 1
1424
+ height, width = page.dimensions
1425
+ page_hocr, body = self._new_document(file_title, _resolve_hocr_language(page.language))
1426
+ page_div = SubElement(
1427
+ body,
1428
+ "div",
1429
+ attrib={
1430
+ "class": "ocr_page",
1431
+ "id": f"page_{page.page_idx + 1}",
1432
+ "title": f"image; bbox 0 0 {width} {height}; ppageno 0",
1433
+ },
1434
+ )
1435
+ # iterate over the predictions and create the XML elements line by line with the attributes
1436
+ for class_name, predictions in page.predictions.items():
1437
+ ordered = predictions_in_reading_order(page, predictions, direction) if reading_order else predictions
1438
+ for prediction in ordered:
1439
+ if len(prediction.geometry) != 2:
1440
+ raise TypeError("XML export is only available for straight bounding boxes for now.")
1441
+ prediction_bbox = _hocr_bbox(prediction.geometry, width, height) # type: ignore[arg-type]
1442
+ x_size, x_fsize = _hocr_text_size(prediction.geometry, height, dpi) # type: ignore[arg-type]
1443
+ prediction_div = SubElement(
1444
+ page_div,
1445
+ "div",
1446
+ attrib={
1447
+ "class": "ocr_carea",
1448
+ "id": f"{class_name}_prediction_{prediction_count}",
1449
+ "title": prediction_bbox,
1450
+ },
1451
+ )
1452
+ # NOTE: ocr_par, ocr_line and ocrx_word are the same because the KIE predictions contain only words
1453
+ # This is a workaround to make it PDF/A compatible
1454
+ par_div = SubElement(
1455
+ prediction_div,
1456
+ "p",
1457
+ attrib={
1458
+ "class": "ocr_par",
1459
+ "id": f"{class_name}_par_{prediction_count}",
1460
+ "title": prediction_bbox,
1461
+ },
1462
+ )
1463
+ line_span = SubElement(
1464
+ par_div,
1465
+ "span",
1466
+ attrib={
1467
+ "class": "ocr_line",
1468
+ "id": f"{class_name}_line_{prediction_count}",
1469
+ "title": (
1470
+ f"{prediction_bbox}; baseline 0 0; x_size {x_size}; x_fsize {x_fsize}; "
1471
+ "x_descenders 0; x_ascenders 0"
1472
+ ),
1473
+ },
1474
+ )
1475
+ word_div = SubElement(
1476
+ line_span,
1477
+ "span",
1478
+ attrib={
1479
+ "class": "ocrx_word",
1480
+ "id": f"{class_name}_word_{prediction_count}",
1481
+ "title": f"{prediction_bbox}; x_wconf {int(round(prediction.confidence * 100))}",
1482
+ },
1483
+ )
1484
+ word_div.text = prediction.value
1485
+ prediction_count += 1
1486
+ return ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr)
1487
+
1488
+ def export_document(self, document: Any, **kwargs: Any) -> list[tuple[bytes, ET.ElementTree]]:
1489
+ """Export a document as a list of hOCR pages.
1490
+
1491
+ Args:
1492
+ document: the document to export
1493
+ **kwargs: additional keyword arguments passed to the page export
1494
+
1495
+ Returns:
1496
+ list of tuple of (bytes, ElementTree), one per page
1497
+ """
1498
+ from doctr.io.elements import KIEPage
1499
+
1500
+ return [
1501
+ self.export_kie_page(page, **kwargs) if isinstance(page, KIEPage) else self.export_page(page, **kwargs)
1502
+ for page in document.pages
1503
+ ]
1504
+
1505
+
1506
+ class PageExportsMixin:
1507
+ """Export functionality of a :class:`~doctr.io.elements.Page`"""
1508
+
1509
+ if TYPE_CHECKING: # structural attributes provided by the element class
1510
+ page: np.ndarray
1511
+ blocks: list["Block"]
1512
+ page_idx: int
1513
+ dimensions: tuple[int, int]
1514
+ orientation: dict[str, Any]
1515
+ language: dict[str, Any]
1516
+ layout: list[Any]
1517
+ tables: list["Table"]
1518
+ formulas: list["Formula"]
1519
+
1520
+ def render(self, block_break: str = "\n\n", direction: str = "auto", include_furniture: bool = True) -> str:
1521
+ """Renders the full text of the page, with its content sorted in reading order.
1522
+
1523
+ Args:
1524
+ block_break: the string inserted between two blocks
1525
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1526
+ include_furniture: whether page headers, page footers and footnotes should be included
1527
+
1528
+ Returns:
1529
+ the text of the page
1530
+ """
1531
+ return TextExporter().export_page(
1532
+ cast("Page", self), direction=direction, include_furniture=include_furniture, block_break=block_break
1533
+ )
1534
+
1535
+ def export(self, reading_order: bool = True) -> dict[str, Any]:
1536
+ """Export the page into a nested dict, with its content sorted in reading order.
1537
+
1538
+ Args:
1539
+ reading_order: whether the blocks should be linearized in reading order, exactly like the
1540
+ Markdown / HTML / AsciiDoc / hOCR exports. Pass False to serialize `page.blocks` as stored.
1541
+
1542
+ Returns:
1543
+ a JSON-serializable dict
1544
+ """
1545
+ from doctr.io.elements import Block, Element
1546
+
1547
+ export_dict = Element.export(cast("Element", self))
1548
+ if reading_order:
1549
+ # Tables, formulas and layout regions have their own export keys
1550
+ blocks = [item for item in page_reading_order(cast("Page", self))[0] if isinstance(item, Block)]
1551
+ if blocks: # an empty linearization (no line on the page) leaves the stored blocks untouched
1552
+ export_dict["blocks"] = [block.export() for block in blocks]
1553
+ return export_dict
1554
+
1555
+ def export_as_xml(
1556
+ self,
1557
+ file_title: str = "docTR - XML export (hOCR)",
1558
+ direction: str = "auto",
1559
+ reading_order: bool = True,
1560
+ dpi: int = 72,
1561
+ ) -> tuple[bytes, ET.ElementTree]:
1562
+ """Export the page as XML (hOCR-format), with its content sorted in reading order
1563
+ convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
1564
+
1565
+ Args:
1566
+ file_title: the title of the XML file
1567
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1568
+ reading_order: whether the content should be linearized in reading order
1569
+ dpi: the page resolution in dots per inch, used to estimate font sizes (`x_size`, `x_fsize`)
1570
+
1571
+ Returns:
1572
+ a tuple of the XML byte string, and its ElementTree
1573
+ """
1574
+ return XMLExporter().export_page(
1575
+ cast("Page", self), file_title=file_title, direction=direction, reading_order=reading_order, dpi=dpi
1576
+ )
1577
+
1578
+ def items_in_reading_order(
1579
+ self, direction: str = "auto", include_figures: bool = False
1580
+ ) -> list["Block | Table | Formula | LayoutElement"]:
1581
+ """Return the content of the page (blocks, tables, formulas and optionally figures) sorted in reading order.
1582
+
1583
+ Args:
1584
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1585
+ include_figures: whether to return the figure regions too
1586
+
1587
+ Returns:
1588
+ list of blocks, tables, formulas and, if requested, figures in reading order
1589
+ """
1590
+ return page_reading_order(cast("Page", self), direction, include_figures=include_figures)[0]
1591
+
1592
+ def export_as_markdown(
1593
+ self,
1594
+ direction: str = "auto",
1595
+ escape: bool = True,
1596
+ include_furniture: bool = True,
1597
+ images: "str | FigureEncoder | None" = "placeholder",
1598
+ ) -> str:
1599
+ """Export the page as Markdown, with its content sorted in reading order.
1600
+
1601
+ Args:
1602
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1603
+ escape: whether the characters carrying a structural meaning in Markdown should be escaped
1604
+ include_furniture: whether page headers, page footers and footnotes should be included
1605
+ images: how to render the figures: 'none', 'placeholder', 'embedded', or a
1606
+ :class:`~doctr.io.FigureEncoder` (required for 'referenced')
1607
+
1608
+ Returns:
1609
+ a Markdown string
1610
+ """
1611
+ return MarkdownExporter().export_page(
1612
+ cast("Page", self),
1613
+ direction=direction,
1614
+ escape=escape,
1615
+ include_furniture=include_furniture,
1616
+ images=images,
1617
+ )
1618
+
1619
+ def export_as_asciidoc(
1620
+ self,
1621
+ direction: str = "auto",
1622
+ escape: bool = True,
1623
+ include_furniture: bool = True,
1624
+ images: "str | FigureEncoder | None" = "placeholder",
1625
+ ) -> str:
1626
+ """Export the page as AsciiDoc, with its content sorted in reading order.
1627
+
1628
+ Args:
1629
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1630
+ escape: whether the characters and line markers carrying a structural meaning in AsciiDoc should
1631
+ be escaped
1632
+ include_furniture: whether page headers, page footers and footnotes should be included
1633
+ images: how to render the figures: 'none', 'placeholder', 'embedded', or a
1634
+ :class:`~doctr.io.FigureEncoder` (required for 'referenced')
1635
+
1636
+ Returns:
1637
+ an AsciiDoc string
1638
+ """
1639
+ return AsciiDocExporter().export_page(
1640
+ cast("Page", self),
1641
+ direction=direction,
1642
+ escape=escape,
1643
+ include_furniture=include_furniture,
1644
+ images=images,
1645
+ )
1646
+
1647
+ def export_as_html(
1648
+ self,
1649
+ direction: str = "auto",
1650
+ include_furniture: bool = True,
1651
+ images: "str | FigureEncoder | None" = "placeholder",
1652
+ ) -> str:
1653
+ """Export the page as semantic HTML, with its content sorted in reading order.
1654
+
1655
+ Args:
1656
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1657
+ include_furniture: whether page headers, page footers and footnotes should be included
1658
+ images: how to render the figures: 'none', 'placeholder', 'embedded', or a
1659
+ :class:`~doctr.io.FigureEncoder` (required for 'referenced')
1660
+
1661
+ Returns:
1662
+ an HTML string
1663
+ """
1664
+ return HTMLExporter().export_page(
1665
+ cast("Page", self), direction=direction, include_furniture=include_furniture, images=images
1666
+ )
1667
+
1668
+ def export_as(self, format: str, **kwargs: Any) -> Any:
1669
+ """Export the page in the requested format.
1670
+
1671
+ Args:
1672
+ format: one of 'markdown'/'md', 'asciidoc'/'adoc', 'html', 'text'/'txt', 'json'/'dict',
1673
+ 'xml'/'hocr'
1674
+ **kwargs: additional keyword arguments passed to the format-specific export method
1675
+
1676
+ Returns:
1677
+ the exported page
1678
+ """
1679
+ exporters: dict[str, Any] = {
1680
+ "markdown": self.export_as_markdown,
1681
+ "md": self.export_as_markdown,
1682
+ "asciidoc": self.export_as_asciidoc,
1683
+ "adoc": self.export_as_asciidoc,
1684
+ "html": self.export_as_html,
1685
+ "text": self.render,
1686
+ "txt": self.render,
1687
+ "json": self.export,
1688
+ "dict": self.export,
1689
+ "xml": self.export_as_xml,
1690
+ "hocr": self.export_as_xml,
1691
+ }
1692
+ return _export_as(exporters, format, **kwargs)
1693
+
1694
+
1695
+ class KIEPageExportsMixin:
1696
+ """Export functionality of a :class:`~doctr.io.elements.KIEPage`"""
1697
+
1698
+ if TYPE_CHECKING: # structural attributes provided by the element class
1699
+ page: np.ndarray
1700
+ predictions: dict[str, list[Any]]
1701
+ page_idx: int
1702
+ dimensions: tuple[int, int]
1703
+ orientation: dict[str, Any]
1704
+ language: dict[str, Any]
1705
+
1706
+ def export(self, reading_order: bool = True) -> dict[str, Any]:
1707
+ """Export the KIE page into a nested dict, with the predictions of each class in reading order.
1708
+
1709
+ Args:
1710
+ reading_order: whether the predictions of each class should be sorted in reading order
1711
+
1712
+ Returns:
1713
+ a JSON-serializable dict
1714
+ """
1715
+ from doctr.io.elements import Element
1716
+
1717
+ export_dict = Element.export(cast("Element", self))
1718
+ if reading_order:
1719
+ export_dict["predictions"] = {
1720
+ class_name: [
1721
+ prediction.export()
1722
+ for prediction in predictions_in_reading_order(cast("KIEPage", self), predictions)
1723
+ ]
1724
+ for class_name, predictions in self.predictions.items()
1725
+ }
1726
+ return export_dict
1727
+
1728
+ def render(self, prediction_break: str = "\n\n", direction: str = "auto") -> str:
1729
+ """Renders the full text of the page, with the predictions of each class sorted in reading order.
1730
+
1731
+ Args:
1732
+ prediction_break: the string inserted between two predictions
1733
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1734
+
1735
+ Returns:
1736
+ the text of the page, one section per detection class with its predictions in reading order
1737
+ """
1738
+ parts: list[str] = []
1739
+ for class_name, predictions in self.predictions.items():
1740
+ parts.extend(
1741
+ f"{class_name}: {prediction.render()}"
1742
+ for prediction in predictions_in_reading_order(cast("KIEPage", self), predictions, direction)
1743
+ )
1744
+ return prediction_break.join(parts)
1745
+
1746
+ def export_as_xml(
1747
+ self,
1748
+ file_title: str = "docTR - XML export (hOCR)",
1749
+ direction: str = "auto",
1750
+ reading_order: bool = True,
1751
+ dpi: int = 72,
1752
+ ) -> tuple[bytes, ET.ElementTree]:
1753
+ """Export the page as XML (hOCR-format), with the predictions of each class in reading order
1754
+ convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
1755
+
1756
+ Args:
1757
+ file_title: the title of the XML file
1758
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1759
+ reading_order: whether the predictions of each class should be sorted in reading order
1760
+ dpi: the page resolution in dots per inch, used to estimate font sizes (`x_size`, `x_fsize`)
1761
+
1762
+ Returns:
1763
+ a tuple of the XML byte string, and its ElementTree
1764
+ """
1765
+ return XMLExporter().export_kie_page(
1766
+ cast("KIEPage", self), file_title=file_title, direction=direction, reading_order=reading_order, dpi=dpi
1767
+ )
1768
+
1769
+ def export_as_markdown(self, direction: str = "auto", escape: bool = True) -> str:
1770
+ """Export the KIE page as Markdown, with the predictions of each class sorted in reading order.
1771
+
1772
+ Args:
1773
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1774
+ escape: whether the characters carrying a structural meaning in Markdown should be escaped
1775
+
1776
+ Returns:
1777
+ a Markdown string with one section per detection class
1778
+ """
1779
+ return MarkdownExporter().export_kie_page(cast("KIEPage", self), direction=direction, escape=escape)
1780
+
1781
+ def export_as_asciidoc(self, direction: str = "auto", escape: bool = True) -> str:
1782
+ """Export the KIE page as AsciiDoc, with the predictions of each class sorted in reading order.
1783
+
1784
+ Args:
1785
+ direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
1786
+ escape: whether the characters and line markers carrying a structural meaning in AsciiDoc should
1787
+ be escaped
1788
+
1789
+ Returns:
1790
+ an AsciiDoc string with one section per detection class
1791
+ """
1792
+ return AsciiDocExporter().export_kie_page(cast("KIEPage", self), direction=direction, escape=escape)
1793
+
1794
+ def export_as_html(self, direction: str = "auto") -> str:
1795
+ """Export the KIE page as semantic HTML, with the predictions of each class sorted in reading order"""
1796
+ return HTMLExporter().export_kie_page(cast("KIEPage", self), direction=direction)
1797
+
1798
+ def export_as(self, format: str, **kwargs: Any) -> Any:
1799
+ """Export the KIE page in the requested format ('markdown'/'md', 'asciidoc'/'adoc', 'html',
1800
+ 'text'/'txt', 'json'/'dict', 'xml'/'hocr')."""
1801
+ exporters: dict[str, Any] = {
1802
+ "markdown": self.export_as_markdown,
1803
+ "md": self.export_as_markdown,
1804
+ "asciidoc": self.export_as_asciidoc,
1805
+ "adoc": self.export_as_asciidoc,
1806
+ "html": self.export_as_html,
1807
+ "text": self.render,
1808
+ "txt": self.render,
1809
+ "json": self.export,
1810
+ "dict": self.export,
1811
+ "xml": self.export_as_xml,
1812
+ "hocr": self.export_as_xml,
1813
+ }
1814
+ return _export_as(exporters, format, **kwargs)
1815
+
1816
+
1817
+ class DocumentExportsMixin:
1818
+ """Export functionality of a :class:`~doctr.io.elements.Document` (also used by `KIEDocument`)"""
1819
+
1820
+ if TYPE_CHECKING: # structural attributes provided by the element class
1821
+ pages: list[Any]
1822
+ _exported_keys: list[str]
1823
+
1824
+ def render(self, page_break: str = "\n\n\n\n", **kwargs: Any) -> str:
1825
+ """Renders the full text of the document, with the content of each page sorted in reading order.
1826
+
1827
+ Args:
1828
+ page_break: the string inserted between two pages
1829
+ **kwargs: additional keyword arguments passed to the `Page.render` / `KIEPage.render` method
1830
+
1831
+ Returns:
1832
+ the text of the document
1833
+ """
1834
+ return page_break.join(page.render(**kwargs) for page in self.pages)
1835
+
1836
+ def export(self, reading_order: bool = True) -> dict[str, Any]:
1837
+ """Export the document into a nested dict, with the content of each page sorted in reading order.
1838
+
1839
+ Args:
1840
+ reading_order: whether the content of each page should be linearized in reading order
1841
+
1842
+ Returns:
1843
+ a JSON-serializable dict
1844
+ """
1845
+ export_dict: dict[str, Any] = {key: to_json_safe(getattr(self, key)) for key in self._exported_keys}
1846
+ export_dict["pages"] = [page.export(reading_order=reading_order) for page in self.pages]
1847
+ return export_dict
1848
+
1849
+ def export_as_xml(self, **kwargs: Any) -> list[tuple[bytes, ET.ElementTree]]:
1850
+ """Export the document as XML (hOCR-format)
1851
+
1852
+ Args:
1853
+ **kwargs: additional keyword arguments passed to the XML page export
1854
+
1855
+ Returns:
1856
+ list of tuple of (bytes, ElementTree)
1857
+ """
1858
+ return XMLExporter().export_document(self, **kwargs)
1859
+
1860
+ def export_as_markdown(self, page_break: str = "\n\n---\n\n", **kwargs: Any) -> str:
1861
+ """Export the document as Markdown, with the content of each page sorted in reading order.
1862
+
1863
+ Args:
1864
+ page_break: the string inserted between two pages (a thematic break by default)
1865
+ **kwargs: additional keyword arguments passed to the `Page.export_as_markdown` method (e.g. `images`,
1866
+ not supported by KIE pages)
1867
+
1868
+ Returns:
1869
+ a Markdown string
1870
+ """
1871
+ return page_break.join(page.export_as_markdown(**kwargs) for page in self.pages)
1872
+
1873
+ def export_as_asciidoc(self, page_break: str = "\n\n<<<\n\n", **kwargs: Any) -> str:
1874
+ """Export the document as AsciiDoc, with the content of each page sorted in reading order.
1875
+
1876
+ Args:
1877
+ page_break: the string inserted between two pages (an AsciiDoc page break by default)
1878
+ **kwargs: additional keyword arguments passed to the `Page.export_as_asciidoc` method (e.g. `images`,
1879
+ not supported by KIE pages)
1880
+
1881
+ Returns:
1882
+ an AsciiDoc string
1883
+ """
1884
+ return page_break.join(page.export_as_asciidoc(**kwargs) for page in self.pages)
1885
+
1886
+ def export_as_html(self, page_break: str = "<hr>", **kwargs: Any) -> str:
1887
+ """Export the document as semantic HTML, with the content of each page sorted in reading order.
1888
+
1889
+ Args:
1890
+ page_break: the HTML snippet inserted between two pages
1891
+ **kwargs: additional keyword arguments passed to the page export (e.g. `images`, not supported by
1892
+ KIE pages)
1893
+
1894
+ Returns:
1895
+ an HTML string
1896
+ """
1897
+ return page_break.join(page.export_as_html(**kwargs) for page in self.pages)
1898
+
1899
+ def export_as(self, format: str, **kwargs: Any) -> Any:
1900
+ """Export the document in the requested format ('markdown'/'md', 'asciidoc'/'adoc', 'html',
1901
+ 'text'/'txt', 'json'/'dict', 'xml'/'hocr')."""
1902
+ exporters: dict[str, Any] = {
1903
+ "markdown": self.export_as_markdown,
1904
+ "md": self.export_as_markdown,
1905
+ "asciidoc": self.export_as_asciidoc,
1906
+ "adoc": self.export_as_asciidoc,
1907
+ "html": self.export_as_html,
1908
+ "text": self.render,
1909
+ "txt": self.render,
1910
+ "json": self.export,
1911
+ "dict": self.export,
1912
+ "xml": self.export_as_xml,
1913
+ "hocr": self.export_as_xml,
1914
+ }
1915
+ return _export_as(exporters, format, **kwargs)