python-doctr 1.0.0__py3-none-any.whl → 1.1.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/__init__.py +0 -0
- doctr/cli/main.py +506 -0
- doctr/contrib/artefacts.py +1 -1
- doctr/contrib/base.py +1 -1
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +5 -3
- doctr/datasets/cord.py +3 -2
- doctr/datasets/datasets/base.py +13 -25
- doctr/datasets/datasets/pytorch.py +15 -5
- doctr/datasets/detection.py +3 -2
- doctr/datasets/doc_artefacts.py +3 -2
- doctr/datasets/funsd.py +3 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +4 -3
- doctr/datasets/ic13.py +5 -3
- doctr/datasets/iiit5k.py +3 -2
- doctr/datasets/iiithws.py +5 -3
- doctr/datasets/imgur5k.py +5 -3
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +5 -3
- doctr/datasets/ocr.py +3 -2
- doctr/datasets/orientation.py +3 -2
- doctr/datasets/recognition.py +3 -2
- doctr/datasets/sroie.py +3 -2
- doctr/datasets/svhn.py +3 -2
- doctr/datasets/svt.py +4 -3
- doctr/datasets/synthtext.py +3 -2
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +15 -6
- doctr/datasets/vocabs.py +3 -1
- doctr/datasets/wildreceipt.py +5 -3
- doctr/file_utils.py +4 -2
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +253 -261
- doctr/io/exporters.py +1275 -0
- doctr/io/html.py +1 -1
- doctr/io/image/base.py +4 -3
- doctr/io/image/pytorch.py +6 -4
- doctr/io/pdf.py +1 -1
- doctr/io/reader.py +1 -1
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +111 -25
- doctr/models/builder.py +533 -62
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +2 -2
- doctr/models/classification/mobilenet/pytorch.py +7 -7
- doctr/models/classification/predictor/pytorch.py +7 -3
- doctr/models/classification/resnet/pytorch.py +6 -6
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +7 -6
- doctr/models/classification/vgg/pytorch.py +4 -3
- doctr/models/classification/vip/layers/pytorch.py +5 -5
- doctr/models/classification/vip/pytorch.py +5 -5
- doctr/models/classification/vit/pytorch.py +4 -4
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +4 -1
- doctr/models/core.py +1 -1
- doctr/models/detection/_utils/base.py +24 -8
- doctr/models/detection/_utils/pytorch.py +1 -1
- doctr/models/detection/core.py +34 -19
- doctr/models/detection/differentiable_binarization/base.py +7 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
- doctr/models/detection/fast/base.py +6 -2
- doctr/models/detection/fast/pytorch.py +4 -4
- doctr/models/detection/linknet/base.py +6 -2
- doctr/models/detection/linknet/pytorch.py +4 -4
- doctr/models/detection/predictor/pytorch.py +4 -3
- doctr/models/detection/zoo.py +3 -3
- doctr/models/factory/hub.py +72 -52
- doctr/models/kie_predictor/base.py +17 -2
- doctr/models/kie_predictor/pytorch.py +42 -11
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +140 -4
- doctr/models/modules/transformer/pytorch.py +1 -1
- doctr/models/modules/vision_transformer/pytorch.py +1 -1
- doctr/models/predictor/base.py +138 -16
- doctr/models/predictor/pytorch.py +151 -9
- doctr/models/preprocessor/pytorch.py +78 -23
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/core.py +1 -1
- doctr/models/recognition/crnn/pytorch.py +6 -8
- doctr/models/recognition/master/base.py +1 -1
- doctr/models/recognition/master/pytorch.py +7 -8
- doctr/models/recognition/parseq/base.py +1 -1
- doctr/models/recognition/parseq/pytorch.py +5 -5
- doctr/models/recognition/predictor/_utils.py +1 -1
- doctr/models/recognition/predictor/pytorch.py +2 -2
- doctr/models/recognition/sar/pytorch.py +2 -2
- doctr/models/recognition/utils.py +9 -11
- doctr/models/recognition/viptr/pytorch.py +4 -6
- doctr/models/recognition/vitstr/base.py +1 -1
- doctr/models/recognition/vitstr/pytorch.py +6 -6
- doctr/models/recognition/zoo.py +6 -7
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +316 -16
- doctr/models/zoo.py +91 -3
- doctr/transforms/functional/base.py +3 -2
- doctr/transforms/functional/pytorch.py +1 -1
- doctr/transforms/modules/base.py +248 -83
- doctr/transforms/modules/pytorch.py +213 -74
- doctr/utils/common_types.py +22 -2
- doctr/utils/data.py +5 -4
- doctr/utils/fonts.py +56 -17
- doctr/utils/geometry.py +136 -19
- doctr/utils/metrics.py +351 -19
- doctr/utils/multithreading.py +6 -3
- doctr/utils/reconstitution.py +697 -133
- doctr/utils/repr.py +1 -1
- doctr/utils/visualization.py +63 -4
- doctr/version.py +1 -1
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.0.dist-info/RECORD +0 -149
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
doctr/io/exporters.py
ADDED
|
@@ -0,0 +1,1275 @@
|
|
|
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
|
+
from html import escape as _html_escape
|
|
7
|
+
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
|
8
|
+
from xml.etree import ElementTree as ET
|
|
9
|
+
from xml.etree.ElementTree import Element as ETElement
|
|
10
|
+
from xml.etree.ElementTree import SubElement
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
import doctr
|
|
15
|
+
from doctr.utils.common_types import BoundingBox
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
18
|
+
from doctr.io.elements import Block, KIEPage, Line, Page, Table
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"AsciiDocExporter",
|
|
22
|
+
"DocumentExportsMixin",
|
|
23
|
+
"HTMLExporter",
|
|
24
|
+
"KIEPageExportsMixin",
|
|
25
|
+
"MarkdownExporter",
|
|
26
|
+
"PageExportsMixin",
|
|
27
|
+
"TextExporter",
|
|
28
|
+
"XMLExporter",
|
|
29
|
+
"page_reading_order",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _export_as(exporters: dict[str, Any], format: str, **kwargs: Any) -> Any:
|
|
34
|
+
fmt = format.strip().lower()
|
|
35
|
+
if fmt not in exporters:
|
|
36
|
+
raise ValueError(f"unsupported export format '{format}', should be one of {sorted(exporters)}")
|
|
37
|
+
return exporters[fmt](**kwargs)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def to_json_safe(value: Any) -> Any:
|
|
41
|
+
"""Recursively convert NumPy containers and scalars into built-in Python types.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
value: any exported value
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
the same value with every NumPy array converted to nested tuples and every NumPy scalar to its
|
|
48
|
+
Python equivalent
|
|
49
|
+
"""
|
|
50
|
+
if isinstance(value, np.ndarray):
|
|
51
|
+
return value.item() if value.ndim == 0 else tuple(to_json_safe(item) for item in value)
|
|
52
|
+
if isinstance(value, np.generic): # np.float32, np.int64, np.bool_, ...
|
|
53
|
+
return value.item()
|
|
54
|
+
if isinstance(value, dict):
|
|
55
|
+
return {str(key): to_json_safe(item) for key, item in value.items()}
|
|
56
|
+
if isinstance(value, tuple):
|
|
57
|
+
return tuple(to_json_safe(item) for item in value)
|
|
58
|
+
if isinstance(value, (list, set, frozenset)):
|
|
59
|
+
return [to_json_safe(item) for item in value]
|
|
60
|
+
return value
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
_LIST_LABELS = {"list_item"}
|
|
64
|
+
# Characters / line markers that carry a structural meaning and are escaped to preserve the raw OCR text
|
|
65
|
+
_MD_SPECIAL_CHARS = "\\`*_[]|#<>"
|
|
66
|
+
_MD_LINE_MARKERS = "-+>#=`"
|
|
67
|
+
_ADOC_SPECIAL_CHARS = "\\`*_#^~|+{}<>"
|
|
68
|
+
_ADOC_LINE_MARKERS = "=*.-/+"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _covering_region_indices(geoms: list[Any], region_geoms: list[Any], min_coverage: float = 0.5) -> list[int]:
|
|
72
|
+
"""For each element geometry, the index of the layout region covering the largest share of its area.
|
|
73
|
+
|
|
74
|
+
Uses the same area-coverage criterion as :func:`doctr.models.reading_order.assign_layout_labels`, and
|
|
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.
|
|
77
|
+
"""
|
|
78
|
+
from doctr.models.reading_order.base import _to_boxes
|
|
79
|
+
|
|
80
|
+
if len(region_geoms) == 0 or len(geoms) == 0:
|
|
81
|
+
return [-1] * len(geoms)
|
|
82
|
+
boxes, regions = _to_boxes(geoms), _to_boxes(region_geoms)
|
|
83
|
+
inter_w = np.minimum(boxes[:, None, 2], regions[None, :, 2]) - np.maximum(boxes[:, None, 0], regions[None, :, 0])
|
|
84
|
+
inter_h = np.minimum(boxes[:, None, 3], regions[None, :, 3]) - np.maximum(boxes[:, None, 1], regions[None, :, 1])
|
|
85
|
+
inter = np.clip(inter_w, 0, None) * np.clip(inter_h, 0, None)
|
|
86
|
+
areas = np.clip((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]), 1e-9, None)
|
|
87
|
+
coverage = inter / areas[:, None]
|
|
88
|
+
best = coverage.argmax(axis=1)
|
|
89
|
+
return [int(reg) if coverage[i, reg] >= min_coverage else -1 for i, reg in enumerate(best)]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _reading_order_signature(page: "Page", direction: str) -> tuple[Any, ...]:
|
|
93
|
+
"""A cheap structural fingerprint of a page, used to invalidate the reading-order cache.
|
|
94
|
+
|
|
95
|
+
Covers the requested direction and the identity (plus line count) of every block and table, so
|
|
96
|
+
replacing or re-grouping the page content invalidates the cache. In-place edits to a `Line`'s words
|
|
97
|
+
are not detected; callers mutating a page that deeply should drop `_reading_order_cache` themselves.
|
|
98
|
+
"""
|
|
99
|
+
return (
|
|
100
|
+
direction,
|
|
101
|
+
tuple((id(block), len(block.lines)) for block in page.blocks),
|
|
102
|
+
tuple(id(table) for table in getattr(page, "tables", ()) or ()),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _store_reading_order(page: "Page", signature: tuple[Any, ...], result: tuple[Any, ...]) -> None:
|
|
107
|
+
"""Memoize a reading-order result on the page, ignoring pages that reject attribute assignment."""
|
|
108
|
+
try:
|
|
109
|
+
page._reading_order_cache = (signature, result) # type: ignore[attr-defined]
|
|
110
|
+
except AttributeError: # pragma: no cover
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def page_reading_order(page: "Page", direction: str = "auto") -> tuple[list[Any], list[str | None], str]:
|
|
115
|
+
"""Linearize the content of a page (blocks & tables) in reading order.
|
|
116
|
+
|
|
117
|
+
The result is memoized on the page: every exporter calls this, so a page exported to several formats
|
|
118
|
+
(or built with `keep_reading_order=True` and then exported) orders its content once.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
page: the page to linearize
|
|
122
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
a tuple with the ordered items (blocks & tables), their layout label (None without layout) and the
|
|
126
|
+
effective reading direction
|
|
127
|
+
"""
|
|
128
|
+
from doctr.io.elements import Block, Table
|
|
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
|
+
)
|
|
136
|
+
|
|
137
|
+
signature = _reading_order_signature(page, direction)
|
|
138
|
+
cached = getattr(page, "_reading_order_cache", None)
|
|
139
|
+
if cached is not None and cached[0] == signature:
|
|
140
|
+
items, labels, resolved = cached[1]
|
|
141
|
+
return list(items), list(labels), resolved
|
|
142
|
+
|
|
143
|
+
texts = [word.value for block in page.blocks for line in block.lines for word in line.words]
|
|
144
|
+
language = page.language.get("value") if isinstance(page.language, dict) else None
|
|
145
|
+
direction = ReadingOrderPredictor(direction=direction).resolve_direction(texts, language=language)
|
|
146
|
+
region_geoms = [region.geometry for region in page.layout]
|
|
147
|
+
region_labels = [region.type for region in page.layout]
|
|
148
|
+
|
|
149
|
+
lines = [line for block in page.blocks for line in block.lines]
|
|
150
|
+
elements: list[Any] = [*lines, *page.tables]
|
|
151
|
+
if len(elements) == 0:
|
|
152
|
+
_store_reading_order(page, signature, ([], [], direction))
|
|
153
|
+
return [], [], direction
|
|
154
|
+
# De-skew once so labeling, ordering and region grouping share the same upright frame; the page angle is
|
|
155
|
+
# estimated from the word polygons, which carry the detection model's true orientation
|
|
156
|
+
elt_geoms, region_geoms = deskew_reading_geometries(
|
|
157
|
+
[elt.geometry for elt in elements],
|
|
158
|
+
region_geoms,
|
|
159
|
+
page_shape=page.dimensions,
|
|
160
|
+
angle_geoms=[word.geometry for line in lines for word in line.words],
|
|
161
|
+
)
|
|
162
|
+
elt_labels: list[str | None] = [None] * len(elements)
|
|
163
|
+
if len(region_geoms) > 0:
|
|
164
|
+
elt_labels = assign_layout_labels(elt_geoms, region_geoms, region_labels)
|
|
165
|
+
elt_labels = ["Table" if isinstance(elt, Table) else label for elt, label in zip(elements, elt_labels)]
|
|
166
|
+
segments = resolve_reading_segments(elt_geoms, direction=direction, labels=elt_labels)
|
|
167
|
+
|
|
168
|
+
items = []
|
|
169
|
+
labels = []
|
|
170
|
+
line_owner = {id(line): idx for idx, block in enumerate(page.blocks) for line in block.lines}
|
|
171
|
+
pending_artefacts = {idx: list(block.artefacts) for idx, block in enumerate(page.blocks) if block.artefacts}
|
|
172
|
+
|
|
173
|
+
def _claim_artefacts(block_lines: list[Any]) -> list[Any]:
|
|
174
|
+
claimed: list[Any] = []
|
|
175
|
+
for line in block_lines:
|
|
176
|
+
owner = line_owner.get(id(line))
|
|
177
|
+
if owner is not None and owner in pending_artefacts:
|
|
178
|
+
claimed.extend(pending_artefacts.pop(owner))
|
|
179
|
+
return claimed
|
|
180
|
+
|
|
181
|
+
# Region index covering each element, used to group the lines of a wrapped list item under a single bullet
|
|
182
|
+
region_idx = _covering_region_indices(elt_geoms, region_geoms) if len(region_geoms) > 0 else [-1] * len(elements)
|
|
183
|
+
open_list_region: int | None = None # region of the list bullet currently being built (None outside a list)
|
|
184
|
+
for segment in segments:
|
|
185
|
+
first = elements[segment[0]]
|
|
186
|
+
seg_label = elt_labels[segment[0]]
|
|
187
|
+
if isinstance(first, Table):
|
|
188
|
+
items.append(first)
|
|
189
|
+
labels.append("Table")
|
|
190
|
+
open_list_region = None
|
|
191
|
+
continue
|
|
192
|
+
if normalize_layout_label(seg_label) in _LIST_LABELS:
|
|
193
|
+
# One bullet per list-item region: consecutive lines sharing the same region are one bullet, so a
|
|
194
|
+
# list item wrapped over several visual lines renders as a single bullet point.
|
|
195
|
+
for idx in segment:
|
|
196
|
+
region = region_idx[idx]
|
|
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]])])
|
|
200
|
+
else:
|
|
201
|
+
items.append(Block(lines=[elements[idx]], artefacts=_claim_artefacts([elements[idx]])))
|
|
202
|
+
labels.append(seg_label)
|
|
203
|
+
open_list_region = region
|
|
204
|
+
else:
|
|
205
|
+
block_lines = [elements[idx] for idx in segment]
|
|
206
|
+
items.append(Block(lines=block_lines, artefacts=_claim_artefacts(block_lines)))
|
|
207
|
+
labels.append(seg_label)
|
|
208
|
+
open_list_region = None
|
|
209
|
+
# Artefacts of blocks without any line stay attached to the page
|
|
210
|
+
leftover = [artefact for artefacts in pending_artefacts.values() for artefact in artefacts]
|
|
211
|
+
if leftover:
|
|
212
|
+
last_block = next((item for item in reversed(items) if isinstance(item, Block)), None)
|
|
213
|
+
if last_block is not None:
|
|
214
|
+
last_block.artefacts = [*last_block.artefacts, *leftover]
|
|
215
|
+
_store_reading_order(page, signature, (items, labels, direction))
|
|
216
|
+
return items, labels, direction
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _line_render_direction(line: "Line", page_direction: str, auto: bool) -> str:
|
|
220
|
+
"""Resolve the direction used to order the words of a line.
|
|
221
|
+
|
|
222
|
+
For vertical pages the words are always read top to bottom. For horizontal pages, when the page direction
|
|
223
|
+
was inferred automatically, the base direction of each line is detected from its own text so that an
|
|
224
|
+
embedded left-to-right run (e.g. a Latin quotation on an Arabic page) keeps its natural word order; when
|
|
225
|
+
the direction is set explicitly, it is applied uniformly to every line.
|
|
226
|
+
"""
|
|
227
|
+
if page_direction in ("ttb-rtl", "ttb-ltr") or not auto or len(line.words) <= 1:
|
|
228
|
+
return page_direction
|
|
229
|
+
from doctr.models.reading_order import detect_text_direction
|
|
230
|
+
|
|
231
|
+
return detect_text_direction([word.render() for word in line.words])
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def ordered_line_words(line: "Line", direction: str = "ltr", auto: bool = False) -> list[Any]:
|
|
235
|
+
"""Return the words of a line in reading order.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
line: the line whose words should be ordered
|
|
239
|
+
direction: the reading direction resolved for the page
|
|
240
|
+
auto: whether the page direction was inferred (each line then gets its own base direction)
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
the words of the line, ordered logically
|
|
244
|
+
"""
|
|
245
|
+
direction = _line_render_direction(line, direction, auto)
|
|
246
|
+
if direction in ("ttb-rtl", "ttb-ltr"):
|
|
247
|
+
return sorted(line.words, key=lambda word: float(np.asarray(word.geometry, dtype=np.float64)[..., 1].mean()))
|
|
248
|
+
if direction == "rtl":
|
|
249
|
+
return sorted(line.words, key=lambda word: -float(np.asarray(word.geometry, dtype=np.float64)[..., 0].mean()))
|
|
250
|
+
return list(line.words)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def predictions_in_reading_order(page: "KIEPage", predictions: list[Any], direction: str = "auto") -> list[Any]:
|
|
254
|
+
"""Sort the predictions of a single KIE detection class in reading order.
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
page: the KIE page the predictions belong to (used for its dimensions and detected language)
|
|
258
|
+
predictions: the predictions of one detection class
|
|
259
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
the predictions, ordered logically
|
|
263
|
+
"""
|
|
264
|
+
from doctr.models.reading_order import ReadingOrderPredictor
|
|
265
|
+
|
|
266
|
+
if len(predictions) < 2:
|
|
267
|
+
return list(predictions)
|
|
268
|
+
language = page.language.get("value") if isinstance(page.language, dict) else None
|
|
269
|
+
order = ReadingOrderPredictor(direction=direction)(
|
|
270
|
+
[prediction.geometry for prediction in predictions],
|
|
271
|
+
texts=[prediction.value for prediction in predictions],
|
|
272
|
+
language=language,
|
|
273
|
+
page_shape=page.dimensions,
|
|
274
|
+
)
|
|
275
|
+
return [predictions[idx] for idx in order]
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class _PageTextExporter:
|
|
279
|
+
"""Shared logic of the reading-order-aware text exporters.
|
|
280
|
+
|
|
281
|
+
Subclasses define the format specifics: heading prefixes (per normalized layout label), the bullet
|
|
282
|
+
prefix, character escaping, line finalization (neutralizing markers a line must not start with) and the
|
|
283
|
+
table rendering.
|
|
284
|
+
"""
|
|
285
|
+
|
|
286
|
+
headings: ClassVar[dict[str, str]] = {}
|
|
287
|
+
bullet: ClassVar[str] = "- "
|
|
288
|
+
block_break: ClassVar[str] = "\n\n"
|
|
289
|
+
page_break: ClassVar[str] = "\n\n"
|
|
290
|
+
|
|
291
|
+
def escape_text(self, text: str) -> str:
|
|
292
|
+
"""Escape the characters carrying a structural meaning in the target format"""
|
|
293
|
+
return text
|
|
294
|
+
|
|
295
|
+
def finalize_line(self, line: str) -> str:
|
|
296
|
+
"""Neutralize the block-level markers a line must not start with in the target format"""
|
|
297
|
+
return line
|
|
298
|
+
|
|
299
|
+
def render_table(self, table: "Table", escape: bool = True) -> str:
|
|
300
|
+
"""Render a recognized table in the target format"""
|
|
301
|
+
raise NotImplementedError
|
|
302
|
+
|
|
303
|
+
def class_header(self, class_name: str, escape: bool = True) -> str:
|
|
304
|
+
"""Render the header of a detection class in a KIE export"""
|
|
305
|
+
raise NotImplementedError
|
|
306
|
+
|
|
307
|
+
def _line_text(self, line: "Line", direction: str, escape: bool) -> str:
|
|
308
|
+
"""Render the text of a line, ordering the words according to the reading direction."""
|
|
309
|
+
text = " ".join(word.render() for word in ordered_line_words(line, direction))
|
|
310
|
+
return self.escape_text(text) if escape else text
|
|
311
|
+
|
|
312
|
+
def export_page(
|
|
313
|
+
self,
|
|
314
|
+
page: "Page",
|
|
315
|
+
direction: str = "auto",
|
|
316
|
+
escape: bool = True,
|
|
317
|
+
include_furniture: bool = True,
|
|
318
|
+
block_break: str | None = None,
|
|
319
|
+
) -> str:
|
|
320
|
+
"""Export a page, with its content sorted in reading order.
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
page: the page to export
|
|
324
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
325
|
+
escape: whether the characters or markers carrying a structural meaning should be neutralized
|
|
326
|
+
include_furniture: whether page headers, page footers and footnotes should be included
|
|
327
|
+
block_break: the string inserted between two blocks (the format-specific default when None)
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
the exported page as a string
|
|
331
|
+
"""
|
|
332
|
+
from doctr.io.elements import Table
|
|
333
|
+
from doctr.models.reading_order import layout_label_role, normalize_layout_label
|
|
334
|
+
|
|
335
|
+
auto = direction == "auto"
|
|
336
|
+
items, labels, direction = page_reading_order(page, direction)
|
|
337
|
+
parts: list[str] = []
|
|
338
|
+
list_group: list[str] = []
|
|
339
|
+
|
|
340
|
+
def _flush_list() -> None:
|
|
341
|
+
if list_group:
|
|
342
|
+
parts.append("\n".join(list_group))
|
|
343
|
+
list_group.clear()
|
|
344
|
+
|
|
345
|
+
for item, label in zip(items, labels):
|
|
346
|
+
if not include_furniture and layout_label_role(label) in ("header", "footer", "footnote"):
|
|
347
|
+
continue
|
|
348
|
+
if isinstance(item, Table):
|
|
349
|
+
_flush_list()
|
|
350
|
+
rendered = self.render_table(item, escape=escape)
|
|
351
|
+
if rendered:
|
|
352
|
+
parts.append(rendered)
|
|
353
|
+
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()]
|
|
358
|
+
if len(item_lines) == 0:
|
|
359
|
+
continue
|
|
360
|
+
norm_label = normalize_layout_label(label)
|
|
361
|
+
if norm_label in self.headings:
|
|
362
|
+
_flush_list()
|
|
363
|
+
parts.append(self.headings[norm_label] + " ".join(item_lines))
|
|
364
|
+
elif norm_label in _LIST_LABELS:
|
|
365
|
+
# A list item (possibly wrapped over several lines) renders as a single bullet
|
|
366
|
+
text = " ".join(item_lines)
|
|
367
|
+
list_group.append(self.bullet + (self.finalize_line(text) if escape else text))
|
|
368
|
+
else:
|
|
369
|
+
_flush_list()
|
|
370
|
+
parts.append("\n".join(self.finalize_line(line) if escape else line for line in item_lines))
|
|
371
|
+
_flush_list()
|
|
372
|
+
return (self.block_break if block_break is None else block_break).join(parts)
|
|
373
|
+
|
|
374
|
+
def export_kie_page(self, page: "KIEPage", direction: str = "auto", escape: bool = True) -> str:
|
|
375
|
+
"""Export a KIE page, with the predictions of each class sorted in reading order.
|
|
376
|
+
|
|
377
|
+
Args:
|
|
378
|
+
page: the KIE page to export
|
|
379
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
380
|
+
escape: whether the characters or markers carrying a structural meaning should be neutralized
|
|
381
|
+
|
|
382
|
+
Returns:
|
|
383
|
+
the exported page as a string, with one section per detection class
|
|
384
|
+
"""
|
|
385
|
+
parts: list[str] = []
|
|
386
|
+
for class_name, predictions in page.predictions.items():
|
|
387
|
+
if len(predictions) == 0:
|
|
388
|
+
continue
|
|
389
|
+
values = "\n".join(
|
|
390
|
+
self.bullet + (self.finalize_line(self.escape_text(prediction.value)) if escape else prediction.value)
|
|
391
|
+
for prediction in predictions_in_reading_order(page, predictions, direction)
|
|
392
|
+
)
|
|
393
|
+
parts.append(f"{self.class_header(class_name, escape)}\n\n{values}")
|
|
394
|
+
return "\n\n".join(parts)
|
|
395
|
+
|
|
396
|
+
def export_document(self, document: Any, page_break: str | None = None, **kwargs: Any) -> str:
|
|
397
|
+
"""Export a document page by page.
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
document: the document to export
|
|
401
|
+
page_break: the string inserted between two pages (a format-specific default when None)
|
|
402
|
+
**kwargs: additional keyword arguments passed to the page export
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
the exported document as a string
|
|
406
|
+
"""
|
|
407
|
+
from doctr.io.elements import KIEPage
|
|
408
|
+
|
|
409
|
+
page_break = self.page_break if page_break is None else page_break
|
|
410
|
+
return page_break.join(
|
|
411
|
+
self.export_kie_page(page, **kwargs) if isinstance(page, KIEPage) else self.export_page(page, **kwargs)
|
|
412
|
+
for page in document.pages
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
class TextExporter(_PageTextExporter):
|
|
417
|
+
"""Export OCR results to plain text, with the content sorted in reading order.
|
|
418
|
+
|
|
419
|
+
>>> from doctr.io import TextExporter
|
|
420
|
+
>>> text = TextExporter().export_page(page)
|
|
421
|
+
"""
|
|
422
|
+
|
|
423
|
+
headings: ClassVar[dict[str, str]] = {}
|
|
424
|
+
bullet: ClassVar[str] = ""
|
|
425
|
+
block_break: ClassVar[str] = "\n\n"
|
|
426
|
+
page_break: ClassVar[str] = "\n\n\n\n"
|
|
427
|
+
|
|
428
|
+
def render_table(self, table: "Table", escape: bool = True) -> str:
|
|
429
|
+
"""Render a table as tab-separated values, one line per row"""
|
|
430
|
+
return table.render()
|
|
431
|
+
|
|
432
|
+
def class_header(self, class_name: str, escape: bool = True) -> str:
|
|
433
|
+
return f"{class_name}:"
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
class MarkdownExporter(_PageTextExporter):
|
|
437
|
+
"""Export OCR results to Markdown, with the content sorted in reading order.
|
|
438
|
+
|
|
439
|
+
>>> from doctr.io import MarkdownExporter
|
|
440
|
+
>>> markdown = MarkdownExporter().export_page(page)
|
|
441
|
+
"""
|
|
442
|
+
|
|
443
|
+
headings: ClassVar[dict[str, str]] = {"title": "# ", "section_header": "## "}
|
|
444
|
+
bullet: ClassVar[str] = "- "
|
|
445
|
+
page_break: ClassVar[str] = "\n\n---\n\n"
|
|
446
|
+
|
|
447
|
+
def escape_text(self, text: str) -> str:
|
|
448
|
+
return "".join(f"\\{char}" if char in _MD_SPECIAL_CHARS else char for char in text)
|
|
449
|
+
|
|
450
|
+
def finalize_line(self, line: str) -> str:
|
|
451
|
+
stripped = line.lstrip()
|
|
452
|
+
if stripped and (stripped[0] in _MD_LINE_MARKERS or stripped.split(" ")[0].rstrip(".").isdigit()):
|
|
453
|
+
return f"\\{line}" if line[0] != "\\" else line
|
|
454
|
+
return line
|
|
455
|
+
|
|
456
|
+
def render_table(self, table: "Table", escape: bool = True) -> str:
|
|
457
|
+
"""Render a table as a GitHub-flavored Markdown table (first row used as header)"""
|
|
458
|
+
grid = table.to_grid()
|
|
459
|
+
if len(grid) == 0 or len(grid[0]) == 0:
|
|
460
|
+
return ""
|
|
461
|
+
|
|
462
|
+
def _cell(value: str) -> str:
|
|
463
|
+
value = self.escape_text(value) if escape else value.replace("|", "\\|")
|
|
464
|
+
return value.replace("\n", " ").strip()
|
|
465
|
+
|
|
466
|
+
rows = ["| " + " | ".join(_cell(value) for value in row) + " |" for row in grid]
|
|
467
|
+
separator = "| " + " | ".join("---" for _ in grid[0]) + " |"
|
|
468
|
+
return "\n".join([rows[0], separator, *rows[1:]])
|
|
469
|
+
|
|
470
|
+
def class_header(self, class_name: str, escape: bool = True) -> str:
|
|
471
|
+
return f"**{self.escape_text(class_name) if escape else class_name}**"
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
class AsciiDocExporter(_PageTextExporter):
|
|
475
|
+
"""Export OCR results to AsciiDoc, with the content sorted in reading order.
|
|
476
|
+
|
|
477
|
+
>>> from doctr.io import AsciiDocExporter
|
|
478
|
+
>>> asciidoc = AsciiDocExporter().export_page(page)
|
|
479
|
+
"""
|
|
480
|
+
|
|
481
|
+
headings: ClassVar[dict[str, str]] = {"title": "== ", "section_header": "=== "}
|
|
482
|
+
bullet: ClassVar[str] = "* "
|
|
483
|
+
page_break: ClassVar[str] = "\n\n<<<\n\n"
|
|
484
|
+
|
|
485
|
+
def escape_text(self, text: str) -> str:
|
|
486
|
+
return "".join(f"\\{char}" if char in _ADOC_SPECIAL_CHARS else char for char in text)
|
|
487
|
+
|
|
488
|
+
def finalize_line(self, line: str) -> str:
|
|
489
|
+
stripped = line.lstrip()
|
|
490
|
+
if stripped and stripped[0] in _ADOC_LINE_MARKERS:
|
|
491
|
+
return f"{{empty}}{line}"
|
|
492
|
+
return line
|
|
493
|
+
|
|
494
|
+
def render_table(self, table: "Table", escape: bool = True) -> str:
|
|
495
|
+
"""Render a table as an AsciiDoc table (first row used as header)"""
|
|
496
|
+
grid = table.to_grid()
|
|
497
|
+
if len(grid) == 0 or len(grid[0]) == 0:
|
|
498
|
+
return ""
|
|
499
|
+
|
|
500
|
+
def _row(row: list[str]) -> str:
|
|
501
|
+
return " ".join(
|
|
502
|
+
"|" + (self.escape_text(value) if escape else value.replace("|", "\\|")).replace("\n", " ").strip()
|
|
503
|
+
for value in row
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
return "\n".join(["|===", _row(grid[0]), "", *[_row(row) for row in grid[1:]], "|==="])
|
|
507
|
+
|
|
508
|
+
def class_header(self, class_name: str, escape: bool = True) -> str:
|
|
509
|
+
return f"*{self.escape_text(class_name) if escape else class_name}*"
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
class HTMLExporter(_PageTextExporter):
|
|
513
|
+
"""Export OCR results to semantic HTML, with the content sorted in reading order.
|
|
514
|
+
|
|
515
|
+
Headings map to `<h1>`/`<h2>`, list items to `<ul><li>`, recognized tables to `<table>` and
|
|
516
|
+
paragraphs to `<p>` (with `<br>` between the visual lines of a paragraph). The output is a
|
|
517
|
+
fragment, not a full document: it carries no doctype, `<html>` or charset declaration.
|
|
518
|
+
|
|
519
|
+
.. warning::
|
|
520
|
+
The recognized text is HTML-escaped by default. Passing ``escape=False`` interpolates the OCR
|
|
521
|
+
output into the markup verbatim, so a document containing markup yields active HTML.
|
|
522
|
+
Only disable escaping for output that is never rendered in a browser.
|
|
523
|
+
|
|
524
|
+
>>> from doctr.io import HTMLExporter
|
|
525
|
+
>>> html = HTMLExporter().export_page(page)
|
|
526
|
+
"""
|
|
527
|
+
|
|
528
|
+
headings: ClassVar[dict[str, str]] = {"title": "h1", "section_header": "h2"}
|
|
529
|
+
block_break: ClassVar[str] = "\n"
|
|
530
|
+
page_break: ClassVar[str] = "\n<hr>\n"
|
|
531
|
+
|
|
532
|
+
def escape_text(self, text: str) -> str:
|
|
533
|
+
return _html_escape(text, quote=False)
|
|
534
|
+
|
|
535
|
+
def export_page(
|
|
536
|
+
self,
|
|
537
|
+
page: "Page",
|
|
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
|
|
545
|
+
|
|
546
|
+
auto = direction == "auto"
|
|
547
|
+
items, labels, direction = page_reading_order(page, direction)
|
|
548
|
+
parts: list[str] = []
|
|
549
|
+
list_group: list[str] = []
|
|
550
|
+
|
|
551
|
+
def _flush_list() -> None:
|
|
552
|
+
if list_group:
|
|
553
|
+
parts.append("<ul>\n" + "\n".join(list_group) + "\n</ul>")
|
|
554
|
+
list_group.clear()
|
|
555
|
+
|
|
556
|
+
for item, label in zip(items, labels):
|
|
557
|
+
if not include_furniture and layout_label_role(label) in ("header", "footer", "footnote"):
|
|
558
|
+
continue
|
|
559
|
+
if isinstance(item, Table):
|
|
560
|
+
_flush_list()
|
|
561
|
+
rendered = self.render_table(item, escape=escape)
|
|
562
|
+
if rendered:
|
|
563
|
+
parts.append(rendered)
|
|
564
|
+
continue
|
|
565
|
+
item_lines = [
|
|
566
|
+
self._line_text(line, _line_render_direction(line, direction, auto), escape) for line in item.lines
|
|
567
|
+
]
|
|
568
|
+
item_lines = [line for line in item_lines if line.strip()]
|
|
569
|
+
if len(item_lines) == 0:
|
|
570
|
+
continue
|
|
571
|
+
norm_label = normalize_layout_label(label)
|
|
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)
|
|
583
|
+
|
|
584
|
+
def render_table(self, table: "Table", escape: bool = True) -> str:
|
|
585
|
+
"""Render a table as an HTML table (first row used as header)"""
|
|
586
|
+
grid = table.to_grid()
|
|
587
|
+
if len(grid) == 0 or len(grid[0]) == 0:
|
|
588
|
+
return ""
|
|
589
|
+
|
|
590
|
+
def _cell(value: str, tag: str) -> str:
|
|
591
|
+
content = self.escape_text(value) if escape else value
|
|
592
|
+
return f"<{tag}>{content.strip()}</{tag}>"
|
|
593
|
+
|
|
594
|
+
head = "<tr>" + "".join(_cell(value, "th") for value in grid[0]) + "</tr>"
|
|
595
|
+
body = "\n".join("<tr>" + "".join(_cell(value, "td") for value in row) + "</tr>" for row in grid[1:])
|
|
596
|
+
return f"<table>\n{head}\n{body}\n</table>" if body else f"<table>\n{head}\n</table>"
|
|
597
|
+
|
|
598
|
+
def export_kie_page(self, page: "KIEPage", direction: str = "auto", escape: bool = True) -> str:
|
|
599
|
+
parts: list[str] = []
|
|
600
|
+
for class_name, predictions in page.predictions.items():
|
|
601
|
+
if len(predictions) == 0:
|
|
602
|
+
continue
|
|
603
|
+
values = "\n".join(
|
|
604
|
+
f"<li>{self.escape_text(prediction.value) if escape else prediction.value}</li>"
|
|
605
|
+
for prediction in predictions_in_reading_order(page, predictions, direction)
|
|
606
|
+
)
|
|
607
|
+
header = self.escape_text(class_name) if escape else class_name
|
|
608
|
+
parts.append(f"<h3>{header}</h3>\n<ul>\n{values}\n</ul>")
|
|
609
|
+
return "\n".join(parts)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _resolve_hocr_language(language: dict[str, Any]) -> str:
|
|
613
|
+
"""Resolve the language code to use in the hOCR export, falling back to 'en'.
|
|
614
|
+
|
|
615
|
+
Args:
|
|
616
|
+
language: the page language dictionary `{"value": str | None, "confidence": float | None}`
|
|
617
|
+
|
|
618
|
+
Returns:
|
|
619
|
+
the detected language code when available, 'en' otherwise
|
|
620
|
+
"""
|
|
621
|
+
lang_value = language.get("value") if isinstance(language, dict) else None
|
|
622
|
+
return lang_value if isinstance(lang_value, str) and len(lang_value) > 0 else "en"
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _hocr_bbox(geometry: BoundingBox, width: int, height: int) -> str:
|
|
626
|
+
"""Format a relative straight bounding box as an absolute hOCR `bbox` property string.
|
|
627
|
+
|
|
628
|
+
Args:
|
|
629
|
+
geometry: the relative bounding box ((xmin, ymin), (xmax, ymax))
|
|
630
|
+
width: the page width in pixels
|
|
631
|
+
height: the page height in pixels
|
|
632
|
+
|
|
633
|
+
Returns:
|
|
634
|
+
the hOCR `bbox` property string
|
|
635
|
+
"""
|
|
636
|
+
(xmin, ymin), (xmax, ymax) = geometry
|
|
637
|
+
return (
|
|
638
|
+
f"bbox {int(round(xmin * width))} {int(round(ymin * height))} "
|
|
639
|
+
f"{int(round(xmax * width))} {int(round(ymax * height))}"
|
|
640
|
+
)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
class XMLExporter:
|
|
644
|
+
"""hOCR (XML) exporter for pages, KIE pages and documents.
|
|
645
|
+
See the hOCR 1.2 specification for the XML convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
646
|
+
|
|
647
|
+
>>> from doctr.io import XMLExporter
|
|
648
|
+
>>> xml_bytes, xml_tree = XMLExporter().export_page(page)
|
|
649
|
+
"""
|
|
650
|
+
|
|
651
|
+
ocr_capabilities: ClassVar[str] = "ocr_page ocr_carea ocr_par ocr_line ocrx_word"
|
|
652
|
+
|
|
653
|
+
def _new_document(self, file_title: str, language: str) -> tuple[ETElement, ETElement]:
|
|
654
|
+
"""Create the hOCR root element with its <head>, returning the root and its <body> element."""
|
|
655
|
+
root = ETElement("html", attrib={"xmlns": "http://www.w3.org/1999/xhtml", "xml:lang": str(language)})
|
|
656
|
+
head = SubElement(root, "head")
|
|
657
|
+
SubElement(head, "title").text = file_title
|
|
658
|
+
SubElement(head, "meta", attrib={"http-equiv": "Content-Type", "content": "text/html; charset=utf-8"})
|
|
659
|
+
SubElement(
|
|
660
|
+
head,
|
|
661
|
+
"meta",
|
|
662
|
+
attrib={"name": "ocr-system", "content": f"python-doctr {doctr.__version__}"}, # type: ignore[attr-defined]
|
|
663
|
+
)
|
|
664
|
+
SubElement(head, "meta", attrib={"name": "ocr-capabilities", "content": self.ocr_capabilities})
|
|
665
|
+
return root, SubElement(root, "body")
|
|
666
|
+
|
|
667
|
+
def _add_table(self, page_div: ETElement, table: "Table", width: int, height: int, table_count: int) -> int:
|
|
668
|
+
"""Serialize a recognized table as an hOCR text area, with one `ocr_line` per row.
|
|
669
|
+
|
|
670
|
+
Args:
|
|
671
|
+
page_div: the `ocr_page` element the table is appended to
|
|
672
|
+
table: the table to serialize
|
|
673
|
+
width: the page width in pixels
|
|
674
|
+
height: the page height in pixels
|
|
675
|
+
table_count: the 1-based index of the table on the page
|
|
676
|
+
|
|
677
|
+
Returns:
|
|
678
|
+
the index of the next table
|
|
679
|
+
"""
|
|
680
|
+
if len(table.geometry) != 2 or any(len(cell.geometry) != 2 for cell in table.cells):
|
|
681
|
+
raise TypeError("XML export is only available for straight bounding boxes for now.")
|
|
682
|
+
table_bbox = _hocr_bbox(table.geometry, width, height) # type: ignore[arg-type]
|
|
683
|
+
table_div = SubElement(
|
|
684
|
+
page_div, "div", attrib={"class": "ocr_carea", "id": f"table_{table_count}", "title": table_bbox}
|
|
685
|
+
)
|
|
686
|
+
paragraph = SubElement(
|
|
687
|
+
table_div, "p", attrib={"class": "ocr_par", "id": f"table_par_{table_count}", "title": table_bbox}
|
|
688
|
+
)
|
|
689
|
+
rows: dict[int, list[Any]] = {}
|
|
690
|
+
for cell in table.cells:
|
|
691
|
+
rows.setdefault(cell.row_start, []).append(cell)
|
|
692
|
+
for row_idx in sorted(rows):
|
|
693
|
+
cells = sorted(rows[row_idx], key=lambda cell: cell.col_start)
|
|
694
|
+
xs = [coord for cell in cells for coord in (cell.geometry[0][0], cell.geometry[1][0])]
|
|
695
|
+
ys = [coord for cell in cells for coord in (cell.geometry[0][1], cell.geometry[1][1])]
|
|
696
|
+
row_bbox = _hocr_bbox(((min(xs), min(ys)), (max(xs), max(ys))), width, height)
|
|
697
|
+
line_span = SubElement(
|
|
698
|
+
paragraph,
|
|
699
|
+
"span",
|
|
700
|
+
attrib={
|
|
701
|
+
"class": "ocr_line",
|
|
702
|
+
"id": f"table_{table_count}_row_{row_idx + 1}",
|
|
703
|
+
"title": f"{row_bbox}; baseline 0 0; x_size 0; x_descenders 0; x_ascenders 0",
|
|
704
|
+
},
|
|
705
|
+
)
|
|
706
|
+
for col_idx, cell in enumerate(cells):
|
|
707
|
+
cell_span = SubElement(
|
|
708
|
+
line_span,
|
|
709
|
+
"span",
|
|
710
|
+
attrib={
|
|
711
|
+
"class": "ocrx_word",
|
|
712
|
+
"id": f"table_{table_count}_cell_{row_idx + 1}_{col_idx + 1}",
|
|
713
|
+
"title": (
|
|
714
|
+
f"{_hocr_bbox(cell.geometry, width, height)}; x_wconf {int(round(cell.confidence * 100))}"
|
|
715
|
+
),
|
|
716
|
+
},
|
|
717
|
+
)
|
|
718
|
+
cell_span.text = cell.value
|
|
719
|
+
return table_count + 1
|
|
720
|
+
|
|
721
|
+
def export_page(
|
|
722
|
+
self,
|
|
723
|
+
page: "Page",
|
|
724
|
+
file_title: str = "docTR - XML export (hOCR)",
|
|
725
|
+
direction: str = "auto",
|
|
726
|
+
reading_order: bool = True,
|
|
727
|
+
) -> tuple[bytes, ET.ElementTree]:
|
|
728
|
+
"""Export a page as hOCR XML, with its content sorted in reading order.
|
|
729
|
+
|
|
730
|
+
Args:
|
|
731
|
+
page: the page to export
|
|
732
|
+
file_title: the title of the XML file
|
|
733
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
734
|
+
reading_order: whether the content should be linearized in reading order. Pass False to serialize
|
|
735
|
+
`page.blocks` then `page.tables` in their raw order.
|
|
736
|
+
|
|
737
|
+
Returns:
|
|
738
|
+
a tuple of the XML byte string, and its ElementTree
|
|
739
|
+
"""
|
|
740
|
+
from doctr.io.elements import Table
|
|
741
|
+
|
|
742
|
+
block_count: int = 1
|
|
743
|
+
line_count: int = 1
|
|
744
|
+
word_count: int = 1
|
|
745
|
+
table_count: int = 1
|
|
746
|
+
height, width = page.dimensions
|
|
747
|
+
page_hocr, body = self._new_document(file_title, _resolve_hocr_language(page.language))
|
|
748
|
+
page_div = SubElement(
|
|
749
|
+
body,
|
|
750
|
+
"div",
|
|
751
|
+
attrib={
|
|
752
|
+
"class": "ocr_page",
|
|
753
|
+
"id": f"page_{page.page_idx + 1}",
|
|
754
|
+
"title": f"image; bbox 0 0 {width} {height}; ppageno 0",
|
|
755
|
+
},
|
|
756
|
+
)
|
|
757
|
+
auto = direction == "auto"
|
|
758
|
+
if reading_order:
|
|
759
|
+
items, _, direction = page_reading_order(page, direction)
|
|
760
|
+
else:
|
|
761
|
+
items = [*page.blocks, *page.tables]
|
|
762
|
+
# iterate over the blocks / lines / words and create the XML elements line by line with the attributes
|
|
763
|
+
for item in items:
|
|
764
|
+
if isinstance(item, Table):
|
|
765
|
+
table_count = self._add_table(page_div, item, width, height, table_count)
|
|
766
|
+
continue
|
|
767
|
+
block = item
|
|
768
|
+
if len(block.geometry) != 2:
|
|
769
|
+
raise TypeError("XML export is only available for straight bounding boxes for now.")
|
|
770
|
+
block_bbox = _hocr_bbox(block.geometry, width, height)
|
|
771
|
+
block_div = SubElement(
|
|
772
|
+
page_div,
|
|
773
|
+
"div",
|
|
774
|
+
attrib={"class": "ocr_carea", "id": f"block_{block_count}", "title": block_bbox},
|
|
775
|
+
)
|
|
776
|
+
paragraph = SubElement(
|
|
777
|
+
block_div,
|
|
778
|
+
"p",
|
|
779
|
+
attrib={"class": "ocr_par", "id": f"par_{block_count}", "title": block_bbox},
|
|
780
|
+
)
|
|
781
|
+
block_count += 1
|
|
782
|
+
for line in block.lines:
|
|
783
|
+
# NOTE: baseline, x_size, x_descenders, x_ascenders is currently initalized to 0
|
|
784
|
+
line_span = SubElement(
|
|
785
|
+
paragraph,
|
|
786
|
+
"span",
|
|
787
|
+
attrib={
|
|
788
|
+
"class": "ocr_line",
|
|
789
|
+
"id": f"line_{line_count}",
|
|
790
|
+
"title": (
|
|
791
|
+
f"{_hocr_bbox(line.geometry, width, height)}; "
|
|
792
|
+
"baseline 0 0; x_size 0; x_descenders 0; x_ascenders 0"
|
|
793
|
+
),
|
|
794
|
+
},
|
|
795
|
+
)
|
|
796
|
+
line_count += 1
|
|
797
|
+
for word in ordered_line_words(line, direction, auto):
|
|
798
|
+
word_div = SubElement(
|
|
799
|
+
line_span,
|
|
800
|
+
"span",
|
|
801
|
+
attrib={
|
|
802
|
+
"class": "ocrx_word",
|
|
803
|
+
"id": f"word_{word_count}",
|
|
804
|
+
"title": (
|
|
805
|
+
f"{_hocr_bbox(word.geometry, width, height)}; "
|
|
806
|
+
f"x_wconf {int(round(word.confidence * 100))}"
|
|
807
|
+
),
|
|
808
|
+
},
|
|
809
|
+
)
|
|
810
|
+
word_div.text = word.value
|
|
811
|
+
word_count += 1
|
|
812
|
+
return ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr)
|
|
813
|
+
|
|
814
|
+
def export_kie_page(
|
|
815
|
+
self,
|
|
816
|
+
page: "KIEPage",
|
|
817
|
+
file_title: str = "docTR - XML export (hOCR)",
|
|
818
|
+
direction: str = "auto",
|
|
819
|
+
reading_order: bool = True,
|
|
820
|
+
) -> tuple[bytes, ET.ElementTree]:
|
|
821
|
+
"""Export a KIE page as hOCR XML, with the predictions of each class sorted in reading order.
|
|
822
|
+
|
|
823
|
+
Args:
|
|
824
|
+
page: the KIE page to export
|
|
825
|
+
file_title: the title of the XML file
|
|
826
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
827
|
+
reading_order: whether the predictions of each class should be sorted in reading order
|
|
828
|
+
|
|
829
|
+
Returns:
|
|
830
|
+
a tuple of the XML byte string, and its ElementTree
|
|
831
|
+
"""
|
|
832
|
+
prediction_count: int = 1
|
|
833
|
+
height, width = page.dimensions
|
|
834
|
+
page_hocr, body = self._new_document(file_title, _resolve_hocr_language(page.language))
|
|
835
|
+
SubElement(
|
|
836
|
+
body,
|
|
837
|
+
"div",
|
|
838
|
+
attrib={
|
|
839
|
+
"class": "ocr_page",
|
|
840
|
+
"id": f"page_{page.page_idx + 1}",
|
|
841
|
+
"title": f"image; bbox 0 0 {width} {height}; ppageno 0",
|
|
842
|
+
},
|
|
843
|
+
)
|
|
844
|
+
# iterate over the predictions and create the XML elements line by line with the attributes
|
|
845
|
+
for class_name, predictions in page.predictions.items():
|
|
846
|
+
ordered = predictions_in_reading_order(page, predictions, direction) if reading_order else predictions
|
|
847
|
+
for prediction in ordered:
|
|
848
|
+
if len(prediction.geometry) != 2:
|
|
849
|
+
raise TypeError("XML export is only available for straight bounding boxes for now.")
|
|
850
|
+
prediction_bbox = _hocr_bbox(prediction.geometry, width, height) # type: ignore[arg-type]
|
|
851
|
+
prediction_div = SubElement(
|
|
852
|
+
body,
|
|
853
|
+
"div",
|
|
854
|
+
attrib={
|
|
855
|
+
"class": "ocr_carea",
|
|
856
|
+
"id": f"{class_name}_prediction_{prediction_count}",
|
|
857
|
+
"title": prediction_bbox,
|
|
858
|
+
},
|
|
859
|
+
)
|
|
860
|
+
# NOTE: ocr_par, ocr_line and ocrx_word are the same because the KIE predictions contain only words
|
|
861
|
+
# This is a workaround to make it PDF/A compatible
|
|
862
|
+
par_div = SubElement(
|
|
863
|
+
prediction_div,
|
|
864
|
+
"p",
|
|
865
|
+
attrib={
|
|
866
|
+
"class": "ocr_par",
|
|
867
|
+
"id": f"{class_name}_par_{prediction_count}",
|
|
868
|
+
"title": prediction_bbox,
|
|
869
|
+
},
|
|
870
|
+
)
|
|
871
|
+
line_span = SubElement(
|
|
872
|
+
par_div,
|
|
873
|
+
"span",
|
|
874
|
+
attrib={
|
|
875
|
+
"class": "ocr_line",
|
|
876
|
+
"id": f"{class_name}_line_{prediction_count}",
|
|
877
|
+
"title": f"{prediction_bbox}; baseline 0 0; x_size 0; x_descenders 0; x_ascenders 0",
|
|
878
|
+
},
|
|
879
|
+
)
|
|
880
|
+
word_div = SubElement(
|
|
881
|
+
line_span,
|
|
882
|
+
"span",
|
|
883
|
+
attrib={
|
|
884
|
+
"class": "ocrx_word",
|
|
885
|
+
"id": f"{class_name}_word_{prediction_count}",
|
|
886
|
+
"title": f"{prediction_bbox}; x_wconf {int(round(prediction.confidence * 100))}",
|
|
887
|
+
},
|
|
888
|
+
)
|
|
889
|
+
word_div.text = prediction.value
|
|
890
|
+
prediction_count += 1
|
|
891
|
+
return ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr)
|
|
892
|
+
|
|
893
|
+
def export_document(self, document: Any, **kwargs: Any) -> list[tuple[bytes, ET.ElementTree]]:
|
|
894
|
+
"""Export a document as a list of hOCR pages.
|
|
895
|
+
|
|
896
|
+
Args:
|
|
897
|
+
document: the document to export
|
|
898
|
+
**kwargs: additional keyword arguments passed to the page export
|
|
899
|
+
|
|
900
|
+
Returns:
|
|
901
|
+
list of tuple of (bytes, ElementTree), one per page
|
|
902
|
+
"""
|
|
903
|
+
from doctr.io.elements import KIEPage
|
|
904
|
+
|
|
905
|
+
return [
|
|
906
|
+
self.export_kie_page(page, **kwargs) if isinstance(page, KIEPage) else self.export_page(page, **kwargs)
|
|
907
|
+
for page in document.pages
|
|
908
|
+
]
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
class PageExportsMixin:
|
|
912
|
+
"""Export functionality of a :class:`~doctr.io.elements.Page`"""
|
|
913
|
+
|
|
914
|
+
if TYPE_CHECKING: # structural attributes provided by the element class
|
|
915
|
+
page: np.ndarray
|
|
916
|
+
blocks: list["Block"]
|
|
917
|
+
page_idx: int
|
|
918
|
+
dimensions: tuple[int, int]
|
|
919
|
+
orientation: dict[str, Any]
|
|
920
|
+
language: dict[str, Any]
|
|
921
|
+
layout: list[Any]
|
|
922
|
+
tables: list["Table"]
|
|
923
|
+
|
|
924
|
+
def render(self, block_break: str = "\n\n", direction: str = "auto", include_furniture: bool = True) -> str:
|
|
925
|
+
"""Renders the full text of the page, with its content sorted in reading order.
|
|
926
|
+
|
|
927
|
+
Args:
|
|
928
|
+
block_break: the string inserted between two blocks
|
|
929
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
930
|
+
include_furniture: whether page headers, page footers and footnotes should be included
|
|
931
|
+
|
|
932
|
+
Returns:
|
|
933
|
+
the text of the page
|
|
934
|
+
"""
|
|
935
|
+
return TextExporter().export_page(
|
|
936
|
+
cast("Page", self), direction=direction, include_furniture=include_furniture, block_break=block_break
|
|
937
|
+
)
|
|
938
|
+
|
|
939
|
+
def export(self, reading_order: bool = True) -> dict[str, Any]:
|
|
940
|
+
"""Export the page into a nested dict, with its content sorted in reading order.
|
|
941
|
+
|
|
942
|
+
Args:
|
|
943
|
+
reading_order: whether the blocks should be linearized in reading order, exactly like the
|
|
944
|
+
Markdown / HTML / AsciiDoc / hOCR exports. Pass False to serialize `page.blocks` as stored.
|
|
945
|
+
|
|
946
|
+
Returns:
|
|
947
|
+
a JSON-serializable dict
|
|
948
|
+
"""
|
|
949
|
+
from doctr.io.elements import Element, Table
|
|
950
|
+
|
|
951
|
+
export_dict = Element.export(cast("Element", self))
|
|
952
|
+
if reading_order:
|
|
953
|
+
blocks = [item for item in page_reading_order(cast("Page", self))[0] if not isinstance(item, Table)]
|
|
954
|
+
if blocks: # an empty linearization (no line on the page) leaves the stored blocks untouched
|
|
955
|
+
export_dict["blocks"] = [block.export() for block in blocks]
|
|
956
|
+
return export_dict
|
|
957
|
+
|
|
958
|
+
def export_as_xml(
|
|
959
|
+
self,
|
|
960
|
+
file_title: str = "docTR - XML export (hOCR)",
|
|
961
|
+
direction: str = "auto",
|
|
962
|
+
reading_order: bool = True,
|
|
963
|
+
) -> tuple[bytes, ET.ElementTree]:
|
|
964
|
+
"""Export the page as XML (hOCR-format), with its content sorted in reading order
|
|
965
|
+
convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
966
|
+
|
|
967
|
+
Args:
|
|
968
|
+
file_title: the title of the XML file
|
|
969
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
970
|
+
reading_order: whether the content should be linearized in reading order
|
|
971
|
+
|
|
972
|
+
Returns:
|
|
973
|
+
a tuple of the XML byte string, and its ElementTree
|
|
974
|
+
"""
|
|
975
|
+
return XMLExporter().export_page(
|
|
976
|
+
cast("Page", self), file_title=file_title, direction=direction, reading_order=reading_order
|
|
977
|
+
)
|
|
978
|
+
|
|
979
|
+
def items_in_reading_order(self, direction: str = "auto") -> list["Block | Table"]:
|
|
980
|
+
"""Return the content of the page (blocks & tables) sorted in reading order.
|
|
981
|
+
|
|
982
|
+
Args:
|
|
983
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
984
|
+
|
|
985
|
+
Returns:
|
|
986
|
+
list of blocks & tables in reading order
|
|
987
|
+
"""
|
|
988
|
+
return page_reading_order(cast("Page", self), direction)[0]
|
|
989
|
+
|
|
990
|
+
def export_as_markdown(self, direction: str = "auto", escape: bool = True, include_furniture: bool = True) -> str:
|
|
991
|
+
"""Export the page as Markdown, with its content sorted in reading order.
|
|
992
|
+
|
|
993
|
+
Args:
|
|
994
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
995
|
+
escape: whether the characters carrying a structural meaning in Markdown should be escaped
|
|
996
|
+
include_furniture: whether page headers, page footers and footnotes should be included
|
|
997
|
+
|
|
998
|
+
Returns:
|
|
999
|
+
a Markdown string
|
|
1000
|
+
"""
|
|
1001
|
+
return MarkdownExporter().export_page(
|
|
1002
|
+
cast("Page", self), direction=direction, escape=escape, include_furniture=include_furniture
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
def export_as_asciidoc(self, direction: str = "auto", escape: bool = True, include_furniture: bool = True) -> str:
|
|
1006
|
+
"""Export the page as AsciiDoc, with its content sorted in reading order.
|
|
1007
|
+
|
|
1008
|
+
Args:
|
|
1009
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1010
|
+
escape: whether the characters and line markers carrying a structural meaning in AsciiDoc should
|
|
1011
|
+
be escaped
|
|
1012
|
+
include_furniture: whether page headers, page footers and footnotes should be included
|
|
1013
|
+
|
|
1014
|
+
Returns:
|
|
1015
|
+
an AsciiDoc string
|
|
1016
|
+
"""
|
|
1017
|
+
return AsciiDocExporter().export_page(
|
|
1018
|
+
cast("Page", self), direction=direction, escape=escape, include_furniture=include_furniture
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
def export_as_html(self, direction: str = "auto", include_furniture: bool = True) -> str:
|
|
1022
|
+
"""Export the page as semantic HTML, with its content sorted in reading order.
|
|
1023
|
+
|
|
1024
|
+
Args:
|
|
1025
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1026
|
+
include_furniture: whether page headers, page footers and footnotes should be included
|
|
1027
|
+
|
|
1028
|
+
Returns:
|
|
1029
|
+
an HTML string
|
|
1030
|
+
"""
|
|
1031
|
+
return HTMLExporter().export_page(cast("Page", self), direction=direction, include_furniture=include_furniture)
|
|
1032
|
+
|
|
1033
|
+
def export_as(self, format: str, **kwargs: Any) -> Any:
|
|
1034
|
+
"""Export the page in the requested format.
|
|
1035
|
+
|
|
1036
|
+
Args:
|
|
1037
|
+
format: one of 'markdown'/'md', 'asciidoc'/'adoc', 'html', 'text'/'txt', 'json'/'dict',
|
|
1038
|
+
'xml'/'hocr'
|
|
1039
|
+
**kwargs: additional keyword arguments passed to the format-specific export method
|
|
1040
|
+
|
|
1041
|
+
Returns:
|
|
1042
|
+
the exported page
|
|
1043
|
+
"""
|
|
1044
|
+
exporters: dict[str, Any] = {
|
|
1045
|
+
"markdown": self.export_as_markdown,
|
|
1046
|
+
"md": self.export_as_markdown,
|
|
1047
|
+
"asciidoc": self.export_as_asciidoc,
|
|
1048
|
+
"adoc": self.export_as_asciidoc,
|
|
1049
|
+
"html": self.export_as_html,
|
|
1050
|
+
"text": self.render,
|
|
1051
|
+
"txt": self.render,
|
|
1052
|
+
"json": self.export,
|
|
1053
|
+
"dict": self.export,
|
|
1054
|
+
"xml": self.export_as_xml,
|
|
1055
|
+
"hocr": self.export_as_xml,
|
|
1056
|
+
}
|
|
1057
|
+
return _export_as(exporters, format, **kwargs)
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
class KIEPageExportsMixin:
|
|
1061
|
+
"""Export functionality of a :class:`~doctr.io.elements.KIEPage`"""
|
|
1062
|
+
|
|
1063
|
+
if TYPE_CHECKING: # structural attributes provided by the element class
|
|
1064
|
+
page: np.ndarray
|
|
1065
|
+
predictions: dict[str, list[Any]]
|
|
1066
|
+
page_idx: int
|
|
1067
|
+
dimensions: tuple[int, int]
|
|
1068
|
+
orientation: dict[str, Any]
|
|
1069
|
+
language: dict[str, Any]
|
|
1070
|
+
|
|
1071
|
+
def export(self, reading_order: bool = True) -> dict[str, Any]:
|
|
1072
|
+
"""Export the KIE page into a nested dict, with the predictions of each class in reading order.
|
|
1073
|
+
|
|
1074
|
+
Args:
|
|
1075
|
+
reading_order: whether the predictions of each class should be sorted in reading order
|
|
1076
|
+
|
|
1077
|
+
Returns:
|
|
1078
|
+
a JSON-serializable dict
|
|
1079
|
+
"""
|
|
1080
|
+
from doctr.io.elements import Element
|
|
1081
|
+
|
|
1082
|
+
export_dict = Element.export(cast("Element", self))
|
|
1083
|
+
if reading_order:
|
|
1084
|
+
export_dict["predictions"] = {
|
|
1085
|
+
class_name: [
|
|
1086
|
+
prediction.export()
|
|
1087
|
+
for prediction in predictions_in_reading_order(cast("KIEPage", self), predictions)
|
|
1088
|
+
]
|
|
1089
|
+
for class_name, predictions in self.predictions.items()
|
|
1090
|
+
}
|
|
1091
|
+
return export_dict
|
|
1092
|
+
|
|
1093
|
+
def render(self, prediction_break: str = "\n\n", direction: str = "auto") -> str:
|
|
1094
|
+
"""Renders the full text of the page, with the predictions of each class sorted in reading order.
|
|
1095
|
+
|
|
1096
|
+
Args:
|
|
1097
|
+
prediction_break: the string inserted between two predictions
|
|
1098
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1099
|
+
|
|
1100
|
+
Returns:
|
|
1101
|
+
the text of the page, one section per detection class with its predictions in reading order
|
|
1102
|
+
"""
|
|
1103
|
+
parts: list[str] = []
|
|
1104
|
+
for class_name, predictions in self.predictions.items():
|
|
1105
|
+
parts.extend(
|
|
1106
|
+
f"{class_name}: {prediction.render()}"
|
|
1107
|
+
for prediction in predictions_in_reading_order(cast("KIEPage", self), predictions, direction)
|
|
1108
|
+
)
|
|
1109
|
+
return prediction_break.join(parts)
|
|
1110
|
+
|
|
1111
|
+
def export_as_xml(
|
|
1112
|
+
self,
|
|
1113
|
+
file_title: str = "docTR - XML export (hOCR)",
|
|
1114
|
+
direction: str = "auto",
|
|
1115
|
+
reading_order: bool = True,
|
|
1116
|
+
) -> tuple[bytes, ET.ElementTree]:
|
|
1117
|
+
"""Export the page as XML (hOCR-format), with the predictions of each class in reading order
|
|
1118
|
+
convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
1119
|
+
|
|
1120
|
+
Args:
|
|
1121
|
+
file_title: the title of the XML file
|
|
1122
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1123
|
+
reading_order: whether the predictions of each class should be sorted in reading order
|
|
1124
|
+
|
|
1125
|
+
Returns:
|
|
1126
|
+
a tuple of the XML byte string, and its ElementTree
|
|
1127
|
+
"""
|
|
1128
|
+
return XMLExporter().export_kie_page(
|
|
1129
|
+
cast("KIEPage", self), file_title=file_title, direction=direction, reading_order=reading_order
|
|
1130
|
+
)
|
|
1131
|
+
|
|
1132
|
+
def export_as_markdown(self, direction: str = "auto", escape: bool = True) -> str:
|
|
1133
|
+
"""Export the KIE page as Markdown, with the predictions of each class sorted in reading order.
|
|
1134
|
+
|
|
1135
|
+
Args:
|
|
1136
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1137
|
+
escape: whether the characters carrying a structural meaning in Markdown should be escaped
|
|
1138
|
+
|
|
1139
|
+
Returns:
|
|
1140
|
+
a Markdown string with one section per detection class
|
|
1141
|
+
"""
|
|
1142
|
+
return MarkdownExporter().export_kie_page(cast("KIEPage", self), direction=direction, escape=escape)
|
|
1143
|
+
|
|
1144
|
+
def export_as_asciidoc(self, direction: str = "auto", escape: bool = True) -> str:
|
|
1145
|
+
"""Export the KIE page as AsciiDoc, with the predictions of each class sorted in reading order.
|
|
1146
|
+
|
|
1147
|
+
Args:
|
|
1148
|
+
direction: reading direction, one of 'auto', 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
1149
|
+
escape: whether the characters and line markers carrying a structural meaning in AsciiDoc should
|
|
1150
|
+
be escaped
|
|
1151
|
+
|
|
1152
|
+
Returns:
|
|
1153
|
+
an AsciiDoc string with one section per detection class
|
|
1154
|
+
"""
|
|
1155
|
+
return AsciiDocExporter().export_kie_page(cast("KIEPage", self), direction=direction, escape=escape)
|
|
1156
|
+
|
|
1157
|
+
def export_as_html(self, direction: str = "auto") -> str:
|
|
1158
|
+
"""Export the KIE page as semantic HTML, with the predictions of each class sorted in reading order"""
|
|
1159
|
+
return HTMLExporter().export_kie_page(cast("KIEPage", self), direction=direction)
|
|
1160
|
+
|
|
1161
|
+
def export_as(self, format: str, **kwargs: Any) -> Any:
|
|
1162
|
+
"""Export the KIE page in the requested format ('markdown'/'md', 'asciidoc'/'adoc', 'html',
|
|
1163
|
+
'text'/'txt', 'json'/'dict', 'xml'/'hocr')."""
|
|
1164
|
+
exporters: dict[str, Any] = {
|
|
1165
|
+
"markdown": self.export_as_markdown,
|
|
1166
|
+
"md": self.export_as_markdown,
|
|
1167
|
+
"asciidoc": self.export_as_asciidoc,
|
|
1168
|
+
"adoc": self.export_as_asciidoc,
|
|
1169
|
+
"html": self.export_as_html,
|
|
1170
|
+
"text": self.render,
|
|
1171
|
+
"txt": self.render,
|
|
1172
|
+
"json": self.export,
|
|
1173
|
+
"dict": self.export,
|
|
1174
|
+
"xml": self.export_as_xml,
|
|
1175
|
+
"hocr": self.export_as_xml,
|
|
1176
|
+
}
|
|
1177
|
+
return _export_as(exporters, format, **kwargs)
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
class DocumentExportsMixin:
|
|
1181
|
+
"""Export functionality of a :class:`~doctr.io.elements.Document` (also used by `KIEDocument`)"""
|
|
1182
|
+
|
|
1183
|
+
if TYPE_CHECKING: # structural attributes provided by the element class
|
|
1184
|
+
pages: list[Any]
|
|
1185
|
+
_exported_keys: list[str]
|
|
1186
|
+
|
|
1187
|
+
def render(self, page_break: str = "\n\n\n\n", **kwargs: Any) -> str:
|
|
1188
|
+
"""Renders the full text of the document, with the content of each page sorted in reading order.
|
|
1189
|
+
|
|
1190
|
+
Args:
|
|
1191
|
+
page_break: the string inserted between two pages
|
|
1192
|
+
**kwargs: additional keyword arguments passed to the `Page.render` / `KIEPage.render` method
|
|
1193
|
+
|
|
1194
|
+
Returns:
|
|
1195
|
+
the text of the document
|
|
1196
|
+
"""
|
|
1197
|
+
return page_break.join(page.render(**kwargs) for page in self.pages)
|
|
1198
|
+
|
|
1199
|
+
def export(self, reading_order: bool = True) -> dict[str, Any]:
|
|
1200
|
+
"""Export the document into a nested dict, with the content of each page sorted in reading order.
|
|
1201
|
+
|
|
1202
|
+
Args:
|
|
1203
|
+
reading_order: whether the content of each page should be linearized in reading order
|
|
1204
|
+
|
|
1205
|
+
Returns:
|
|
1206
|
+
a JSON-serializable dict
|
|
1207
|
+
"""
|
|
1208
|
+
export_dict: dict[str, Any] = {key: to_json_safe(getattr(self, key)) for key in self._exported_keys}
|
|
1209
|
+
export_dict["pages"] = [page.export(reading_order=reading_order) for page in self.pages]
|
|
1210
|
+
return export_dict
|
|
1211
|
+
|
|
1212
|
+
def export_as_xml(self, **kwargs: Any) -> list[tuple[bytes, ET.ElementTree]]:
|
|
1213
|
+
"""Export the document as XML (hOCR-format)
|
|
1214
|
+
|
|
1215
|
+
Args:
|
|
1216
|
+
**kwargs: additional keyword arguments passed to the XML page export
|
|
1217
|
+
|
|
1218
|
+
Returns:
|
|
1219
|
+
list of tuple of (bytes, ElementTree)
|
|
1220
|
+
"""
|
|
1221
|
+
return XMLExporter().export_document(self, **kwargs)
|
|
1222
|
+
|
|
1223
|
+
def export_as_markdown(self, page_break: str = "\n\n---\n\n", **kwargs: Any) -> str:
|
|
1224
|
+
"""Export the document as Markdown, with the content of each page sorted in reading order.
|
|
1225
|
+
|
|
1226
|
+
Args:
|
|
1227
|
+
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
|
|
1229
|
+
|
|
1230
|
+
Returns:
|
|
1231
|
+
a Markdown string
|
|
1232
|
+
"""
|
|
1233
|
+
return page_break.join(page.export_as_markdown(**kwargs) for page in self.pages)
|
|
1234
|
+
|
|
1235
|
+
def export_as_asciidoc(self, page_break: str = "\n\n<<<\n\n", **kwargs: Any) -> str:
|
|
1236
|
+
"""Export the document as AsciiDoc, with the content of each page sorted in reading order.
|
|
1237
|
+
|
|
1238
|
+
Args:
|
|
1239
|
+
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
|
|
1241
|
+
|
|
1242
|
+
Returns:
|
|
1243
|
+
an AsciiDoc string
|
|
1244
|
+
"""
|
|
1245
|
+
return page_break.join(page.export_as_asciidoc(**kwargs) for page in self.pages)
|
|
1246
|
+
|
|
1247
|
+
def export_as_html(self, page_break: str = "<hr>", **kwargs: Any) -> str:
|
|
1248
|
+
"""Export the document as semantic HTML, with the content of each page sorted in reading order.
|
|
1249
|
+
|
|
1250
|
+
Args:
|
|
1251
|
+
page_break: the HTML snippet inserted between two pages
|
|
1252
|
+
**kwargs: additional keyword arguments passed to the page export
|
|
1253
|
+
|
|
1254
|
+
Returns:
|
|
1255
|
+
an HTML string
|
|
1256
|
+
"""
|
|
1257
|
+
return page_break.join(page.export_as_html(**kwargs) for page in self.pages)
|
|
1258
|
+
|
|
1259
|
+
def export_as(self, format: str, **kwargs: Any) -> Any:
|
|
1260
|
+
"""Export the document in the requested format ('markdown'/'md', 'asciidoc'/'adoc', 'html',
|
|
1261
|
+
'text'/'txt', 'json'/'dict', 'xml'/'hocr')."""
|
|
1262
|
+
exporters: dict[str, Any] = {
|
|
1263
|
+
"markdown": self.export_as_markdown,
|
|
1264
|
+
"md": self.export_as_markdown,
|
|
1265
|
+
"asciidoc": self.export_as_asciidoc,
|
|
1266
|
+
"adoc": self.export_as_asciidoc,
|
|
1267
|
+
"html": self.export_as_html,
|
|
1268
|
+
"text": self.render,
|
|
1269
|
+
"txt": self.render,
|
|
1270
|
+
"json": self.export,
|
|
1271
|
+
"dict": self.export,
|
|
1272
|
+
"xml": self.export_as_xml,
|
|
1273
|
+
"hocr": self.export_as_xml,
|
|
1274
|
+
}
|
|
1275
|
+
return _export_as(exporters, format, **kwargs)
|