python-doctr 1.0.1__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +669 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +14 -3
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +121 -37
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +9 -7
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +129 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +5 -4
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +10 -8
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +104 -21
- doctr/datasets/vocabs.py +320 -148
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +3 -0
- doctr/io/elements.py +381 -271
- doctr/io/exporters.py +1915 -0
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -7
- doctr/io/image/pytorch.py +13 -5
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +3 -0
- doctr/models/_utils.py +206 -13
- doctr/models/builder.py +590 -137
- doctr/models/classification/__init__.py +3 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +34 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- 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 +14 -2
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +32 -18
- doctr/models/detection/differentiable_binarization/base.py +23 -9
- doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
- doctr/models/detection/fast/base.py +22 -6
- doctr/models/detection/fast/pytorch.py +24 -11
- doctr/models/detection/linknet/base.py +22 -6
- doctr/models/detection/linknet/pytorch.py +10 -3
- doctr/models/detection/predictor/pytorch.py +43 -2
- doctr/models/detection/zoo.py +6 -2
- doctr/models/factory/hub.py +59 -41
- 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 +23 -1
- doctr/models/kie_predictor/pytorch.py +87 -15
- 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 +895 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +114 -0
- doctr/models/layout/zoo.py +94 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +415 -17
- doctr/models/predictor/pytorch.py +109 -12
- doctr/models/preprocessor/pytorch.py +82 -25
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +1127 -0
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +40 -16
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +84 -22
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +126 -25
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +68 -12
- doctr/models/recognition/sar/pytorch.py +21 -7
- doctr/models/recognition/utils.py +80 -50
- doctr/models/recognition/viptr/pytorch.py +38 -14
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +11 -7
- doctr/models/recognition/zoo.py +36 -9
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +231 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +675 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
- doctr/models/table_structure/zoo.py +87 -0
- doctr/models/utils/pytorch.py +381 -25
- doctr/models/zoo.py +141 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +261 -82
- doctr/transforms/modules/pytorch.py +396 -76
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +24 -11
- doctr/utils/fonts.py +64 -17
- doctr/utils/geometry.py +167 -28
- doctr/utils/metrics.py +481 -19
- doctr/utils/multithreading.py +127 -4
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +73 -10
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
- python_doctr-1.2.0.dist-info/RECORD +191 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/io/elements.py
CHANGED
|
@@ -3,19 +3,14 @@
|
|
|
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
|
+
from collections.abc import Callable
|
|
7
|
+
from functools import cmp_to_key
|
|
6
8
|
from typing import Any
|
|
7
9
|
|
|
8
|
-
from defusedxml import defuse_stdlib
|
|
9
|
-
|
|
10
|
-
defuse_stdlib()
|
|
11
|
-
from xml.etree import ElementTree as ET
|
|
12
|
-
from xml.etree.ElementTree import Element as ETElement
|
|
13
|
-
from xml.etree.ElementTree import SubElement
|
|
14
|
-
|
|
15
10
|
import numpy as np
|
|
16
11
|
|
|
17
|
-
import doctr
|
|
18
12
|
from doctr.file_utils import requires_package
|
|
13
|
+
from doctr.io.exporters import DocumentExportsMixin, KIEPageExportsMixin, PageExportsMixin, to_json_safe
|
|
19
14
|
from doctr.utils.common_types import BoundingBox
|
|
20
15
|
from doctr.utils.geometry import resolve_enclosing_bbox, resolve_enclosing_rbbox
|
|
21
16
|
from doctr.utils.reconstitution import synthesize_kie_page, synthesize_page
|
|
@@ -23,10 +18,74 @@ from doctr.utils.repr import NestedObject
|
|
|
23
18
|
|
|
24
19
|
try: # optional dependency for visualization
|
|
25
20
|
from doctr.utils.visualization import visualize_kie_page, visualize_page
|
|
26
|
-
except ModuleNotFoundError:
|
|
21
|
+
except ModuleNotFoundError: # pragma: no cover
|
|
27
22
|
pass
|
|
28
23
|
|
|
29
|
-
__all__ = [
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Element",
|
|
26
|
+
"Word",
|
|
27
|
+
"Artefact",
|
|
28
|
+
"Line",
|
|
29
|
+
"Prediction",
|
|
30
|
+
"Block",
|
|
31
|
+
"Page",
|
|
32
|
+
"KIEPage",
|
|
33
|
+
"KIEDocument",
|
|
34
|
+
"Document",
|
|
35
|
+
"LayoutElement",
|
|
36
|
+
"TableCell",
|
|
37
|
+
"Table",
|
|
38
|
+
"Formula",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _empty_page_image(page: np.ndarray | None) -> np.ndarray:
|
|
43
|
+
"""Return the given page image, or an empty placeholder when the page was restored from an export."""
|
|
44
|
+
return page if page is not None else np.zeros((0, 0, 3), dtype=np.uint8)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# A page image, or a zero-argument callable decoding it on demand. Predictions made on a lazy page source
|
|
48
|
+
# (cf. `doctr.io.PageSource`) only keep a reference to their page, so that their memory footprint does not grow
|
|
49
|
+
# with the image of every page of a long document.
|
|
50
|
+
PageImage = np.ndarray | Callable[[], np.ndarray]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _get_page_image(self: Any) -> np.ndarray:
|
|
54
|
+
state = self.__dict__
|
|
55
|
+
if "_page" in state:
|
|
56
|
+
image = state["_page"]
|
|
57
|
+
elif "page" in state:
|
|
58
|
+
# Pages pickled by a previous release store their image under `page` (a plain instance attribute back then)
|
|
59
|
+
image = state["page"]
|
|
60
|
+
else:
|
|
61
|
+
raise AttributeError(f"'{type(self).__name__}' object has no attribute 'page'")
|
|
62
|
+
return image() if callable(image) else image
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _set_page_image(self: Any, image: PageImage) -> None:
|
|
66
|
+
# Drop the legacy entry of a page unpickled from a previous release, so that it cannot shadow the new image
|
|
67
|
+
self.__dict__.pop("page", None)
|
|
68
|
+
self._page = image
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
_page_image_property = property(
|
|
72
|
+
_get_page_image,
|
|
73
|
+
_set_page_image,
|
|
74
|
+
doc="the page image as a numpy array (decoded on access when the page was predicted from a lazy page source)",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _reading_order(a: "TableCell", b: "TableCell") -> int:
|
|
79
|
+
"""Compare 2 table cells in reading order: cells overlapping by half their height are on the same line and read
|
|
80
|
+
left to right, the other ones top to bottom."""
|
|
81
|
+
(ax0, ay0), (ax1, ay1) = (pts := np.asarray(a.geometry).reshape(-1, 2)).min(axis=0), pts.max(axis=0)
|
|
82
|
+
(bx0, by0), (bx1, by1) = (pts := np.asarray(b.geometry).reshape(-1, 2)).min(axis=0), pts.max(axis=0)
|
|
83
|
+
overlap = min(ay1, by1) - max(ay0, by0)
|
|
84
|
+
if overlap >= 0.5 * min(ay1 - ay0, by1 - by0):
|
|
85
|
+
delta = (ax0 + ax1) - (bx0 + bx1)
|
|
86
|
+
else:
|
|
87
|
+
delta = (ay0 + ay1) - (by0 + by1)
|
|
88
|
+
return int(np.sign(delta))
|
|
30
89
|
|
|
31
90
|
|
|
32
91
|
class Element(NestedObject):
|
|
@@ -44,7 +103,7 @@ class Element(NestedObject):
|
|
|
44
103
|
|
|
45
104
|
def export(self) -> dict[str, Any]:
|
|
46
105
|
"""Exports the object into a nested dict format"""
|
|
47
|
-
export_dict = {k: getattr(self, k) for k in self._exported_keys}
|
|
106
|
+
export_dict = {k: to_json_safe(getattr(self, k)) for k in self._exported_keys}
|
|
48
107
|
for children_name in self._children_names:
|
|
49
108
|
if children_name in ["predictions"]:
|
|
50
109
|
export_dict[children_name] = {
|
|
@@ -70,7 +129,7 @@ class Word(Element):
|
|
|
70
129
|
value: the text string of the word
|
|
71
130
|
confidence: the confidence associated with the text prediction
|
|
72
131
|
geometry: bounding box of the word in format ((xmin, ymin), (xmax, ymax)) where coordinates are relative to
|
|
73
|
-
|
|
132
|
+
the page's size
|
|
74
133
|
objectness_score: the objectness score of the detection
|
|
75
134
|
crop_orientation: the general orientation of the crop in degrees and its confidence
|
|
76
135
|
"""
|
|
@@ -126,8 +185,39 @@ class Artefact(Element):
|
|
|
126
185
|
self.confidence = confidence
|
|
127
186
|
|
|
128
187
|
def render(self) -> str:
|
|
129
|
-
"""Renders the
|
|
130
|
-
return f"[{self.type.upper()}]"
|
|
188
|
+
"""Renders the region as a tag"""
|
|
189
|
+
return f"<[{self.type.upper()}]>"
|
|
190
|
+
|
|
191
|
+
def extra_repr(self) -> str:
|
|
192
|
+
return f"type='{self.type}', confidence={self.confidence:.2}"
|
|
193
|
+
|
|
194
|
+
@classmethod
|
|
195
|
+
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
196
|
+
return cls(artefact_type=save_dict["type"], confidence=save_dict["confidence"], geometry=save_dict["geometry"])
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class LayoutElement(Element):
|
|
200
|
+
"""Implements a layout region predicted by a layout detection model
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
layout_type: the predicted region class (e.g. 'Title', 'Text', 'Table', 'Page-header')
|
|
204
|
+
confidence: the confidence of the region prediction
|
|
205
|
+
geometry: bounding box of the word in format ((xmin, ymin), (xmax, ymax)) where coordinates are relative to
|
|
206
|
+
the page's size
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
_exported_keys: list[str] = ["geometry", "type", "confidence"]
|
|
210
|
+
_children_names: list[str] = []
|
|
211
|
+
|
|
212
|
+
def __init__(self, layout_type: str, confidence: float, geometry: BoundingBox | np.ndarray) -> None:
|
|
213
|
+
super().__init__()
|
|
214
|
+
self.geometry = geometry
|
|
215
|
+
self.type = layout_type
|
|
216
|
+
self.confidence = confidence
|
|
217
|
+
|
|
218
|
+
def render(self) -> str:
|
|
219
|
+
"""Renders the region as a tag"""
|
|
220
|
+
return f"<[{self.type.upper()}]>"
|
|
131
221
|
|
|
132
222
|
def extra_repr(self) -> str:
|
|
133
223
|
return f"type='{self.type}', confidence={self.confidence:.2}"
|
|
@@ -135,9 +225,191 @@ class Artefact(Element):
|
|
|
135
225
|
@classmethod
|
|
136
226
|
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
137
227
|
kwargs = {k: save_dict[k] for k in cls._exported_keys}
|
|
228
|
+
return cls(layout_type=kwargs["type"], confidence=kwargs["confidence"], geometry=kwargs["geometry"])
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class TableCell(Element):
|
|
232
|
+
"""Implements a single cell of a recognized table
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
value: the text content of the cell (words assigned to the cell, joined together)
|
|
236
|
+
confidence: the mean recognition confidence of the words assigned to the cell (its `objectness_score` if
|
|
237
|
+
no word is assigned to it)
|
|
238
|
+
geometry: bounding box of the cell in format ((xmin, ymin), (xmax, ymax)) or a (4, 2) polygon,
|
|
239
|
+
with coordinates relative to the page's size
|
|
240
|
+
row_start: index of the first row spanned by the cell (0-indexed)
|
|
241
|
+
row_end: index of the last row spanned by the cell (0-indexed, inclusive)
|
|
242
|
+
col_start: index of the first column spanned by the cell (0-indexed)
|
|
243
|
+
col_end: index of the last column spanned by the cell (0-indexed, inclusive)
|
|
244
|
+
objectness_score: the score of the cell predicted by the table structure model, None if unknown
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
_exported_keys: list[str] = [
|
|
248
|
+
"geometry",
|
|
249
|
+
"value",
|
|
250
|
+
"confidence",
|
|
251
|
+
"row_start",
|
|
252
|
+
"row_end",
|
|
253
|
+
"col_start",
|
|
254
|
+
"col_end",
|
|
255
|
+
"objectness_score",
|
|
256
|
+
]
|
|
257
|
+
_children_names: list[str] = []
|
|
258
|
+
|
|
259
|
+
def __init__(
|
|
260
|
+
self,
|
|
261
|
+
value: str,
|
|
262
|
+
confidence: float,
|
|
263
|
+
geometry: BoundingBox | np.ndarray,
|
|
264
|
+
row_start: int,
|
|
265
|
+
row_end: int,
|
|
266
|
+
col_start: int,
|
|
267
|
+
col_end: int,
|
|
268
|
+
objectness_score: float | None = None,
|
|
269
|
+
) -> None:
|
|
270
|
+
super().__init__()
|
|
271
|
+
self.value = value
|
|
272
|
+
self.confidence = confidence
|
|
273
|
+
self.geometry = geometry
|
|
274
|
+
self.row_start = row_start
|
|
275
|
+
self.row_end = row_end
|
|
276
|
+
self.col_start = col_start
|
|
277
|
+
self.col_end = col_end
|
|
278
|
+
self.objectness_score = objectness_score
|
|
279
|
+
|
|
280
|
+
@property
|
|
281
|
+
def row_span(self) -> int:
|
|
282
|
+
"""Number of rows spanned by the cell"""
|
|
283
|
+
return self.row_end - self.row_start + 1
|
|
284
|
+
|
|
285
|
+
@property
|
|
286
|
+
def col_span(self) -> int:
|
|
287
|
+
"""Number of columns spanned by the cell"""
|
|
288
|
+
return self.col_end - self.col_start + 1
|
|
289
|
+
|
|
290
|
+
def render(self) -> str:
|
|
291
|
+
"""Renders the cell text"""
|
|
292
|
+
return self.value
|
|
293
|
+
|
|
294
|
+
def extra_repr(self) -> str:
|
|
295
|
+
return f"value='{self.value}', rows=({self.row_start}, {self.row_end}), cols=({self.col_start}, {self.col_end})"
|
|
296
|
+
|
|
297
|
+
@classmethod
|
|
298
|
+
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
299
|
+
# `objectness_score` is missing from the exports of earlier versions
|
|
300
|
+
kwargs = {k: save_dict[k] for k in cls._exported_keys if k != "objectness_score"}
|
|
301
|
+
return cls(**kwargs, objectness_score=save_dict.get("objectness_score"))
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class Table(Element):
|
|
305
|
+
"""Implements a table recognized on a page as a grid of cells
|
|
306
|
+
|
|
307
|
+
The recognized text of the words falling inside the table is regrouped here and removed from the
|
|
308
|
+
regular `blocks` output of the page, so it is not duplicated. The structured content can be loaded
|
|
309
|
+
directly into pandas, e.g. `pd.DataFrame(table.to_grid())`.
|
|
310
|
+
|
|
311
|
+
Args:
|
|
312
|
+
cells: list of `TableCell` objects composing the table
|
|
313
|
+
num_rows: number of rows of the table
|
|
314
|
+
num_cols: number of columns of the table
|
|
315
|
+
geometry: bounding box enclosing the whole table, with coordinates relative to the page's size
|
|
316
|
+
confidence: the confidence of the table structure prediction (mean of the `objectness_score` of its cells)
|
|
317
|
+
"""
|
|
318
|
+
|
|
319
|
+
_exported_keys: list[str] = ["geometry", "num_rows", "num_cols", "confidence"]
|
|
320
|
+
_children_names: list[str] = ["cells"]
|
|
321
|
+
cells: list[TableCell] = []
|
|
322
|
+
|
|
323
|
+
def __init__(
|
|
324
|
+
self,
|
|
325
|
+
cells: list[TableCell],
|
|
326
|
+
num_rows: int,
|
|
327
|
+
num_cols: int,
|
|
328
|
+
geometry: BoundingBox | np.ndarray,
|
|
329
|
+
confidence: float = 1.0,
|
|
330
|
+
) -> None:
|
|
331
|
+
super().__init__(cells=cells)
|
|
332
|
+
self.num_rows = num_rows
|
|
333
|
+
self.num_cols = num_cols
|
|
334
|
+
self.geometry = geometry
|
|
335
|
+
self.confidence = confidence
|
|
336
|
+
|
|
337
|
+
def to_grid(self) -> list[list[str]]:
|
|
338
|
+
"""Return the table content as a dense `num_rows` x `num_cols` grid of strings.
|
|
339
|
+
|
|
340
|
+
Cells spanning several rows/columns have their value placed at their top-left position; the
|
|
341
|
+
remaining positions they span are left empty. Cells sharing the same top-left position have their
|
|
342
|
+
values joined in reading order, so no text is lost. The result is directly loadable into pandas via
|
|
343
|
+
`pd.DataFrame(table.to_grid())`.
|
|
344
|
+
|
|
345
|
+
Returns:
|
|
346
|
+
a list of `num_rows` lists, each of length `num_cols`
|
|
347
|
+
"""
|
|
348
|
+
grid = [["" for _ in range(self.num_cols)] for _ in range(self.num_rows)]
|
|
349
|
+
for cell in sorted(self.cells, key=cmp_to_key(_reading_order)):
|
|
350
|
+
if 0 <= cell.row_start < self.num_rows and 0 <= cell.col_start < self.num_cols and cell.value:
|
|
351
|
+
current = grid[cell.row_start][cell.col_start]
|
|
352
|
+
grid[cell.row_start][cell.col_start] = f"{current} {cell.value}" if current else cell.value
|
|
353
|
+
return grid
|
|
354
|
+
|
|
355
|
+
def render(self, row_break: str = "\n", col_break: str = "\t") -> str:
|
|
356
|
+
"""Renders the table as plain text (tab-separated values)"""
|
|
357
|
+
return row_break.join(col_break.join(row) for row in self.to_grid())
|
|
358
|
+
|
|
359
|
+
def extra_repr(self) -> str:
|
|
360
|
+
return f"num_rows={self.num_rows}, num_cols={self.num_cols}, confidence={self.confidence:.2}"
|
|
361
|
+
|
|
362
|
+
@classmethod
|
|
363
|
+
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
364
|
+
kwargs = {k: save_dict[k] for k in cls._exported_keys}
|
|
365
|
+
kwargs["cells"] = [TableCell.from_dict(cell) for cell in save_dict["cells"]]
|
|
138
366
|
return cls(**kwargs)
|
|
139
367
|
|
|
140
368
|
|
|
369
|
+
class Formula(Element):
|
|
370
|
+
r"""Implements a mathematical formula recognized on a page as LaTeX
|
|
371
|
+
|
|
372
|
+
The formula regions are located by the layout model and kept out of the regular text recognition, so the
|
|
373
|
+
formula is not duplicated in the `blocks` of the page.
|
|
374
|
+
|
|
375
|
+
Args:
|
|
376
|
+
value: the LaTeX source of the formula (tokens separated by spaces, e.g. `\frac { a } { b }`), without
|
|
377
|
+
math delimiters
|
|
378
|
+
confidence: the confidence of the formula recognition
|
|
379
|
+
geometry: bounding box of the formula in format ((xmin, ymin), (xmax, ymax)) or a (4, 2) polygon, with
|
|
380
|
+
coordinates relative to the page's size
|
|
381
|
+
objectness_score: the score of the formula region predicted by the layout model, None if unknown
|
|
382
|
+
"""
|
|
383
|
+
|
|
384
|
+
_exported_keys: list[str] = ["geometry", "value", "confidence", "objectness_score"]
|
|
385
|
+
_children_names: list[str] = []
|
|
386
|
+
|
|
387
|
+
def __init__(
|
|
388
|
+
self,
|
|
389
|
+
value: str,
|
|
390
|
+
confidence: float,
|
|
391
|
+
geometry: BoundingBox | np.ndarray,
|
|
392
|
+
objectness_score: float | None = None,
|
|
393
|
+
) -> None:
|
|
394
|
+
super().__init__()
|
|
395
|
+
self.value = value
|
|
396
|
+
self.confidence = confidence
|
|
397
|
+
self.geometry = geometry
|
|
398
|
+
self.objectness_score = objectness_score
|
|
399
|
+
|
|
400
|
+
def render(self) -> str:
|
|
401
|
+
"""Renders the LaTeX source of the formula"""
|
|
402
|
+
return self.value
|
|
403
|
+
|
|
404
|
+
def extra_repr(self) -> str:
|
|
405
|
+
return f"value='{self.value}', confidence={self.confidence:.2}"
|
|
406
|
+
|
|
407
|
+
@classmethod
|
|
408
|
+
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
409
|
+
kwargs = {k: save_dict[k] for k in cls._exported_keys if k != "objectness_score"}
|
|
410
|
+
return cls(**kwargs, objectness_score=save_dict.get("objectness_score"))
|
|
411
|
+
|
|
412
|
+
|
|
141
413
|
class Line(Element):
|
|
142
414
|
"""Implements a line element as a collection of words
|
|
143
415
|
|
|
@@ -158,6 +430,8 @@ class Line(Element):
|
|
|
158
430
|
geometry: BoundingBox | np.ndarray | None = None,
|
|
159
431
|
objectness_score: float | None = None,
|
|
160
432
|
) -> None:
|
|
433
|
+
if geometry is None and not words:
|
|
434
|
+
raise ValueError("the geometry of a line without any word can not be resolved, please pass it")
|
|
161
435
|
# Compute the objectness score of the line
|
|
162
436
|
if objectness_score is None:
|
|
163
437
|
objectness_score = float(np.mean([w.objectness_score for w in words]))
|
|
@@ -213,21 +487,29 @@ class Block(Element):
|
|
|
213
487
|
|
|
214
488
|
def __init__(
|
|
215
489
|
self,
|
|
216
|
-
lines: list[Line] =
|
|
217
|
-
artefacts: list[Artefact] =
|
|
490
|
+
lines: list[Line] | None = None,
|
|
491
|
+
artefacts: list[Artefact] | None = None,
|
|
218
492
|
geometry: BoundingBox | np.ndarray | None = None,
|
|
219
493
|
objectness_score: float | None = None,
|
|
220
494
|
) -> None:
|
|
221
|
-
|
|
495
|
+
if lines is None:
|
|
496
|
+
lines = []
|
|
497
|
+
if artefacts is None:
|
|
498
|
+
artefacts = []
|
|
499
|
+
if geometry is None and not lines and not artefacts:
|
|
500
|
+
raise ValueError("the geometry of a block without any line or artefact can not be resolved, please pass it")
|
|
501
|
+
# Compute the objectness score of the block
|
|
222
502
|
if objectness_score is None:
|
|
223
|
-
|
|
503
|
+
# A block without any word (only artefacts) takes the confidence of its artefacts, instead of NaN
|
|
504
|
+
scores = [w.objectness_score for line in lines for w in line.words] or [a.confidence for a in artefacts]
|
|
505
|
+
objectness_score = float(np.mean(scores))
|
|
224
506
|
# Resolve the geometry using the smallest enclosing bounding box
|
|
225
507
|
if geometry is None:
|
|
226
508
|
line_boxes = [word.geometry for line in lines for word in line.words]
|
|
227
509
|
artefact_boxes = [artefact.geometry for artefact in artefacts]
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
)
|
|
510
|
+
# Check whether this is a rotated or straight box (geometries read back from an export are lists)
|
|
511
|
+
first_geometry = lines[0].geometry if lines else artefacts[0].geometry
|
|
512
|
+
box_resolution_fn = resolve_enclosing_rbbox if len(first_geometry) == 4 else resolve_enclosing_bbox
|
|
231
513
|
geometry = box_resolution_fn(line_boxes + artefact_boxes) # type: ignore
|
|
232
514
|
|
|
233
515
|
super().__init__(lines=lines, artefacts=artefacts)
|
|
@@ -248,42 +530,54 @@ class Block(Element):
|
|
|
248
530
|
return cls(**kwargs)
|
|
249
531
|
|
|
250
532
|
|
|
251
|
-
class Page(Element):
|
|
533
|
+
class Page(PageExportsMixin, Element):
|
|
252
534
|
"""Implements a page element as a collection of blocks
|
|
253
535
|
|
|
254
536
|
Args:
|
|
255
|
-
page: image encoded as a numpy array in uint8
|
|
537
|
+
page: image encoded as a numpy array in uint8, or a callable returning it (decoded on access)
|
|
256
538
|
blocks: list of block elements
|
|
257
539
|
page_idx: the index of the page in the input raw document
|
|
258
540
|
dimensions: the page size in pixels in format (height, width)
|
|
259
541
|
orientation: a dictionary with the value of the rotation angle in degress and confidence of the prediction
|
|
260
542
|
language: a dictionary with the language value and confidence of the prediction
|
|
543
|
+
layout: optional list of layout regions detected on the page
|
|
544
|
+
tables: optional list of tables recognized on the page. Words assigned to a table are removed from `blocks`.
|
|
545
|
+
formulas: optional list of formulas recognized on the page. Formula regions are not part of `blocks`.
|
|
261
546
|
"""
|
|
262
547
|
|
|
263
548
|
_exported_keys: list[str] = ["page_idx", "dimensions", "orientation", "language"]
|
|
264
|
-
_children_names: list[str] = ["blocks"]
|
|
549
|
+
_children_names: list[str] = ["blocks", "layout", "tables", "formulas"]
|
|
265
550
|
blocks: list[Block] = []
|
|
551
|
+
layout: list[LayoutElement] = []
|
|
552
|
+
tables: list[Table] = []
|
|
553
|
+
formulas: list[Formula] = []
|
|
554
|
+
|
|
555
|
+
page = _page_image_property
|
|
266
556
|
|
|
267
557
|
def __init__(
|
|
268
558
|
self,
|
|
269
|
-
page:
|
|
559
|
+
page: PageImage,
|
|
270
560
|
blocks: list[Block],
|
|
271
561
|
page_idx: int,
|
|
272
562
|
dimensions: tuple[int, int],
|
|
273
563
|
orientation: dict[str, Any] | None = None,
|
|
274
564
|
language: dict[str, Any] | None = None,
|
|
565
|
+
layout: list[LayoutElement] | None = None,
|
|
566
|
+
tables: list[Table] | None = None,
|
|
567
|
+
formulas: list[Formula] | None = None,
|
|
275
568
|
) -> None:
|
|
276
|
-
super().__init__(
|
|
569
|
+
super().__init__(
|
|
570
|
+
blocks=blocks,
|
|
571
|
+
layout=layout if layout is not None else [],
|
|
572
|
+
tables=tables if tables is not None else [],
|
|
573
|
+
formulas=formulas if formulas is not None else [],
|
|
574
|
+
)
|
|
277
575
|
self.page = page
|
|
278
576
|
self.page_idx = page_idx
|
|
279
577
|
self.dimensions = dimensions
|
|
280
578
|
self.orientation = orientation if isinstance(orientation, dict) else dict(value=None, confidence=None)
|
|
281
579
|
self.language = language if isinstance(language, dict) else dict(value=None, confidence=None)
|
|
282
580
|
|
|
283
|
-
def render(self, block_break: str = "\n\n") -> str:
|
|
284
|
-
"""Renders the full text of the element"""
|
|
285
|
-
return block_break.join(b.render() for b in self.blocks)
|
|
286
|
-
|
|
287
581
|
def extra_repr(self) -> str:
|
|
288
582
|
return f"dimensions={self.dimensions}"
|
|
289
583
|
|
|
@@ -294,12 +588,20 @@ class Page(Element):
|
|
|
294
588
|
interactive: whether the display should be interactive
|
|
295
589
|
preserve_aspect_ratio: pass True if you passed True to the predictor
|
|
296
590
|
**kwargs: additional keyword arguments passed to the matplotlib.pyplot.show method
|
|
591
|
+
(e.g. `display_layout=False` to hide detected layout regions)
|
|
297
592
|
"""
|
|
298
593
|
requires_package("matplotlib", "`.show()` requires matplotlib & mplcursors installed")
|
|
299
594
|
requires_package("mplcursors", "`.show()` requires matplotlib & mplcursors installed")
|
|
300
595
|
import matplotlib.pyplot as plt
|
|
301
596
|
|
|
302
|
-
|
|
597
|
+
show_kwargs = {k: kwargs.pop(k) for k in ("words_only", "display_artefacts", "display_layout") if k in kwargs}
|
|
598
|
+
visualize_page(
|
|
599
|
+
self.export(),
|
|
600
|
+
self.page,
|
|
601
|
+
interactive=interactive,
|
|
602
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
603
|
+
**show_kwargs,
|
|
604
|
+
)
|
|
303
605
|
plt.show(**kwargs)
|
|
304
606
|
|
|
305
607
|
def synthesize(self, **kwargs) -> np.ndarray:
|
|
@@ -313,155 +615,56 @@ class Page(Element):
|
|
|
313
615
|
"""
|
|
314
616
|
return synthesize_page(self.export(), **kwargs)
|
|
315
617
|
|
|
316
|
-
def export_as_xml(self, file_title: str = "docTR - XML export (hOCR)") -> tuple[bytes, ET.ElementTree]:
|
|
317
|
-
"""Export the page as XML (hOCR-format)
|
|
318
|
-
convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
319
|
-
|
|
320
|
-
Args:
|
|
321
|
-
file_title: the title of the XML file
|
|
322
|
-
|
|
323
|
-
Returns:
|
|
324
|
-
a tuple of the XML byte string, and its ElementTree
|
|
325
|
-
"""
|
|
326
|
-
p_idx = self.page_idx
|
|
327
|
-
block_count: int = 1
|
|
328
|
-
line_count: int = 1
|
|
329
|
-
word_count: int = 1
|
|
330
|
-
height, width = self.dimensions
|
|
331
|
-
language = self.language if "language" in self.language.keys() else "en"
|
|
332
|
-
# Create the XML root element
|
|
333
|
-
page_hocr = ETElement("html", attrib={"xmlns": "http://www.w3.org/1999/xhtml", "xml:lang": str(language)})
|
|
334
|
-
# Create the header / SubElements of the root element
|
|
335
|
-
head = SubElement(page_hocr, "head")
|
|
336
|
-
SubElement(head, "title").text = file_title
|
|
337
|
-
SubElement(head, "meta", attrib={"http-equiv": "Content-Type", "content": "text/html; charset=utf-8"})
|
|
338
|
-
SubElement(
|
|
339
|
-
head,
|
|
340
|
-
"meta",
|
|
341
|
-
attrib={"name": "ocr-system", "content": f"python-doctr {doctr.__version__}"}, # type: ignore[attr-defined]
|
|
342
|
-
)
|
|
343
|
-
SubElement(
|
|
344
|
-
head,
|
|
345
|
-
"meta",
|
|
346
|
-
attrib={"name": "ocr-capabilities", "content": "ocr_page ocr_carea ocr_par ocr_line ocrx_word"},
|
|
347
|
-
)
|
|
348
|
-
# Create the body
|
|
349
|
-
body = SubElement(page_hocr, "body")
|
|
350
|
-
page_div = SubElement(
|
|
351
|
-
body,
|
|
352
|
-
"div",
|
|
353
|
-
attrib={
|
|
354
|
-
"class": "ocr_page",
|
|
355
|
-
"id": f"page_{p_idx + 1}",
|
|
356
|
-
"title": f"image; bbox 0 0 {width} {height}; ppageno 0",
|
|
357
|
-
},
|
|
358
|
-
)
|
|
359
|
-
# iterate over the blocks / lines / words and create the XML elements in body line by line with the attributes
|
|
360
|
-
for block in self.blocks:
|
|
361
|
-
if len(block.geometry) != 2:
|
|
362
|
-
raise TypeError("XML export is only available for straight bounding boxes for now.")
|
|
363
|
-
(xmin, ymin), (xmax, ymax) = block.geometry
|
|
364
|
-
block_div = SubElement(
|
|
365
|
-
page_div,
|
|
366
|
-
"div",
|
|
367
|
-
attrib={
|
|
368
|
-
"class": "ocr_carea",
|
|
369
|
-
"id": f"block_{block_count}",
|
|
370
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
371
|
-
{int(round(xmax * width))} {int(round(ymax * height))}",
|
|
372
|
-
},
|
|
373
|
-
)
|
|
374
|
-
paragraph = SubElement(
|
|
375
|
-
block_div,
|
|
376
|
-
"p",
|
|
377
|
-
attrib={
|
|
378
|
-
"class": "ocr_par",
|
|
379
|
-
"id": f"par_{block_count}",
|
|
380
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
381
|
-
{int(round(xmax * width))} {int(round(ymax * height))}",
|
|
382
|
-
},
|
|
383
|
-
)
|
|
384
|
-
block_count += 1
|
|
385
|
-
for line in block.lines:
|
|
386
|
-
(xmin, ymin), (xmax, ymax) = line.geometry
|
|
387
|
-
# NOTE: baseline, x_size, x_descenders, x_ascenders is currently initalized to 0
|
|
388
|
-
line_span = SubElement(
|
|
389
|
-
paragraph,
|
|
390
|
-
"span",
|
|
391
|
-
attrib={
|
|
392
|
-
"class": "ocr_line",
|
|
393
|
-
"id": f"line_{line_count}",
|
|
394
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
395
|
-
{int(round(xmax * width))} {int(round(ymax * height))}; \
|
|
396
|
-
baseline 0 0; x_size 0; x_descenders 0; x_ascenders 0",
|
|
397
|
-
},
|
|
398
|
-
)
|
|
399
|
-
line_count += 1
|
|
400
|
-
for word in line.words:
|
|
401
|
-
(xmin, ymin), (xmax, ymax) = word.geometry
|
|
402
|
-
conf = word.confidence
|
|
403
|
-
word_div = SubElement(
|
|
404
|
-
line_span,
|
|
405
|
-
"span",
|
|
406
|
-
attrib={
|
|
407
|
-
"class": "ocrx_word",
|
|
408
|
-
"id": f"word_{word_count}",
|
|
409
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
410
|
-
{int(round(xmax * width))} {int(round(ymax * height))}; \
|
|
411
|
-
x_wconf {int(round(conf * 100))}",
|
|
412
|
-
},
|
|
413
|
-
)
|
|
414
|
-
# set the text
|
|
415
|
-
word_div.text = word.value
|
|
416
|
-
word_count += 1
|
|
417
|
-
|
|
418
|
-
return (ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr))
|
|
419
|
-
|
|
420
618
|
@classmethod
|
|
421
|
-
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
619
|
+
def from_dict(cls, save_dict: dict[str, Any], page: np.ndarray | None = None, **kwargs):
|
|
620
|
+
_kwargs: dict[str, Any] = {k: save_dict[k] for k in cls._exported_keys}
|
|
621
|
+
_kwargs.update({
|
|
622
|
+
"blocks": [Block.from_dict(block_dict) for block_dict in save_dict["blocks"]],
|
|
623
|
+
"layout": [LayoutElement.from_dict(region_dict) for region_dict in save_dict.get("layout", [])],
|
|
624
|
+
"tables": [Table.from_dict(table_dict) for table_dict in save_dict.get("tables", [])],
|
|
625
|
+
"formulas": [Formula.from_dict(formula_dict) for formula_dict in save_dict.get("formulas", [])],
|
|
626
|
+
})
|
|
627
|
+
# The page image is not part of the export: pass it back explicitly to restore a fully usable page
|
|
628
|
+
return cls(page=_empty_page_image(page), **_kwargs)
|
|
425
629
|
|
|
426
630
|
|
|
427
|
-
class KIEPage(Element):
|
|
631
|
+
class KIEPage(KIEPageExportsMixin, Element):
|
|
428
632
|
"""Implements a KIE page element as a collection of predictions
|
|
429
633
|
|
|
430
634
|
Args:
|
|
431
635
|
predictions: Dictionary with list of block elements for each detection class
|
|
432
|
-
page: image encoded as a numpy array in uint8
|
|
636
|
+
page: image encoded as a numpy array in uint8, or a callable returning it (decoded on access)
|
|
433
637
|
page_idx: the index of the page in the input raw document
|
|
434
638
|
dimensions: the page size in pixels in format (height, width)
|
|
435
639
|
orientation: a dictionary with the value of the rotation angle in degress and confidence of the prediction
|
|
436
640
|
language: a dictionary with the language value and confidence of the prediction
|
|
641
|
+
layout: optional list of layout regions detected on the page
|
|
437
642
|
"""
|
|
438
643
|
|
|
439
644
|
_exported_keys: list[str] = ["page_idx", "dimensions", "orientation", "language"]
|
|
440
|
-
_children_names: list[str] = ["predictions"]
|
|
645
|
+
_children_names: list[str] = ["predictions", "layout"]
|
|
441
646
|
predictions: dict[str, list[Prediction]] = {}
|
|
647
|
+
layout: list[LayoutElement] = []
|
|
648
|
+
|
|
649
|
+
page = _page_image_property
|
|
442
650
|
|
|
443
651
|
def __init__(
|
|
444
652
|
self,
|
|
445
|
-
page:
|
|
653
|
+
page: PageImage,
|
|
446
654
|
predictions: dict[str, list[Prediction]],
|
|
447
655
|
page_idx: int,
|
|
448
656
|
dimensions: tuple[int, int],
|
|
449
657
|
orientation: dict[str, Any] | None = None,
|
|
450
658
|
language: dict[str, Any] | None = None,
|
|
659
|
+
layout: list[LayoutElement] | None = None,
|
|
451
660
|
) -> None:
|
|
452
|
-
super().__init__(predictions=predictions)
|
|
661
|
+
super().__init__(predictions=predictions, layout=layout if layout is not None else [])
|
|
453
662
|
self.page = page
|
|
454
663
|
self.page_idx = page_idx
|
|
455
664
|
self.dimensions = dimensions
|
|
456
665
|
self.orientation = orientation if isinstance(orientation, dict) else dict(value=None, confidence=None)
|
|
457
666
|
self.language = language if isinstance(language, dict) else dict(value=None, confidence=None)
|
|
458
667
|
|
|
459
|
-
def render(self, prediction_break: str = "\n\n") -> str:
|
|
460
|
-
"""Renders the full text of the element"""
|
|
461
|
-
return prediction_break.join(
|
|
462
|
-
f"{class_name}: {p.render()}" for class_name, predictions in self.predictions.items() for p in predictions
|
|
463
|
-
)
|
|
464
|
-
|
|
465
668
|
def extra_repr(self) -> str:
|
|
466
669
|
return f"dimensions={self.dimensions}"
|
|
467
670
|
|
|
@@ -477,8 +680,13 @@ class KIEPage(Element):
|
|
|
477
680
|
requires_package("mplcursors", "`.show()` requires matplotlib & mplcursors installed")
|
|
478
681
|
import matplotlib.pyplot as plt
|
|
479
682
|
|
|
683
|
+
show_kwargs = {k: kwargs.pop(k) for k in ("words_only", "display_artefacts", "display_layout") if k in kwargs}
|
|
480
684
|
visualize_kie_page(
|
|
481
|
-
self.export(),
|
|
685
|
+
self.export(),
|
|
686
|
+
self.page,
|
|
687
|
+
interactive=interactive,
|
|
688
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
689
|
+
**show_kwargs,
|
|
482
690
|
)
|
|
483
691
|
plt.show(**kwargs)
|
|
484
692
|
|
|
@@ -493,112 +701,21 @@ class KIEPage(Element):
|
|
|
493
701
|
"""
|
|
494
702
|
return synthesize_kie_page(self.export(), **kwargs)
|
|
495
703
|
|
|
496
|
-
def export_as_xml(self, file_title: str = "docTR - XML export (hOCR)") -> tuple[bytes, ET.ElementTree]:
|
|
497
|
-
"""Export the page as XML (hOCR-format)
|
|
498
|
-
convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
|
|
499
|
-
|
|
500
|
-
Args:
|
|
501
|
-
file_title: the title of the XML file
|
|
502
|
-
|
|
503
|
-
Returns:
|
|
504
|
-
a tuple of the XML byte string, and its ElementTree
|
|
505
|
-
"""
|
|
506
|
-
p_idx = self.page_idx
|
|
507
|
-
prediction_count: int = 1
|
|
508
|
-
height, width = self.dimensions
|
|
509
|
-
language = self.language if "language" in self.language.keys() else "en"
|
|
510
|
-
# Create the XML root element
|
|
511
|
-
page_hocr = ETElement("html", attrib={"xmlns": "http://www.w3.org/1999/xhtml", "xml:lang": str(language)})
|
|
512
|
-
# Create the header / SubElements of the root element
|
|
513
|
-
head = SubElement(page_hocr, "head")
|
|
514
|
-
SubElement(head, "title").text = file_title
|
|
515
|
-
SubElement(head, "meta", attrib={"http-equiv": "Content-Type", "content": "text/html; charset=utf-8"})
|
|
516
|
-
SubElement(
|
|
517
|
-
head,
|
|
518
|
-
"meta",
|
|
519
|
-
attrib={"name": "ocr-system", "content": f"python-doctr {doctr.__version__}"}, # type: ignore[attr-defined]
|
|
520
|
-
)
|
|
521
|
-
SubElement(
|
|
522
|
-
head,
|
|
523
|
-
"meta",
|
|
524
|
-
attrib={"name": "ocr-capabilities", "content": "ocr_page ocr_carea ocr_par ocr_line ocrx_word"},
|
|
525
|
-
)
|
|
526
|
-
# Create the body
|
|
527
|
-
body = SubElement(page_hocr, "body")
|
|
528
|
-
SubElement(
|
|
529
|
-
body,
|
|
530
|
-
"div",
|
|
531
|
-
attrib={
|
|
532
|
-
"class": "ocr_page",
|
|
533
|
-
"id": f"page_{p_idx + 1}",
|
|
534
|
-
"title": f"image; bbox 0 0 {width} {height}; ppageno 0",
|
|
535
|
-
},
|
|
536
|
-
)
|
|
537
|
-
# iterate over the blocks / lines / words and create the XML elements in body line by line with the attributes
|
|
538
|
-
for class_name, predictions in self.predictions.items():
|
|
539
|
-
for prediction in predictions:
|
|
540
|
-
if len(prediction.geometry) != 2:
|
|
541
|
-
raise TypeError("XML export is only available for straight bounding boxes for now.")
|
|
542
|
-
(xmin, ymin), (xmax, ymax) = prediction.geometry
|
|
543
|
-
prediction_div = SubElement(
|
|
544
|
-
body,
|
|
545
|
-
"div",
|
|
546
|
-
attrib={
|
|
547
|
-
"class": "ocr_carea",
|
|
548
|
-
"id": f"{class_name}_prediction_{prediction_count}",
|
|
549
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
550
|
-
{int(round(xmax * width))} {int(round(ymax * height))}",
|
|
551
|
-
},
|
|
552
|
-
)
|
|
553
|
-
# NOTE: ocr_par, ocr_line and ocrx_word are the same because the KIE predictions contain only words
|
|
554
|
-
# This is a workaround to make it PDF/A compatible
|
|
555
|
-
par_div = SubElement(
|
|
556
|
-
prediction_div,
|
|
557
|
-
"p",
|
|
558
|
-
attrib={
|
|
559
|
-
"class": "ocr_par",
|
|
560
|
-
"id": f"{class_name}_par_{prediction_count}",
|
|
561
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
562
|
-
{int(round(xmax * width))} {int(round(ymax * height))}",
|
|
563
|
-
},
|
|
564
|
-
)
|
|
565
|
-
line_span = SubElement(
|
|
566
|
-
par_div,
|
|
567
|
-
"span",
|
|
568
|
-
attrib={
|
|
569
|
-
"class": "ocr_line",
|
|
570
|
-
"id": f"{class_name}_line_{prediction_count}",
|
|
571
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
572
|
-
{int(round(xmax * width))} {int(round(ymax * height))}; \
|
|
573
|
-
baseline 0 0; x_size 0; x_descenders 0; x_ascenders 0",
|
|
574
|
-
},
|
|
575
|
-
)
|
|
576
|
-
word_div = SubElement(
|
|
577
|
-
line_span,
|
|
578
|
-
"span",
|
|
579
|
-
attrib={
|
|
580
|
-
"class": "ocrx_word",
|
|
581
|
-
"id": f"{class_name}_word_{prediction_count}",
|
|
582
|
-
"title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
|
|
583
|
-
{int(round(xmax * width))} {int(round(ymax * height))}; \
|
|
584
|
-
x_wconf {int(round(prediction.confidence * 100))}",
|
|
585
|
-
},
|
|
586
|
-
)
|
|
587
|
-
word_div.text = prediction.value
|
|
588
|
-
prediction_count += 1
|
|
589
|
-
|
|
590
|
-
return ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr)
|
|
591
|
-
|
|
592
704
|
@classmethod
|
|
593
|
-
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
"predictions":
|
|
705
|
+
def from_dict(cls, save_dict: dict[str, Any], page: np.ndarray | None = None, **kwargs):
|
|
706
|
+
_kwargs: dict[str, Any] = {k: save_dict[k] for k in cls._exported_keys}
|
|
707
|
+
_kwargs.update({
|
|
708
|
+
"predictions": {
|
|
709
|
+
class_name: [Prediction.from_dict(pred) for pred in preds]
|
|
710
|
+
for class_name, preds in save_dict["predictions"].items()
|
|
711
|
+
},
|
|
712
|
+
"layout": [LayoutElement.from_dict(region_dict) for region_dict in save_dict.get("layout", [])],
|
|
597
713
|
})
|
|
598
|
-
|
|
714
|
+
# The page image is not part of the export: pass it back explicitly to restore a fully usable page
|
|
715
|
+
return cls(page=_empty_page_image(page), **_kwargs)
|
|
599
716
|
|
|
600
717
|
|
|
601
|
-
class Document(Element):
|
|
718
|
+
class Document(DocumentExportsMixin, Element):
|
|
602
719
|
"""Implements a document element as a collection of pages
|
|
603
720
|
|
|
604
721
|
Args:
|
|
@@ -614,10 +731,6 @@ class Document(Element):
|
|
|
614
731
|
) -> None:
|
|
615
732
|
super().__init__(pages=pages)
|
|
616
733
|
|
|
617
|
-
def render(self, page_break: str = "\n\n\n\n") -> str:
|
|
618
|
-
"""Renders the full text of the element"""
|
|
619
|
-
return page_break.join(p.render() for p in self.pages)
|
|
620
|
-
|
|
621
734
|
def show(self, **kwargs) -> None:
|
|
622
735
|
"""Overlay the result on a given image"""
|
|
623
736
|
for result in self.pages:
|
|
@@ -634,22 +747,18 @@ class Document(Element):
|
|
|
634
747
|
"""
|
|
635
748
|
return [page.synthesize(**kwargs) for page in self.pages]
|
|
636
749
|
|
|
637
|
-
|
|
638
|
-
"""Export the document as XML (hOCR-format)
|
|
639
|
-
|
|
640
|
-
Args:
|
|
641
|
-
**kwargs: additional keyword arguments passed to the Page.export_as_xml method
|
|
642
|
-
|
|
643
|
-
Returns:
|
|
644
|
-
list of tuple of (bytes, ElementTree)
|
|
645
|
-
"""
|
|
646
|
-
return [page.export_as_xml(**kwargs) for page in self.pages]
|
|
750
|
+
_page_cls: Any = Page
|
|
647
751
|
|
|
648
752
|
@classmethod
|
|
649
|
-
def from_dict(cls, save_dict: dict[str, Any], **kwargs):
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
753
|
+
def from_dict(cls, save_dict: dict[str, Any], pages: list[np.ndarray] | None = None, **kwargs):
|
|
754
|
+
_kwargs: dict[str, Any] = {k: save_dict[k] for k in cls._exported_keys}
|
|
755
|
+
_kwargs.update({
|
|
756
|
+
"pages": [
|
|
757
|
+
cls._page_cls.from_dict(page_dict, page=None if pages is None else pages[idx])
|
|
758
|
+
for idx, page_dict in enumerate(save_dict["pages"])
|
|
759
|
+
]
|
|
760
|
+
})
|
|
761
|
+
return cls(**_kwargs)
|
|
653
762
|
|
|
654
763
|
|
|
655
764
|
class KIEDocument(Document):
|
|
@@ -660,6 +769,7 @@ class KIEDocument(Document):
|
|
|
660
769
|
"""
|
|
661
770
|
|
|
662
771
|
_children_names: list[str] = ["pages"]
|
|
772
|
+
_page_cls: Any = KIEPage
|
|
663
773
|
pages: list[KIEPage] = [] # type: ignore[assignment]
|
|
664
774
|
|
|
665
775
|
def __init__(
|