python-doctr 1.1.0__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.
- doctr/cli/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/io/exporters.py
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
|
+
import re
|
|
6
7
|
from html import escape as _html_escape
|
|
7
|
-
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
|
8
|
+
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, cast
|
|
8
9
|
from xml.etree import ElementTree as ET
|
|
9
10
|
from xml.etree.ElementTree import Element as ETElement
|
|
10
11
|
from xml.etree.ElementTree import SubElement
|
|
@@ -12,10 +13,11 @@ from xml.etree.ElementTree import SubElement
|
|
|
12
13
|
import numpy as np
|
|
13
14
|
|
|
14
15
|
import doctr
|
|
16
|
+
from doctr.io.figures import FigureEncoder, is_picture_label, picture_regions
|
|
15
17
|
from doctr.utils.common_types import BoundingBox
|
|
16
18
|
|
|
17
19
|
if TYPE_CHECKING: # pragma: no cover
|
|
18
|
-
from doctr.io.elements import Block, KIEPage, Line, Page, Table
|
|
20
|
+
from doctr.io.elements import Block, Formula, KIEPage, LayoutElement, Line, Page, Table
|
|
19
21
|
|
|
20
22
|
__all__ = [
|
|
21
23
|
"AsciiDocExporter",
|
|
@@ -64,42 +66,79 @@ _LIST_LABELS = {"list_item"}
|
|
|
64
66
|
# Characters / line markers that carry a structural meaning and are escaped to preserve the raw OCR text
|
|
65
67
|
_MD_SPECIAL_CHARS = "\\`*_[]|#<>"
|
|
66
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|$)")
|
|
67
71
|
_ADOC_SPECIAL_CHARS = "\\`*_#^~|+{}<>"
|
|
68
72
|
_ADOC_LINE_MARKERS = "=*.-/+"
|
|
69
73
|
|
|
70
74
|
|
|
71
|
-
def _covering_region_indices(
|
|
72
|
-
|
|
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)
|
|
73
82
|
|
|
74
|
-
|
|
75
|
-
returns -1 when no region covers the element by at least `min_coverage`. The geometries are expected to
|
|
76
|
-
be in the same (upright) frame.
|
|
83
|
+
Same criterion as :func:`doctr.models.reading_order.assign_layout_labels`, on geometries in the same frame.
|
|
77
84
|
"""
|
|
78
|
-
from doctr.models.reading_order.base import _to_boxes
|
|
85
|
+
from doctr.models.reading_order.base import _covering_regions, _to_boxes
|
|
79
86
|
|
|
80
87
|
if len(region_geoms) == 0 or len(geoms) == 0:
|
|
81
88
|
return [-1] * len(geoms)
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
|
90
127
|
|
|
91
128
|
|
|
92
129
|
def _reading_order_signature(page: "Page", direction: str) -> tuple[Any, ...]:
|
|
93
|
-
"""
|
|
130
|
+
"""Return a cheap fingerprint of a page, used to invalidate the reading-order cache
|
|
94
131
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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.
|
|
98
135
|
"""
|
|
99
136
|
return (
|
|
100
137
|
direction,
|
|
101
138
|
tuple((id(block), len(block.lines)) for block in page.blocks),
|
|
102
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 ()),
|
|
103
142
|
)
|
|
104
143
|
|
|
105
144
|
|
|
@@ -111,109 +150,232 @@ def _store_reading_order(page: "Page", signature: tuple[Any, ...], result: tuple
|
|
|
111
150
|
pass
|
|
112
151
|
|
|
113
152
|
|
|
114
|
-
def page_reading_order(
|
|
115
|
-
""
|
|
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
|
|
116
157
|
|
|
117
|
-
The result is
|
|
118
|
-
|
|
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.
|
|
119
160
|
|
|
120
161
|
Args:
|
|
121
162
|
page: the page to linearize
|
|
122
163
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
164
|
+
include_figures: whether to return the figure regions too
|
|
123
165
|
|
|
124
166
|
Returns:
|
|
125
|
-
|
|
126
|
-
effective reading direction
|
|
167
|
+
the ordered items, their layout label (None without layout) and the effective reading direction
|
|
127
168
|
"""
|
|
128
|
-
from doctr.
|
|
129
|
-
from doctr.models.reading_order import (
|
|
130
|
-
ReadingOrderPredictor,
|
|
131
|
-
assign_layout_labels,
|
|
132
|
-
deskew_reading_geometries,
|
|
133
|
-
normalize_layout_label,
|
|
134
|
-
resolve_reading_segments,
|
|
135
|
-
)
|
|
169
|
+
from doctr.models.reading_order import ReadingOrderPredictor, deskew_reading_geometries, resolve_reading_segments
|
|
136
170
|
|
|
137
171
|
signature = _reading_order_signature(page, direction)
|
|
138
172
|
cached = getattr(page, "_reading_order_cache", None)
|
|
139
173
|
if cached is not None and cached[0] == signature:
|
|
140
|
-
|
|
141
|
-
return list(
|
|
174
|
+
cached_items, cached_labels, resolved = cached[1]
|
|
175
|
+
return _select_items(list(cached_items), list(cached_labels), resolved, include_figures)
|
|
142
176
|
|
|
143
|
-
|
|
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]
|
|
144
179
|
language = page.language.get("value") if isinstance(page.language, dict) else None
|
|
145
|
-
direction = ReadingOrderPredictor(direction=direction).resolve_direction(
|
|
146
|
-
|
|
147
|
-
|
|
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)
|
|
148
210
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
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]
|
|
161
231
|
)
|
|
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
|
-
|
|
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):
|
|
188
304
|
items.append(first)
|
|
189
|
-
labels.append("Table")
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
if open_list_region is not None and region == open_list_region and region != -1:
|
|
198
|
-
merged = [*items[-1].lines, elements[idx]]
|
|
199
|
-
items[-1] = Block(lines=merged, artefacts=[*items[-1].artefacts, *_claim_artefacts([merged[-1]])])
|
|
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)
|
|
200
313
|
else:
|
|
201
|
-
items.append(
|
|
202
|
-
labels.append(
|
|
203
|
-
|
|
314
|
+
items.append(artefacts.block([elements[idx]]))
|
|
315
|
+
labels.append(label)
|
|
316
|
+
list_region = region
|
|
204
317
|
else:
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
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]
|
|
212
352
|
last_block = next((item for item in reversed(items) if isinstance(item, Block)), None)
|
|
213
|
-
if last_block is not None:
|
|
353
|
+
if leftover and last_block is not None:
|
|
214
354
|
last_block.artefacts = [*last_block.artefacts, *leftover]
|
|
215
|
-
|
|
216
|
-
|
|
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
|
|
217
379
|
|
|
218
380
|
|
|
219
381
|
def _line_render_direction(line: "Line", page_direction: str, auto: bool) -> str:
|
|
@@ -275,18 +437,167 @@ def predictions_in_reading_order(page: "KIEPage", predictions: list[Any], direct
|
|
|
275
437
|
return [predictions[idx] for idx in order]
|
|
276
438
|
|
|
277
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
|
+
|
|
278
587
|
class _PageTextExporter:
|
|
279
|
-
"""Shared logic of the reading-order-aware text exporters
|
|
588
|
+
"""Shared logic of the reading-order-aware text exporters
|
|
280
589
|
|
|
281
|
-
Subclasses define the format specifics:
|
|
282
|
-
prefix, character escaping, line finalization (neutralizing markers a line must not start with) and the
|
|
283
|
-
table rendering.
|
|
590
|
+
Subclasses define the format specifics: headings, bullets, escaping, line finalization, tables and figures.
|
|
284
591
|
"""
|
|
285
592
|
|
|
286
593
|
headings: ClassVar[dict[str, str]] = {}
|
|
287
594
|
bullet: ClassVar[str] = "- "
|
|
288
595
|
block_break: ClassVar[str] = "\n\n"
|
|
289
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] = ""
|
|
290
601
|
|
|
291
602
|
def escape_text(self, text: str) -> str:
|
|
292
603
|
"""Escape the characters carrying a structural meaning in the target format"""
|
|
@@ -300,6 +611,40 @@ class _PageTextExporter:
|
|
|
300
611
|
"""Render a recognized table in the target format"""
|
|
301
612
|
raise NotImplementedError
|
|
302
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
|
+
|
|
303
648
|
def class_header(self, class_name: str, escape: bool = True) -> str:
|
|
304
649
|
"""Render the header of a detection class in a KIE export"""
|
|
305
650
|
raise NotImplementedError
|
|
@@ -309,6 +654,71 @@ class _PageTextExporter:
|
|
|
309
654
|
text = " ".join(word.render() for word in ordered_line_words(line, direction))
|
|
310
655
|
return self.escape_text(text) if escape else text
|
|
311
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
|
+
|
|
312
722
|
def export_page(
|
|
313
723
|
self,
|
|
314
724
|
page: "Page",
|
|
@@ -316,6 +726,7 @@ class _PageTextExporter:
|
|
|
316
726
|
escape: bool = True,
|
|
317
727
|
include_furniture: bool = True,
|
|
318
728
|
block_break: str | None = None,
|
|
729
|
+
images: "str | FigureEncoder | None" = "placeholder",
|
|
319
730
|
) -> str:
|
|
320
731
|
"""Export a page, with its content sorted in reading order.
|
|
321
732
|
|
|
@@ -325,49 +736,67 @@ class _PageTextExporter:
|
|
|
325
736
|
escape: whether the characters or markers carrying a structural meaning should be neutralized
|
|
326
737
|
include_furniture: whether page headers, page footers and footnotes should be included
|
|
327
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')
|
|
328
741
|
|
|
329
742
|
Returns:
|
|
330
743
|
the exported page as a string
|
|
331
744
|
"""
|
|
332
|
-
from doctr.io.elements import Table
|
|
745
|
+
from doctr.io.elements import Formula, LayoutElement, Table
|
|
333
746
|
from doctr.models.reading_order import layout_label_role, normalize_layout_label
|
|
747
|
+
from doctr.models.reading_order.base import _FURNITURE_ROLES
|
|
334
748
|
|
|
335
749
|
auto = direction == "auto"
|
|
336
|
-
|
|
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
|
+
)
|
|
337
755
|
parts: list[str] = []
|
|
338
756
|
list_group: list[str] = []
|
|
339
757
|
|
|
340
758
|
def _flush_list() -> None:
|
|
341
759
|
if list_group:
|
|
342
|
-
parts.append(
|
|
760
|
+
parts.append(self.render_list(list_group))
|
|
343
761
|
list_group.clear()
|
|
344
762
|
|
|
345
|
-
for item, label in zip(items, labels):
|
|
346
|
-
if not include_furniture and layout_label_role(label) in
|
|
763
|
+
for index, (item, label) in enumerate(zip(items, labels)):
|
|
764
|
+
if not include_furniture and layout_label_role(label) in _FURNITURE_ROLES:
|
|
347
765
|
continue
|
|
348
|
-
if isinstance(item,
|
|
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)):
|
|
349
774
|
_flush_list()
|
|
350
|
-
rendered =
|
|
775
|
+
rendered = (
|
|
776
|
+
self.render_table(item, escape=escape)
|
|
777
|
+
if isinstance(item, Table)
|
|
778
|
+
else self.render_formula(item, escape=escape)
|
|
779
|
+
)
|
|
351
780
|
if rendered:
|
|
352
781
|
parts.append(rendered)
|
|
353
782
|
continue
|
|
354
|
-
item_lines =
|
|
355
|
-
self._line_text(line, _line_render_direction(line, direction, auto), escape) for line in item.lines
|
|
356
|
-
]
|
|
357
|
-
item_lines = [line for line in item_lines if line.strip()]
|
|
783
|
+
item_lines = self._block_lines(item, direction, escape, auto)
|
|
358
784
|
if len(item_lines) == 0:
|
|
359
785
|
continue
|
|
360
786
|
norm_label = normalize_layout_label(label)
|
|
361
|
-
if
|
|
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:
|
|
362
792
|
_flush_list()
|
|
363
|
-
parts.append(self.
|
|
793
|
+
parts.append(self.render_heading(norm_label, item_lines, escape))
|
|
364
794
|
elif norm_label in _LIST_LABELS:
|
|
365
795
|
# A list item (possibly wrapped over several lines) renders as a single bullet
|
|
366
|
-
|
|
367
|
-
list_group.append(self.bullet + (self.finalize_line(text) if escape else text))
|
|
796
|
+
list_group.append(self.render_list_item(item_lines, escape))
|
|
368
797
|
else:
|
|
369
798
|
_flush_list()
|
|
370
|
-
parts.append(
|
|
799
|
+
parts.append(self.render_paragraph(item_lines, escape))
|
|
371
800
|
_flush_list()
|
|
372
801
|
return (self.block_break if block_break is None else block_break).join(parts)
|
|
373
802
|
|
|
@@ -443,15 +872,18 @@ class MarkdownExporter(_PageTextExporter):
|
|
|
443
872
|
headings: ClassVar[dict[str, str]] = {"title": "# ", "section_header": "## "}
|
|
444
873
|
bullet: ClassVar[str] = "- "
|
|
445
874
|
page_break: ClassVar[str] = "\n\n---\n\n"
|
|
875
|
+
supports_figures: ClassVar[bool] = True
|
|
876
|
+
figure_placeholder: ClassVar[str] = "<!-- image -->"
|
|
446
877
|
|
|
447
878
|
def escape_text(self, text: str) -> str:
|
|
448
879
|
return "".join(f"\\{char}" if char in _MD_SPECIAL_CHARS else char for char in text)
|
|
449
880
|
|
|
450
881
|
def finalize_line(self, line: str) -> str:
|
|
451
882
|
stripped = line.lstrip()
|
|
452
|
-
if stripped and
|
|
883
|
+
if stripped and stripped[0] in _MD_LINE_MARKERS:
|
|
453
884
|
return f"\\{line}" if line[0] != "\\" else line
|
|
454
|
-
|
|
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)
|
|
455
887
|
|
|
456
888
|
def render_table(self, table: "Table", escape: bool = True) -> str:
|
|
457
889
|
"""Render a table as a GitHub-flavored Markdown table (first row used as header)"""
|
|
@@ -467,6 +899,25 @@ class MarkdownExporter(_PageTextExporter):
|
|
|
467
899
|
separator = "| " + " | ".join("---" for _ in grid[0]) + " |"
|
|
468
900
|
return "\n".join([rows[0], separator, *rows[1:]])
|
|
469
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""
|
|
917
|
+
if not caption:
|
|
918
|
+
return image
|
|
919
|
+
return f"{image}\n\n*{self.escape_text(caption) if escape else caption}*"
|
|
920
|
+
|
|
470
921
|
def class_header(self, class_name: str, escape: bool = True) -> str:
|
|
471
922
|
return f"**{self.escape_text(class_name) if escape else class_name}**"
|
|
472
923
|
|
|
@@ -481,6 +932,8 @@ class AsciiDocExporter(_PageTextExporter):
|
|
|
481
932
|
headings: ClassVar[dict[str, str]] = {"title": "== ", "section_header": "=== "}
|
|
482
933
|
bullet: ClassVar[str] = "* "
|
|
483
934
|
page_break: ClassVar[str] = "\n\n<<<\n\n"
|
|
935
|
+
supports_figures: ClassVar[bool] = True
|
|
936
|
+
figure_placeholder: ClassVar[str] = "// image"
|
|
484
937
|
|
|
485
938
|
def escape_text(self, text: str) -> str:
|
|
486
939
|
return "".join(f"\\{char}" if char in _ADOC_SPECIAL_CHARS else char for char in text)
|
|
@@ -505,6 +958,26 @@ class AsciiDocExporter(_PageTextExporter):
|
|
|
505
958
|
|
|
506
959
|
return "\n".join(["|===", _row(grid[0]), "", *[_row(row) for row in grid[1:]], "|==="])
|
|
507
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
|
+
|
|
508
981
|
def class_header(self, class_name: str, escape: bool = True) -> str:
|
|
509
982
|
return f"*{self.escape_text(class_name) if escape else class_name}*"
|
|
510
983
|
|
|
@@ -512,7 +985,8 @@ class AsciiDocExporter(_PageTextExporter):
|
|
|
512
985
|
class HTMLExporter(_PageTextExporter):
|
|
513
986
|
"""Export OCR results to semantic HTML, with the content sorted in reading order.
|
|
514
987
|
|
|
515
|
-
Headings map to `<h1>`/`<h2>`, list items to `<ul><li>`, recognized tables to `<table
|
|
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
|
|
516
990
|
paragraphs to `<p>` (with `<br>` between the visual lines of a paragraph). The output is a
|
|
517
991
|
fragment, not a full document: it carries no doctype, `<html>` or charset declaration.
|
|
518
992
|
|
|
@@ -528,72 +1002,89 @@ class HTMLExporter(_PageTextExporter):
|
|
|
528
1002
|
headings: ClassVar[dict[str, str]] = {"title": "h1", "section_header": "h2"}
|
|
529
1003
|
block_break: ClassVar[str] = "\n"
|
|
530
1004
|
page_break: ClassVar[str] = "\n<hr>\n"
|
|
1005
|
+
supports_figures: ClassVar[bool] = True
|
|
1006
|
+
figure_placeholder: ClassVar[str] = "<!-- image -->"
|
|
531
1007
|
|
|
532
1008
|
def escape_text(self, text: str) -> str:
|
|
533
1009
|
return _html_escape(text, quote=False)
|
|
534
1010
|
|
|
535
|
-
def
|
|
536
|
-
self
|
|
537
|
-
|
|
538
|
-
direction: str = "auto",
|
|
539
|
-
escape: bool = True,
|
|
540
|
-
include_furniture: bool = True,
|
|
541
|
-
block_break: str | None = None,
|
|
542
|
-
) -> str:
|
|
543
|
-
from doctr.io.elements import Table
|
|
544
|
-
from doctr.models.reading_order import layout_label_role, normalize_layout_label
|
|
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}>"
|
|
545
1014
|
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
parts: list[str] = []
|
|
549
|
-
list_group: list[str] = []
|
|
1015
|
+
def render_list_item(self, lines: list[str], escape: bool = True) -> str:
|
|
1016
|
+
return f"<li>{' '.join(lines)}</li>"
|
|
550
1017
|
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
parts.append("<ul>\n" + "\n".join(list_group) + "\n</ul>")
|
|
554
|
-
list_group.clear()
|
|
1018
|
+
def render_list(self, items: list[str]) -> str:
|
|
1019
|
+
return "<ul>\n" + "\n".join(items) + "\n</ul>"
|
|
555
1020
|
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
if norm_label in self.headings:
|
|
573
|
-
_flush_list()
|
|
574
|
-
tag = self.headings[norm_label]
|
|
575
|
-
parts.append(f"<{tag}>{' '.join(item_lines)}</{tag}>")
|
|
576
|
-
elif norm_label in _LIST_LABELS:
|
|
577
|
-
list_group.append(f"<li>{' '.join(item_lines)}</li>")
|
|
578
|
-
else:
|
|
579
|
-
_flush_list()
|
|
580
|
-
parts.append("<p>" + "<br>\n".join(item_lines) + "</p>")
|
|
581
|
-
_flush_list()
|
|
582
|
-
return (self.block_break if block_break is None else block_break).join(parts)
|
|
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>'
|
|
583
1037
|
|
|
584
1038
|
def render_table(self, table: "Table", escape: bool = True) -> str:
|
|
585
|
-
"""Render a table as an HTML table (first row used as header)
|
|
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."""
|
|
586
1041
|
grid = table.to_grid()
|
|
587
1042
|
if len(grid) == 0 or len(grid[0]) == 0:
|
|
588
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
|
+
}
|
|
589
1071
|
|
|
590
|
-
def _cell(value: str, tag: str) -> str:
|
|
1072
|
+
def _cell(value: str, tag: str, position: tuple[int, int]) -> str:
|
|
591
1073
|
content = self.escape_text(value) if escape else value
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
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>"
|
|
597
1088
|
|
|
598
1089
|
def export_kie_page(self, page: "KIEPage", direction: str = "auto", escape: bool = True) -> str:
|
|
599
1090
|
parts: list[str] = []
|
|
@@ -640,6 +1131,22 @@ def _hocr_bbox(geometry: BoundingBox, width: int, height: int) -> str:
|
|
|
640
1131
|
)
|
|
641
1132
|
|
|
642
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
|
+
|
|
643
1150
|
class XMLExporter:
|
|
644
1151
|
"""hOCR (XML) exporter for pages, KIE pages and documents.
|
|
645
1152
|
See the hOCR 1.2 specification for the XML convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
@@ -648,7 +1155,7 @@ class XMLExporter:
|
|
|
648
1155
|
>>> xml_bytes, xml_tree = XMLExporter().export_page(page)
|
|
649
1156
|
"""
|
|
650
1157
|
|
|
651
|
-
ocr_capabilities: ClassVar[str] = "ocr_page ocr_carea ocr_par ocr_line ocrx_word"
|
|
1158
|
+
ocr_capabilities: ClassVar[str] = "ocr_page ocr_carea ocr_par ocr_line ocrx_word ocr_photo ocr_math"
|
|
652
1159
|
|
|
653
1160
|
def _new_document(self, file_title: str, language: str) -> tuple[ETElement, ETElement]:
|
|
654
1161
|
"""Create the hOCR root element with its <head>, returning the root and its <body> element."""
|
|
@@ -664,7 +1171,9 @@ class XMLExporter:
|
|
|
664
1171
|
SubElement(head, "meta", attrib={"name": "ocr-capabilities", "content": self.ocr_capabilities})
|
|
665
1172
|
return root, SubElement(root, "body")
|
|
666
1173
|
|
|
667
|
-
def _add_table(
|
|
1174
|
+
def _add_table(
|
|
1175
|
+
self, page_div: ETElement, table: "Table", width: int, height: int, table_count: int, dpi: int = 72
|
|
1176
|
+
) -> int:
|
|
668
1177
|
"""Serialize a recognized table as an hOCR text area, with one `ocr_line` per row.
|
|
669
1178
|
|
|
670
1179
|
Args:
|
|
@@ -673,6 +1182,7 @@ class XMLExporter:
|
|
|
673
1182
|
width: the page width in pixels
|
|
674
1183
|
height: the page height in pixels
|
|
675
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
|
|
676
1186
|
|
|
677
1187
|
Returns:
|
|
678
1188
|
the index of the next table
|
|
@@ -693,14 +1203,19 @@ class XMLExporter:
|
|
|
693
1203
|
cells = sorted(rows[row_idx], key=lambda cell: cell.col_start)
|
|
694
1204
|
xs = [coord for cell in cells for coord in (cell.geometry[0][0], cell.geometry[1][0])]
|
|
695
1205
|
ys = [coord for cell in cells for coord in (cell.geometry[0][1], cell.geometry[1][1])]
|
|
696
|
-
|
|
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)
|
|
697
1209
|
line_span = SubElement(
|
|
698
1210
|
paragraph,
|
|
699
1211
|
"span",
|
|
700
1212
|
attrib={
|
|
701
1213
|
"class": "ocr_line",
|
|
702
1214
|
"id": f"table_{table_count}_row_{row_idx + 1}",
|
|
703
|
-
"title":
|
|
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
|
+
),
|
|
704
1219
|
},
|
|
705
1220
|
)
|
|
706
1221
|
for col_idx, cell in enumerate(cells):
|
|
@@ -718,31 +1233,97 @@ class XMLExporter:
|
|
|
718
1233
|
cell_span.text = cell.value
|
|
719
1234
|
return table_count + 1
|
|
720
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
|
+
|
|
721
1296
|
def export_page(
|
|
722
1297
|
self,
|
|
723
1298
|
page: "Page",
|
|
724
1299
|
file_title: str = "docTR - XML export (hOCR)",
|
|
725
1300
|
direction: str = "auto",
|
|
726
1301
|
reading_order: bool = True,
|
|
1302
|
+
dpi: int = 72,
|
|
727
1303
|
) -> tuple[bytes, ET.ElementTree]:
|
|
728
1304
|
"""Export a page as hOCR XML, with its content sorted in reading order.
|
|
729
1305
|
|
|
1306
|
+
Figures are exported as `ocr_photo` areas, formulas as `ocr_math` elements holding their LaTeX source.
|
|
1307
|
+
|
|
730
1308
|
Args:
|
|
731
1309
|
page: the page to export
|
|
732
1310
|
file_title: the title of the XML file
|
|
733
1311
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
734
1312
|
reading_order: whether the content should be linearized in reading order. Pass False to serialize
|
|
735
|
-
`page.blocks` then `page.
|
|
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`)
|
|
736
1315
|
|
|
737
1316
|
Returns:
|
|
738
1317
|
a tuple of the XML byte string, and its ElementTree
|
|
739
1318
|
"""
|
|
740
|
-
from doctr.io.elements import Table
|
|
1319
|
+
from doctr.io.elements import Formula, LayoutElement, Table
|
|
741
1320
|
|
|
742
1321
|
block_count: int = 1
|
|
743
1322
|
line_count: int = 1
|
|
744
1323
|
word_count: int = 1
|
|
745
1324
|
table_count: int = 1
|
|
1325
|
+
figure_count: int = 1
|
|
1326
|
+
formula_count: int = 1
|
|
746
1327
|
height, width = page.dimensions
|
|
747
1328
|
page_hocr, body = self._new_document(file_title, _resolve_hocr_language(page.language))
|
|
748
1329
|
page_div = SubElement(
|
|
@@ -756,13 +1337,19 @@ class XMLExporter:
|
|
|
756
1337
|
)
|
|
757
1338
|
auto = direction == "auto"
|
|
758
1339
|
if reading_order:
|
|
759
|
-
items, _, direction = page_reading_order(page, direction)
|
|
1340
|
+
items, _, direction = page_reading_order(page, direction, include_figures=True)
|
|
760
1341
|
else:
|
|
761
|
-
items = [*page.blocks, *page.tables]
|
|
1342
|
+
items = [*page.blocks, *page.tables, *page.formulas, *picture_regions(page)]
|
|
762
1343
|
# iterate over the blocks / lines / words and create the XML elements line by line with the attributes
|
|
763
1344
|
for item in items:
|
|
764
1345
|
if isinstance(item, Table):
|
|
765
|
-
table_count = self._add_table(page_div, item, width, height, table_count)
|
|
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)
|
|
766
1353
|
continue
|
|
767
1354
|
block = item
|
|
768
1355
|
if len(block.geometry) != 2:
|
|
@@ -780,7 +1367,9 @@ class XMLExporter:
|
|
|
780
1367
|
)
|
|
781
1368
|
block_count += 1
|
|
782
1369
|
for line in block.lines:
|
|
783
|
-
# NOTE: baseline,
|
|
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)
|
|
784
1373
|
line_span = SubElement(
|
|
785
1374
|
paragraph,
|
|
786
1375
|
"span",
|
|
@@ -789,7 +1378,7 @@ class XMLExporter:
|
|
|
789
1378
|
"id": f"line_{line_count}",
|
|
790
1379
|
"title": (
|
|
791
1380
|
f"{_hocr_bbox(line.geometry, width, height)}; "
|
|
792
|
-
"baseline 0 0; x_size
|
|
1381
|
+
f"baseline 0 0; x_size {x_size}; x_fsize {x_fsize}; x_descenders 0; x_ascenders 0"
|
|
793
1382
|
),
|
|
794
1383
|
},
|
|
795
1384
|
)
|
|
@@ -817,6 +1406,7 @@ class XMLExporter:
|
|
|
817
1406
|
file_title: str = "docTR - XML export (hOCR)",
|
|
818
1407
|
direction: str = "auto",
|
|
819
1408
|
reading_order: bool = True,
|
|
1409
|
+
dpi: int = 72,
|
|
820
1410
|
) -> tuple[bytes, ET.ElementTree]:
|
|
821
1411
|
"""Export a KIE page as hOCR XML, with the predictions of each class sorted in reading order.
|
|
822
1412
|
|
|
@@ -825,6 +1415,7 @@ class XMLExporter:
|
|
|
825
1415
|
file_title: the title of the XML file
|
|
826
1416
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
827
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`)
|
|
828
1419
|
|
|
829
1420
|
Returns:
|
|
830
1421
|
a tuple of the XML byte string, and its ElementTree
|
|
@@ -832,7 +1423,7 @@ class XMLExporter:
|
|
|
832
1423
|
prediction_count: int = 1
|
|
833
1424
|
height, width = page.dimensions
|
|
834
1425
|
page_hocr, body = self._new_document(file_title, _resolve_hocr_language(page.language))
|
|
835
|
-
SubElement(
|
|
1426
|
+
page_div = SubElement(
|
|
836
1427
|
body,
|
|
837
1428
|
"div",
|
|
838
1429
|
attrib={
|
|
@@ -848,8 +1439,9 @@ class XMLExporter:
|
|
|
848
1439
|
if len(prediction.geometry) != 2:
|
|
849
1440
|
raise TypeError("XML export is only available for straight bounding boxes for now.")
|
|
850
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]
|
|
851
1443
|
prediction_div = SubElement(
|
|
852
|
-
|
|
1444
|
+
page_div,
|
|
853
1445
|
"div",
|
|
854
1446
|
attrib={
|
|
855
1447
|
"class": "ocr_carea",
|
|
@@ -874,7 +1466,10 @@ class XMLExporter:
|
|
|
874
1466
|
attrib={
|
|
875
1467
|
"class": "ocr_line",
|
|
876
1468
|
"id": f"{class_name}_line_{prediction_count}",
|
|
877
|
-
"title":
|
|
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
|
+
),
|
|
878
1473
|
},
|
|
879
1474
|
)
|
|
880
1475
|
word_div = SubElement(
|
|
@@ -920,6 +1515,7 @@ class PageExportsMixin:
|
|
|
920
1515
|
language: dict[str, Any]
|
|
921
1516
|
layout: list[Any]
|
|
922
1517
|
tables: list["Table"]
|
|
1518
|
+
formulas: list["Formula"]
|
|
923
1519
|
|
|
924
1520
|
def render(self, block_break: str = "\n\n", direction: str = "auto", include_furniture: bool = True) -> str:
|
|
925
1521
|
"""Renders the full text of the page, with its content sorted in reading order.
|
|
@@ -946,11 +1542,12 @@ class PageExportsMixin:
|
|
|
946
1542
|
Returns:
|
|
947
1543
|
a JSON-serializable dict
|
|
948
1544
|
"""
|
|
949
|
-
from doctr.io.elements import
|
|
1545
|
+
from doctr.io.elements import Block, Element
|
|
950
1546
|
|
|
951
1547
|
export_dict = Element.export(cast("Element", self))
|
|
952
1548
|
if reading_order:
|
|
953
|
-
|
|
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)]
|
|
954
1551
|
if blocks: # an empty linearization (no line on the page) leaves the stored blocks untouched
|
|
955
1552
|
export_dict["blocks"] = [block.export() for block in blocks]
|
|
956
1553
|
return export_dict
|
|
@@ -960,6 +1557,7 @@ class PageExportsMixin:
|
|
|
960
1557
|
file_title: str = "docTR - XML export (hOCR)",
|
|
961
1558
|
direction: str = "auto",
|
|
962
1559
|
reading_order: bool = True,
|
|
1560
|
+
dpi: int = 72,
|
|
963
1561
|
) -> tuple[bytes, ET.ElementTree]:
|
|
964
1562
|
"""Export the page as XML (hOCR-format), with its content sorted in reading order
|
|
965
1563
|
convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
@@ -968,41 +1566,63 @@ class PageExportsMixin:
|
|
|
968
1566
|
file_title: the title of the XML file
|
|
969
1567
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
970
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`)
|
|
971
1570
|
|
|
972
1571
|
Returns:
|
|
973
1572
|
a tuple of the XML byte string, and its ElementTree
|
|
974
1573
|
"""
|
|
975
1574
|
return XMLExporter().export_page(
|
|
976
|
-
cast("Page", self), file_title=file_title, direction=direction, reading_order=reading_order
|
|
1575
|
+
cast("Page", self), file_title=file_title, direction=direction, reading_order=reading_order, dpi=dpi
|
|
977
1576
|
)
|
|
978
1577
|
|
|
979
|
-
def items_in_reading_order(
|
|
980
|
-
|
|
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.
|
|
981
1582
|
|
|
982
1583
|
Args:
|
|
983
1584
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1585
|
+
include_figures: whether to return the figure regions too
|
|
984
1586
|
|
|
985
1587
|
Returns:
|
|
986
|
-
list of blocks
|
|
1588
|
+
list of blocks, tables, formulas and, if requested, figures in reading order
|
|
987
1589
|
"""
|
|
988
|
-
return page_reading_order(cast("Page", self), direction)[0]
|
|
1590
|
+
return page_reading_order(cast("Page", self), direction, include_figures=include_figures)[0]
|
|
989
1591
|
|
|
990
|
-
def export_as_markdown(
|
|
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:
|
|
991
1599
|
"""Export the page as Markdown, with its content sorted in reading order.
|
|
992
1600
|
|
|
993
1601
|
Args:
|
|
994
1602
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
995
1603
|
escape: whether the characters carrying a structural meaning in Markdown should be escaped
|
|
996
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')
|
|
997
1607
|
|
|
998
1608
|
Returns:
|
|
999
1609
|
a Markdown string
|
|
1000
1610
|
"""
|
|
1001
1611
|
return MarkdownExporter().export_page(
|
|
1002
|
-
cast("Page", self),
|
|
1612
|
+
cast("Page", self),
|
|
1613
|
+
direction=direction,
|
|
1614
|
+
escape=escape,
|
|
1615
|
+
include_furniture=include_furniture,
|
|
1616
|
+
images=images,
|
|
1003
1617
|
)
|
|
1004
1618
|
|
|
1005
|
-
def export_as_asciidoc(
|
|
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:
|
|
1006
1626
|
"""Export the page as AsciiDoc, with its content sorted in reading order.
|
|
1007
1627
|
|
|
1008
1628
|
Args:
|
|
@@ -1010,25 +1630,40 @@ class PageExportsMixin:
|
|
|
1010
1630
|
escape: whether the characters and line markers carrying a structural meaning in AsciiDoc should
|
|
1011
1631
|
be escaped
|
|
1012
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')
|
|
1013
1635
|
|
|
1014
1636
|
Returns:
|
|
1015
1637
|
an AsciiDoc string
|
|
1016
1638
|
"""
|
|
1017
1639
|
return AsciiDocExporter().export_page(
|
|
1018
|
-
cast("Page", self),
|
|
1640
|
+
cast("Page", self),
|
|
1641
|
+
direction=direction,
|
|
1642
|
+
escape=escape,
|
|
1643
|
+
include_furniture=include_furniture,
|
|
1644
|
+
images=images,
|
|
1019
1645
|
)
|
|
1020
1646
|
|
|
1021
|
-
def export_as_html(
|
|
1647
|
+
def export_as_html(
|
|
1648
|
+
self,
|
|
1649
|
+
direction: str = "auto",
|
|
1650
|
+
include_furniture: bool = True,
|
|
1651
|
+
images: "str | FigureEncoder | None" = "placeholder",
|
|
1652
|
+
) -> str:
|
|
1022
1653
|
"""Export the page as semantic HTML, with its content sorted in reading order.
|
|
1023
1654
|
|
|
1024
1655
|
Args:
|
|
1025
1656
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1026
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')
|
|
1027
1660
|
|
|
1028
1661
|
Returns:
|
|
1029
1662
|
an HTML string
|
|
1030
1663
|
"""
|
|
1031
|
-
return HTMLExporter().export_page(
|
|
1664
|
+
return HTMLExporter().export_page(
|
|
1665
|
+
cast("Page", self), direction=direction, include_furniture=include_furniture, images=images
|
|
1666
|
+
)
|
|
1032
1667
|
|
|
1033
1668
|
def export_as(self, format: str, **kwargs: Any) -> Any:
|
|
1034
1669
|
"""Export the page in the requested format.
|
|
@@ -1113,6 +1748,7 @@ class KIEPageExportsMixin:
|
|
|
1113
1748
|
file_title: str = "docTR - XML export (hOCR)",
|
|
1114
1749
|
direction: str = "auto",
|
|
1115
1750
|
reading_order: bool = True,
|
|
1751
|
+
dpi: int = 72,
|
|
1116
1752
|
) -> tuple[bytes, ET.ElementTree]:
|
|
1117
1753
|
"""Export the page as XML (hOCR-format), with the predictions of each class in reading order
|
|
1118
1754
|
convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
@@ -1121,12 +1757,13 @@ class KIEPageExportsMixin:
|
|
|
1121
1757
|
file_title: the title of the XML file
|
|
1122
1758
|
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1123
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`)
|
|
1124
1761
|
|
|
1125
1762
|
Returns:
|
|
1126
1763
|
a tuple of the XML byte string, and its ElementTree
|
|
1127
1764
|
"""
|
|
1128
1765
|
return XMLExporter().export_kie_page(
|
|
1129
|
-
cast("KIEPage", self), file_title=file_title, direction=direction, reading_order=reading_order
|
|
1766
|
+
cast("KIEPage", self), file_title=file_title, direction=direction, reading_order=reading_order, dpi=dpi
|
|
1130
1767
|
)
|
|
1131
1768
|
|
|
1132
1769
|
def export_as_markdown(self, direction: str = "auto", escape: bool = True) -> str:
|
|
@@ -1225,7 +1862,8 @@ class DocumentExportsMixin:
|
|
|
1225
1862
|
|
|
1226
1863
|
Args:
|
|
1227
1864
|
page_break: the string inserted between two pages (a thematic break by default)
|
|
1228
|
-
**kwargs: additional keyword arguments passed to the `Page.export_as_markdown` method
|
|
1865
|
+
**kwargs: additional keyword arguments passed to the `Page.export_as_markdown` method (e.g. `images`,
|
|
1866
|
+
not supported by KIE pages)
|
|
1229
1867
|
|
|
1230
1868
|
Returns:
|
|
1231
1869
|
a Markdown string
|
|
@@ -1237,7 +1875,8 @@ class DocumentExportsMixin:
|
|
|
1237
1875
|
|
|
1238
1876
|
Args:
|
|
1239
1877
|
page_break: the string inserted between two pages (an AsciiDoc page break by default)
|
|
1240
|
-
**kwargs: additional keyword arguments passed to the `Page.export_as_asciidoc` method
|
|
1878
|
+
**kwargs: additional keyword arguments passed to the `Page.export_as_asciidoc` method (e.g. `images`,
|
|
1879
|
+
not supported by KIE pages)
|
|
1241
1880
|
|
|
1242
1881
|
Returns:
|
|
1243
1882
|
an AsciiDoc string
|
|
@@ -1249,7 +1888,8 @@ class DocumentExportsMixin:
|
|
|
1249
1888
|
|
|
1250
1889
|
Args:
|
|
1251
1890
|
page_break: the HTML snippet inserted between two pages
|
|
1252
|
-
**kwargs: additional keyword arguments passed to the page export
|
|
1891
|
+
**kwargs: additional keyword arguments passed to the page export (e.g. `images`, not supported by
|
|
1892
|
+
KIE pages)
|
|
1253
1893
|
|
|
1254
1894
|
Returns:
|
|
1255
1895
|
an HTML string
|