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/models/builder.py
CHANGED
|
@@ -1,16 +1,35 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
2
|
|
|
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
6
|
|
|
7
|
+
from collections.abc import Sequence
|
|
7
8
|
from typing import Any
|
|
8
9
|
|
|
9
10
|
import numpy as np
|
|
10
11
|
from scipy.cluster.hierarchy import fclusterdata
|
|
11
12
|
|
|
12
|
-
from doctr.io.elements import
|
|
13
|
-
|
|
13
|
+
from doctr.io.elements import (
|
|
14
|
+
Block,
|
|
15
|
+
Document,
|
|
16
|
+
KIEDocument,
|
|
17
|
+
KIEPage,
|
|
18
|
+
LayoutElement,
|
|
19
|
+
Line,
|
|
20
|
+
Page,
|
|
21
|
+
Prediction,
|
|
22
|
+
Table,
|
|
23
|
+
TableCell,
|
|
24
|
+
Word,
|
|
25
|
+
)
|
|
26
|
+
from doctr.utils.geometry import (
|
|
27
|
+
estimate_page_angle,
|
|
28
|
+
order_points,
|
|
29
|
+
resolve_enclosing_bbox,
|
|
30
|
+
resolve_enclosing_rbbox,
|
|
31
|
+
rotate_boxes,
|
|
32
|
+
)
|
|
14
33
|
from doctr.utils.repr import NestedObject
|
|
15
34
|
|
|
16
35
|
__all__ = ["DocumentBuilder"]
|
|
@@ -25,6 +44,10 @@ class DocumentBuilder(NestedObject):
|
|
|
25
44
|
paragraph_break: relative length of the minimum space separating paragraphs
|
|
26
45
|
export_as_straight_boxes: if True, force straight boxes in the export (fit a rectangle
|
|
27
46
|
box to all rotated boxes). Else, keep the boxes format unchanged, no matter what it is.
|
|
47
|
+
keep_reading_order: if True, arrange the content of every page in reading order (cf.
|
|
48
|
+
:mod:`doctr.models.reading_order`). The reading direction is inferred from the recognized text.
|
|
49
|
+
When a layout is available it is always preferred: the text blocks and the page furniture
|
|
50
|
+
(headers, footers, ...) are taken from the layout regions.
|
|
28
51
|
"""
|
|
29
52
|
|
|
30
53
|
def __init__(
|
|
@@ -33,18 +56,21 @@ class DocumentBuilder(NestedObject):
|
|
|
33
56
|
resolve_blocks: bool = False,
|
|
34
57
|
paragraph_break: float = 0.035,
|
|
35
58
|
export_as_straight_boxes: bool = False,
|
|
59
|
+
keep_reading_order: bool = False,
|
|
36
60
|
) -> None:
|
|
37
61
|
self.resolve_lines = resolve_lines
|
|
38
62
|
self.resolve_blocks = resolve_blocks
|
|
39
63
|
self.paragraph_break = paragraph_break
|
|
40
64
|
self.export_as_straight_boxes = export_as_straight_boxes
|
|
65
|
+
self.keep_reading_order = keep_reading_order
|
|
41
66
|
|
|
42
67
|
@staticmethod
|
|
43
|
-
def _sort_boxes(boxes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
68
|
+
def _sort_boxes(boxes: np.ndarray, shape: tuple[int, int] | None = None) -> tuple[np.ndarray, np.ndarray]:
|
|
44
69
|
"""Sort bounding boxes from top to bottom, left to right
|
|
45
70
|
|
|
46
71
|
Args:
|
|
47
|
-
boxes: bounding boxes of shape (N, 4) or (N, 4, 2)
|
|
72
|
+
boxes: bounding boxes of shape (N, 4) or (N, 4, 2)
|
|
73
|
+
shape: the page dimensions (height, width)
|
|
48
74
|
|
|
49
75
|
Returns:
|
|
50
76
|
tuple: indices of ordered boxes of shape (N,), boxes
|
|
@@ -53,25 +79,45 @@ class DocumentBuilder(NestedObject):
|
|
|
53
79
|
so that we fit the lines afterwards to the straigthened page
|
|
54
80
|
"""
|
|
55
81
|
if boxes.ndim == 3:
|
|
56
|
-
|
|
82
|
+
height, width = shape if shape is not None else (1024, 1024)
|
|
83
|
+
scale = np.array([width, height], dtype=boxes.dtype)
|
|
84
|
+
angle = estimate_page_angle(boxes * scale)
|
|
85
|
+
rotated = rotate_boxes(
|
|
57
86
|
loc_preds=boxes,
|
|
58
|
-
angle=-
|
|
59
|
-
orig_shape=(
|
|
60
|
-
min_angle=
|
|
87
|
+
angle=-angle,
|
|
88
|
+
orig_shape=(height, width),
|
|
89
|
+
min_angle=1.0,
|
|
61
90
|
)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
91
|
+
# On rotated pages, detectors can output a mix of properly rotated polygons and axis-aligned
|
|
92
|
+
# enclosing boxes. A box that is not itself rotated carries no rotation to remove
|
|
93
|
+
if abs(angle) >= 1.0:
|
|
94
|
+
edges = (boxes[:, 1] - boxes[:, 0]) * scale
|
|
95
|
+
own_angle = np.rad2deg(np.arctan2(-edges[:, 1], edges[:, 0]))
|
|
96
|
+
keep = np.abs(own_angle) < abs(angle) / 2
|
|
97
|
+
if keep.any():
|
|
98
|
+
centers = boxes.mean(axis=1, keepdims=True)
|
|
99
|
+
new_centers = rotated.mean(axis=1, keepdims=True)
|
|
100
|
+
rotated[keep] = boxes[keep] - centers[keep] + new_centers[keep]
|
|
101
|
+
boxes = np.concatenate((rotated.min(1), rotated.max(1)), -1)
|
|
102
|
+
med_height = float(np.median(boxes[:, 3] - boxes[:, 1]))
|
|
103
|
+
if not np.isfinite(med_height) or med_height <= 0:
|
|
104
|
+
med_height = 1.0
|
|
105
|
+
return (boxes[:, 0] + 2 * boxes[:, 3] / med_height).argsort(), boxes
|
|
106
|
+
|
|
107
|
+
def _resolve_sub_lines(
|
|
108
|
+
self, boxes: np.ndarray, word_idcs: list[int], break_dist: float | None = None
|
|
109
|
+
) -> list[list[int]]:
|
|
66
110
|
"""Split a line in sub_lines
|
|
67
111
|
|
|
68
112
|
Args:
|
|
69
113
|
boxes: bounding boxes of shape (N, 4)
|
|
70
114
|
word_idcs: list of indexes for the words of the line
|
|
115
|
+
break_dist: horizontal distance above which the line is split (defaults to `self.paragraph_break`)
|
|
71
116
|
|
|
72
117
|
Returns:
|
|
73
118
|
A list of (sub-)lines computed from the original line (words)
|
|
74
119
|
"""
|
|
120
|
+
break_dist = self.paragraph_break if break_dist is None else break_dist
|
|
75
121
|
lines = []
|
|
76
122
|
# Sort words horizontally
|
|
77
123
|
word_idcs = [word_idcs[idx] for idx in boxes[word_idcs, 0].argsort().tolist()]
|
|
@@ -87,8 +133,8 @@ class DocumentBuilder(NestedObject):
|
|
|
87
133
|
prev_box = boxes[sub_line[-1]]
|
|
88
134
|
# Compute distance between boxes
|
|
89
135
|
dist = boxes[i, 0] - prev_box[2]
|
|
90
|
-
# If distance between boxes is lower than
|
|
91
|
-
if dist <
|
|
136
|
+
# If distance between boxes is lower than the break distance, same sub-line
|
|
137
|
+
if dist < break_dist:
|
|
92
138
|
horiz_break = False
|
|
93
139
|
|
|
94
140
|
if horiz_break:
|
|
@@ -100,22 +146,24 @@ class DocumentBuilder(NestedObject):
|
|
|
100
146
|
|
|
101
147
|
return lines
|
|
102
148
|
|
|
103
|
-
def _resolve_lines(self, boxes: np.ndarray) -> list[list[int]]:
|
|
149
|
+
def _resolve_lines(self, boxes: np.ndarray, shape: tuple[int, int] | None = None) -> list[list[int]]:
|
|
104
150
|
"""Order boxes to group them in lines
|
|
105
151
|
|
|
106
152
|
Args:
|
|
107
153
|
boxes: bounding boxes of shape (N, 4) or (N, 4, 2) in case of rotated bbox
|
|
154
|
+
shape: the page dimensions (height, width), used to de-skew rotated pages exactly
|
|
108
155
|
|
|
109
156
|
Returns:
|
|
110
157
|
nested list of box indices
|
|
111
158
|
"""
|
|
112
159
|
# Sort boxes, and straighten the boxes if they are rotated
|
|
113
|
-
idxs, boxes = self._sort_boxes(boxes)
|
|
160
|
+
idxs, boxes = self._sort_boxes(boxes, shape)
|
|
114
161
|
|
|
115
162
|
# Compute median for boxes heights
|
|
116
163
|
y_med = np.median(boxes[:, 3] - boxes[:, 1])
|
|
117
164
|
|
|
118
|
-
|
|
165
|
+
# Group the words into visual rows
|
|
166
|
+
rows = []
|
|
119
167
|
words = [idxs[0]] # Assign the top-left word to the first line
|
|
120
168
|
# Define a mean y-center for the line
|
|
121
169
|
y_center_sum = boxes[idxs[0]][[1, 3]].mean()
|
|
@@ -130,18 +178,43 @@ class DocumentBuilder(NestedObject):
|
|
|
130
178
|
vert_break = False
|
|
131
179
|
|
|
132
180
|
if vert_break:
|
|
133
|
-
|
|
134
|
-
lines.extend(self._resolve_sub_lines(boxes, words))
|
|
181
|
+
rows.append(words)
|
|
135
182
|
words = []
|
|
136
183
|
y_center_sum = 0
|
|
137
184
|
|
|
138
185
|
words.append(idx)
|
|
139
186
|
y_center_sum += boxes[idx][[1, 3]].mean()
|
|
140
187
|
|
|
141
|
-
# Use the remaining words to form the last
|
|
188
|
+
# Use the remaining words to form the last row
|
|
142
189
|
if len(words) > 0:
|
|
143
|
-
|
|
144
|
-
|
|
190
|
+
rows.append(words)
|
|
191
|
+
|
|
192
|
+
# Split the rows horizontally, using a break distance adapted to the page spacing.
|
|
193
|
+
# The gaps are collected with one vectorized pass per row (the loop is over rows, not word pairs).
|
|
194
|
+
gap_chunks = []
|
|
195
|
+
n_pairs = 0
|
|
196
|
+
for row in rows:
|
|
197
|
+
if len(row) < 2:
|
|
198
|
+
continue
|
|
199
|
+
row_idcs = np.asarray(row)
|
|
200
|
+
row_idcs = row_idcs[np.argsort(boxes[row_idcs, 0], kind="stable")]
|
|
201
|
+
n_pairs += row_idcs.shape[0] - 1
|
|
202
|
+
gap_chunks.append(boxes[row_idcs[1:], 0] - boxes[row_idcs[:-1], 2])
|
|
203
|
+
all_gaps = np.concatenate(gap_chunks) if gap_chunks else np.empty(0, dtype=boxes.dtype)
|
|
204
|
+
pos_gaps = all_gaps[all_gaps > 0]
|
|
205
|
+
# Median word height, converted to width units
|
|
206
|
+
aspect = (shape[0] / shape[1]) if shape is not None else 1.0
|
|
207
|
+
floor = float(y_med) * aspect
|
|
208
|
+
if pos_gaps.shape[0] >= 5 and pos_gaps.shape[0] >= 0.5 * n_pairs:
|
|
209
|
+
break_dist = min(self.paragraph_break, max(3.0 * float(np.median(pos_gaps)), floor))
|
|
210
|
+
elif n_pairs >= 5:
|
|
211
|
+
break_dist = min(self.paragraph_break, floor)
|
|
212
|
+
else:
|
|
213
|
+
break_dist = self.paragraph_break
|
|
214
|
+
|
|
215
|
+
lines = []
|
|
216
|
+
for row in rows:
|
|
217
|
+
lines.extend(self._resolve_sub_lines(boxes, row, break_dist))
|
|
145
218
|
|
|
146
219
|
return lines
|
|
147
220
|
|
|
@@ -211,12 +284,308 @@ class DocumentBuilder(NestedObject):
|
|
|
211
284
|
|
|
212
285
|
return blocks
|
|
213
286
|
|
|
287
|
+
@staticmethod
|
|
288
|
+
def _build_layout_elements(regions: dict[str, Any] | None) -> list[LayoutElement]:
|
|
289
|
+
"""Convert a raw layout prediction into exportable `LayoutElement` objects.
|
|
290
|
+
|
|
291
|
+
Args:
|
|
292
|
+
regions: a layout prediction `{"boxes": (R, 4) | (R, 4, 2), "class_names": [...], "scores": [...]}`
|
|
293
|
+
as returned by a `LayoutPredictor`, or None.
|
|
294
|
+
|
|
295
|
+
Returns:
|
|
296
|
+
list of `LayoutElement` (empty if no layout was provided).
|
|
297
|
+
"""
|
|
298
|
+
if regions is None or len(regions.get("boxes", [])) == 0:
|
|
299
|
+
return []
|
|
300
|
+
boxes = np.asarray(regions["boxes"])
|
|
301
|
+
class_names = regions.get("class_names") or ["" for _ in range(len(boxes))]
|
|
302
|
+
scores = regions.get("scores")
|
|
303
|
+
scores = scores if scores is not None else [1.0 for _ in range(len(boxes))]
|
|
304
|
+
|
|
305
|
+
elements: list[LayoutElement] = []
|
|
306
|
+
for box, cname, score in zip(boxes, class_names, scores):
|
|
307
|
+
if box.ndim == 2: # rotated polygon (4, 2)
|
|
308
|
+
geometry: Any = tuple(tuple(float(c) for c in pt) for pt in box.tolist())
|
|
309
|
+
else: # straight (x1, y1, x2, y2)
|
|
310
|
+
geometry = ((float(box[0]), float(box[1])), (float(box[2]), float(box[3])))
|
|
311
|
+
elements.append(LayoutElement(layout_type=str(cname), confidence=float(score), geometry=geometry))
|
|
312
|
+
return elements
|
|
313
|
+
|
|
314
|
+
@staticmethod
|
|
315
|
+
def _word_centers(boxes: np.ndarray) -> np.ndarray:
|
|
316
|
+
"""Return the (x, y) center of each word box.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
boxes: word boxes of shape (N, 4) (straight: x1, y1, x2, y2) or (N, 4, 2) (rotated polygon)
|
|
320
|
+
|
|
321
|
+
Returns:
|
|
322
|
+
array of shape (N, 2) with the relative center coordinates of each box
|
|
323
|
+
"""
|
|
324
|
+
if boxes.ndim == 3: # rotated polygons (N, 4, 2)
|
|
325
|
+
return boxes.mean(axis=1)
|
|
326
|
+
return np.stack([(boxes[:, 0] + boxes[:, 2]) / 2, (boxes[:, 1] + boxes[:, 3]) / 2], axis=1)
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def _as_cell_polygon(geometry: Any) -> np.ndarray:
|
|
330
|
+
"""Normalize a cell geometry to a (4, 2) polygon.
|
|
331
|
+
|
|
332
|
+
Straight-page table predictions store cells as flat (xmin, ymin, xmax, ymax) boxes, while rotated-page
|
|
333
|
+
predictions store (4, 2) corner polygons: both are mapped to a (4, 2) polygon (TL, TR, BR, BL).
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
geometry: the raw cell geometry
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
array of shape (4, 2) with the polygon vertices
|
|
340
|
+
"""
|
|
341
|
+
arr = np.asarray(geometry, dtype=np.float32)
|
|
342
|
+
if arr.ndim == 1: # straight box (xmin, ymin, xmax, ymax)
|
|
343
|
+
x0, y0, x1, y1 = arr
|
|
344
|
+
return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float32)
|
|
345
|
+
return order_points(arr.reshape(-1, 2))
|
|
346
|
+
|
|
347
|
+
@staticmethod
|
|
348
|
+
def _points_in_polygons(points: np.ndarray, polys: np.ndarray) -> np.ndarray:
|
|
349
|
+
"""Vectorized ray casting: test every point against every polygon at once.
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
points: array of shape (N, 2) with the (x, y) coordinates of the points
|
|
353
|
+
polys: array of shape (C, V, 2) with the polygon vertices
|
|
354
|
+
|
|
355
|
+
Returns:
|
|
356
|
+
boolean array of shape (N, C), True where point n lies inside polygon c
|
|
357
|
+
"""
|
|
358
|
+
if points.shape[0] == 0 or polys.shape[0] == 0:
|
|
359
|
+
return np.zeros((points.shape[0], polys.shape[0]), dtype=bool)
|
|
360
|
+
px = points[:, 0].astype(np.float64)[:, None, None]
|
|
361
|
+
py = points[:, 1].astype(np.float64)[:, None, None]
|
|
362
|
+
vi = polys.astype(np.float64) # (C, V, 2)
|
|
363
|
+
vj = np.roll(vi, 1, axis=1) # previous vertex, with wrap-around
|
|
364
|
+
xi, yi = vi[None, ..., 0], vi[None, ..., 1]
|
|
365
|
+
xj, yj = vj[None, ..., 0], vj[None, ..., 1]
|
|
366
|
+
crossing = ((yi > py) != (yj > py)) & (px < (xj - xi) * (py - yi) / (yj - yi + 1e-12) + xi)
|
|
367
|
+
# A point is inside when a ray crosses the polygon boundary an odd number of times
|
|
368
|
+
return (crossing.sum(axis=-1) % 2).astype(bool)
|
|
369
|
+
|
|
370
|
+
@staticmethod
|
|
371
|
+
def _order_cell_words(w_idcs: list[int], centers: np.ndarray, heights: np.ndarray) -> list[int]:
|
|
372
|
+
"""Order the words of a table cell in reading order: rows top to bottom, words left to right.
|
|
373
|
+
|
|
374
|
+
Args:
|
|
375
|
+
w_idcs: indices of the cell's words
|
|
376
|
+
centers: word centers of shape (N, 2), de-skewed for rotated pages
|
|
377
|
+
heights: per-word heights of shape (N,) (rotation-invariant)
|
|
378
|
+
|
|
379
|
+
Returns:
|
|
380
|
+
the cell's word indices in reading order
|
|
381
|
+
"""
|
|
382
|
+
idcs = sorted(w_idcs, key=lambda i: float(centers[i][1]))
|
|
383
|
+
med_height = float(np.median([heights[i] for i in idcs]))
|
|
384
|
+
if not np.isfinite(med_height) or med_height <= 0:
|
|
385
|
+
med_height = 1.0
|
|
386
|
+
rows: list[list[int]] = [[idcs[0]]]
|
|
387
|
+
y_sum = float(centers[idcs[0]][1])
|
|
388
|
+
for idx in idcs[1:]:
|
|
389
|
+
if float(centers[idx][1]) - y_sum / len(rows[-1]) < med_height / 2:
|
|
390
|
+
rows[-1].append(idx)
|
|
391
|
+
y_sum += float(centers[idx][1])
|
|
392
|
+
else:
|
|
393
|
+
rows.append([idx])
|
|
394
|
+
y_sum = float(centers[idx][1])
|
|
395
|
+
return [idx for row in rows for idx in sorted(row, key=lambda i: float(centers[i][0]))]
|
|
396
|
+
|
|
397
|
+
@staticmethod
|
|
398
|
+
def _localize_logic(cells: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int, int]:
|
|
399
|
+
"""Re-index a table's logical coordinates to a local 0-based grid.
|
|
400
|
+
|
|
401
|
+
The table model returns logical (row/column) coordinates that may carry a constant offset; shifting them
|
|
402
|
+
so that the smallest row/column start is 0 makes the grid directly usable by :meth:`Table.to_grid`.
|
|
403
|
+
|
|
404
|
+
Args:
|
|
405
|
+
cells: the cells of a single table
|
|
406
|
+
|
|
407
|
+
Returns:
|
|
408
|
+
a tuple `(cells, num_rows, num_cols)` with the re-indexed cells and the table dimensions
|
|
409
|
+
"""
|
|
410
|
+
min_row = min(int(c["row_start"]) for c in cells)
|
|
411
|
+
min_col = min(int(c["col_start"]) for c in cells)
|
|
412
|
+
norm: list[dict[str, Any]] = []
|
|
413
|
+
max_row = max_col = 0
|
|
414
|
+
for c in cells:
|
|
415
|
+
nc = dict(c)
|
|
416
|
+
nc["row_start"] = int(c["row_start"]) - min_row
|
|
417
|
+
nc["row_end"] = int(c["row_end"]) - min_row
|
|
418
|
+
nc["col_start"] = int(c["col_start"]) - min_col
|
|
419
|
+
nc["col_end"] = int(c["col_end"]) - min_col
|
|
420
|
+
max_row, max_col = max(max_row, nc["row_end"]), max(max_col, nc["col_end"])
|
|
421
|
+
norm.append(nc)
|
|
422
|
+
return norm, max_row + 1, max_col + 1
|
|
423
|
+
|
|
424
|
+
def _build_tables(
|
|
425
|
+
self,
|
|
426
|
+
boxes: np.ndarray,
|
|
427
|
+
word_preds: list[tuple[str, float]],
|
|
428
|
+
page_table: dict[str, Any] | list[dict[str, Any]] | None,
|
|
429
|
+
) -> tuple[list[Table], np.ndarray]:
|
|
430
|
+
"""Assign detected words to table cells and build the page tables.
|
|
431
|
+
|
|
432
|
+
Args:
|
|
433
|
+
boxes: word boxes of the page, of shape (N, 4) or (N, 4, 2), in relative coordinates
|
|
434
|
+
word_preds: list of (text, confidence) for each of the N words
|
|
435
|
+
page_table: the table structure prediction(s) for the page. Either a single grid
|
|
436
|
+
`{"cells": [{"geometry", "score", "row_start", "row_end", "col_start", "col_end"}], "num_rows",
|
|
437
|
+
"num_cols"}` (cell geometries in page-relative coordinates), a list of such grids, or None
|
|
438
|
+
|
|
439
|
+
Returns:
|
|
440
|
+
a tuple with the list of `Table` objects of the page (one per provided table) and a boolean mask of
|
|
441
|
+
shape (N,) that is True for words assigned to a table (to be removed from `blocks`)
|
|
442
|
+
"""
|
|
443
|
+
num_words = boxes.shape[0]
|
|
444
|
+
consumed = np.zeros(num_words, dtype=bool)
|
|
445
|
+
if page_table is None:
|
|
446
|
+
return [], consumed
|
|
447
|
+
|
|
448
|
+
# Normalize the prediction(s) to a list of per-table grids with local 0-based logical coordinates
|
|
449
|
+
raw_tables = [page_table] if isinstance(page_table, dict) else list(page_table)
|
|
450
|
+
table_dicts: list[dict[str, Any]] = []
|
|
451
|
+
for raw in raw_tables:
|
|
452
|
+
if not raw or len(raw.get("cells", [])) == 0:
|
|
453
|
+
continue
|
|
454
|
+
cells, n_rows, n_cols = self._localize_logic(raw["cells"])
|
|
455
|
+
table_dicts.append({"cells": cells, "num_rows": n_rows, "num_cols": n_cols})
|
|
456
|
+
if len(table_dicts) == 0:
|
|
457
|
+
return [], consumed
|
|
458
|
+
|
|
459
|
+
centers = self._word_centers(boxes) if num_words > 0 else np.empty((0, 2))
|
|
460
|
+
# Geometry format follows the page's word geometry: straight 2-point boxes when the word boxes are
|
|
461
|
+
# (N, 4), 4-point polygons when they are (N, 4, 2).
|
|
462
|
+
straight = boxes.ndim != 3
|
|
463
|
+
# Rotation-invariant word heights (left edge length for polygons), used to cluster cell words into rows
|
|
464
|
+
if num_words == 0:
|
|
465
|
+
word_heights = np.empty(0)
|
|
466
|
+
elif straight:
|
|
467
|
+
word_heights = boxes[:, 3] - boxes[:, 1]
|
|
468
|
+
else:
|
|
469
|
+
word_heights = np.linalg.norm(boxes[:, 3] - boxes[:, 0], axis=1)
|
|
470
|
+
|
|
471
|
+
tables_out: list[Table] = []
|
|
472
|
+
for table_dict in table_dicts:
|
|
473
|
+
cells = table_dict["cells"]
|
|
474
|
+
if len(cells) == 0:
|
|
475
|
+
continue
|
|
476
|
+
cell_polys = [self._as_cell_polygon(cell["geometry"]) for cell in cells]
|
|
477
|
+
polys_arr = np.stack(cell_polys) # (C, 4, 2), vertices ordered TL, TR, BR, BL
|
|
478
|
+
|
|
479
|
+
# Order along the table's own axes instead by de-skewing the centers with the table angle
|
|
480
|
+
order_centers = centers
|
|
481
|
+
if not straight and centers.shape[0] > 0:
|
|
482
|
+
top_edges = polys_arr[:, 1] - polys_arr[:, 0] # TR - TL
|
|
483
|
+
angle = float(np.median(np.arctan2(top_edges[:, 1], top_edges[:, 0])))
|
|
484
|
+
cos_a, sin_a = np.cos(-angle), np.sin(-angle)
|
|
485
|
+
pivot = centers.mean(axis=0)
|
|
486
|
+
shifted = centers - pivot
|
|
487
|
+
order_centers = np.stack(
|
|
488
|
+
[
|
|
489
|
+
pivot[0] + shifted[:, 0] * cos_a - shifted[:, 1] * sin_a,
|
|
490
|
+
pivot[1] + shifted[:, 0] * sin_a + shifted[:, 1] * cos_a,
|
|
491
|
+
],
|
|
492
|
+
axis=1,
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
# Assign each (still unassigned) word to at most one cell of this table
|
|
496
|
+
cell_word_idcs: list[list[int]] = [[] for _ in cells]
|
|
497
|
+
free_idcs = np.flatnonzero(~consumed)
|
|
498
|
+
if free_idcs.size > 0:
|
|
499
|
+
# The first cell (in cell order) whose polygon contains the word center
|
|
500
|
+
inside = self._points_in_polygons(centers[free_idcs], polys_arr) # (F, C)
|
|
501
|
+
assigned = inside.any(axis=1)
|
|
502
|
+
first_cell = np.where(assigned, inside.argmax(axis=1), -1)
|
|
503
|
+
for w_idx, c_idx in zip(free_idcs, first_cell):
|
|
504
|
+
if c_idx >= 0:
|
|
505
|
+
cell_word_idcs[c_idx].append(int(w_idx))
|
|
506
|
+
consumed[w_idx] = True
|
|
507
|
+
|
|
508
|
+
# Words that landed just outside every cell but still inside the table region are attached
|
|
509
|
+
# to the nearest cell, so table text is not dropped into the body.
|
|
510
|
+
# The capture radius is bounded by the cell size to avoid pulling in body words.
|
|
511
|
+
leftover = free_idcs[~assigned]
|
|
512
|
+
if leftover.size > 0:
|
|
513
|
+
tx0, ty0 = polys_arr[..., 0].min(), polys_arr[..., 1].min()
|
|
514
|
+
tx1, ty1 = polys_arr[..., 0].max(), polys_arr[..., 1].max()
|
|
515
|
+
cell_centers = polys_arr.mean(axis=1) # (C, 2)
|
|
516
|
+
cell_sizes = np.linalg.norm(polys_arr[:, 2] - polys_arr[:, 0], axis=1) # TL->BR diagonal
|
|
517
|
+
max_dist = 0.5 * float(np.median(cell_sizes))
|
|
518
|
+
in_region = (
|
|
519
|
+
(centers[leftover, 0] >= tx0)
|
|
520
|
+
& (centers[leftover, 0] <= tx1)
|
|
521
|
+
& (centers[leftover, 1] >= ty0)
|
|
522
|
+
& (centers[leftover, 1] <= ty1)
|
|
523
|
+
)
|
|
524
|
+
for w_idx in leftover[in_region]:
|
|
525
|
+
dists = np.linalg.norm(cell_centers - centers[w_idx], axis=1)
|
|
526
|
+
nearest = int(dists.argmin())
|
|
527
|
+
if dists[nearest] <= max_dist:
|
|
528
|
+
cell_word_idcs[nearest].append(int(w_idx))
|
|
529
|
+
consumed[w_idx] = True
|
|
530
|
+
|
|
531
|
+
# Build the cells
|
|
532
|
+
table_cells: list[TableCell] = []
|
|
533
|
+
for cell, poly, w_idcs in zip(cells, cell_polys, cell_word_idcs):
|
|
534
|
+
if len(w_idcs) > 0:
|
|
535
|
+
# Reading order inside the cell: rows top to bottom, words left to right (table axes)
|
|
536
|
+
ordered = self._order_cell_words(w_idcs, order_centers, word_heights)
|
|
537
|
+
value = " ".join(word_preds[i][0] for i in ordered)
|
|
538
|
+
confidence = float(np.mean([word_preds[i][1] for i in ordered]))
|
|
539
|
+
else:
|
|
540
|
+
value, confidence = "", float(cell["score"])
|
|
541
|
+
if straight:
|
|
542
|
+
xs, ys = poly[:, 0], poly[:, 1]
|
|
543
|
+
geometry: Any = (
|
|
544
|
+
(float(xs.min()), float(ys.min())),
|
|
545
|
+
(float(xs.max()), float(ys.max())),
|
|
546
|
+
)
|
|
547
|
+
else:
|
|
548
|
+
geometry = tuple(tuple(float(c) for c in pt) for pt in poly.tolist())
|
|
549
|
+
table_cells.append(
|
|
550
|
+
TableCell(
|
|
551
|
+
value=value,
|
|
552
|
+
confidence=confidence,
|
|
553
|
+
geometry=geometry,
|
|
554
|
+
row_start=int(cell["row_start"]),
|
|
555
|
+
row_end=int(cell["row_end"]),
|
|
556
|
+
col_start=int(cell["col_start"]),
|
|
557
|
+
col_end=int(cell["col_end"]),
|
|
558
|
+
)
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
# Enclosing geometry of the whole table
|
|
562
|
+
all_pts = np.concatenate(cell_polys, axis=0)
|
|
563
|
+
xmin, ymin = float(all_pts[:, 0].min()), float(all_pts[:, 1].min())
|
|
564
|
+
xmax, ymax = float(all_pts[:, 0].max()), float(all_pts[:, 1].max())
|
|
565
|
+
table_geometry: Any = (
|
|
566
|
+
((xmin, ymin), (xmax, ymax)) if straight else ((xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax))
|
|
567
|
+
)
|
|
568
|
+
table_confidence = float(np.mean([cell["score"] for cell in cells]))
|
|
569
|
+
|
|
570
|
+
tables_out.append(
|
|
571
|
+
Table(
|
|
572
|
+
cells=table_cells,
|
|
573
|
+
num_rows=int(table_dict["num_rows"]),
|
|
574
|
+
num_cols=int(table_dict["num_cols"]),
|
|
575
|
+
geometry=table_geometry,
|
|
576
|
+
confidence=table_confidence,
|
|
577
|
+
)
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
return tables_out, consumed
|
|
581
|
+
|
|
214
582
|
def _build_blocks(
|
|
215
583
|
self,
|
|
216
584
|
boxes: np.ndarray,
|
|
217
585
|
objectness_scores: np.ndarray,
|
|
218
586
|
word_preds: list[tuple[str, float]],
|
|
219
587
|
crop_orientations: list[dict[str, Any]],
|
|
588
|
+
shape: tuple[int, int] | None = None,
|
|
220
589
|
) -> list[Block]:
|
|
221
590
|
"""Gather independent words in structured blocks
|
|
222
591
|
|
|
@@ -226,6 +595,8 @@ class DocumentBuilder(NestedObject):
|
|
|
226
595
|
word_preds: list of all detected words of the page, of shape N
|
|
227
596
|
crop_orientations: list of dictoinaries containing
|
|
228
597
|
the general orientation (orientations + confidences) of the crops
|
|
598
|
+
shape: the page dimensions (height, width), used to de-skew rotated pages exactly when
|
|
599
|
+
resolving lines
|
|
229
600
|
|
|
230
601
|
Returns:
|
|
231
602
|
list of block elements
|
|
@@ -239,7 +610,7 @@ class DocumentBuilder(NestedObject):
|
|
|
239
610
|
# Decide whether we try to form lines
|
|
240
611
|
_boxes = boxes
|
|
241
612
|
if self.resolve_lines:
|
|
242
|
-
lines = self._resolve_lines(_boxes if _boxes.ndim == 3 else _boxes[:, :4])
|
|
613
|
+
lines = self._resolve_lines(_boxes if _boxes.ndim == 3 else _boxes[:, :4], shape)
|
|
243
614
|
# Decide whether we try to form blocks
|
|
244
615
|
if self.resolve_blocks and len(lines) > 1:
|
|
245
616
|
_blocks = self._resolve_blocks(_boxes if _boxes.ndim == 3 else _boxes[:, :4], lines)
|
|
@@ -247,7 +618,7 @@ class DocumentBuilder(NestedObject):
|
|
|
247
618
|
_blocks = [lines]
|
|
248
619
|
else:
|
|
249
620
|
# Sort bounding boxes, one line for all boxes, one block for the line
|
|
250
|
-
lines = [self._sort_boxes(_boxes if _boxes.ndim == 3 else _boxes[:, :4])[0]] # type: ignore[list-item]
|
|
621
|
+
lines = [self._sort_boxes(_boxes if _boxes.ndim == 3 else _boxes[:, :4], shape)[0]] # type: ignore[list-item]
|
|
251
622
|
_blocks = [lines]
|
|
252
623
|
|
|
253
624
|
blocks = [
|
|
@@ -275,11 +646,54 @@ class DocumentBuilder(NestedObject):
|
|
|
275
646
|
|
|
276
647
|
return blocks
|
|
277
648
|
|
|
649
|
+
@staticmethod
|
|
650
|
+
def _words_to_boxes(words: list[Word]) -> np.ndarray:
|
|
651
|
+
"""Rebuild a localization array from word geometries (rotated polygons or straight boxes)."""
|
|
652
|
+
geoms = [np.asarray(word.geometry, dtype=np.float32) for word in words]
|
|
653
|
+
if len(geoms) > 0 and geoms[0].shape == (4, 2):
|
|
654
|
+
return np.stack(geoms) # (N, 4, 2) rotated polygons
|
|
655
|
+
return np.asarray(
|
|
656
|
+
[[g[0][0], g[0][1], g[1][0], g[1][1]] for g in geoms], dtype=np.float32
|
|
657
|
+
) # (N, 4) straight boxes
|
|
658
|
+
|
|
659
|
+
def _apply_reading_order(self, page: Page) -> None:
|
|
660
|
+
"""Arrange the blocks of a page in reading order, in place.
|
|
661
|
+
|
|
662
|
+
Args:
|
|
663
|
+
page: the page whose blocks should be reordered in place
|
|
664
|
+
"""
|
|
665
|
+
from doctr.io.exporters import _reading_order_signature, _store_reading_order, page_reading_order
|
|
666
|
+
|
|
667
|
+
if not page.blocks:
|
|
668
|
+
return
|
|
669
|
+
|
|
670
|
+
collapse = not self.resolve_lines
|
|
671
|
+
if collapse:
|
|
672
|
+
words = [word for block in page.blocks for line in block.lines for word in line.words]
|
|
673
|
+
if len(words) < 2:
|
|
674
|
+
return
|
|
675
|
+
groups = self._resolve_lines(self._words_to_boxes(words), page.dimensions)
|
|
676
|
+
page.blocks = [Block([Line([words[idx] for idx in group]) for group in groups])]
|
|
677
|
+
|
|
678
|
+
items, labels, direction = page_reading_order(page)
|
|
679
|
+
blocks = [item for item in items if isinstance(item, Block)]
|
|
680
|
+
page.blocks = (
|
|
681
|
+
[Block(lines=[Line([word for block in blocks for line in block.lines for word in line.words])])]
|
|
682
|
+
if collapse
|
|
683
|
+
else blocks
|
|
684
|
+
)
|
|
685
|
+
if not collapse:
|
|
686
|
+
# The page now *is* the reading order, so an export would recompute the very same linearization.
|
|
687
|
+
# Re-key the cached result to the new block list so the first export reuses it.
|
|
688
|
+
# Skipped when collapsing: the single flattened line no longer matches the line-level items.
|
|
689
|
+
_store_reading_order(page, _reading_order_signature(page, "auto"), (items, labels, direction))
|
|
690
|
+
|
|
278
691
|
def extra_repr(self) -> str:
|
|
279
692
|
return (
|
|
280
693
|
f"resolve_lines={self.resolve_lines}, resolve_blocks={self.resolve_blocks}, "
|
|
281
694
|
f"paragraph_break={self.paragraph_break}, "
|
|
282
|
-
f"export_as_straight_boxes={self.export_as_straight_boxes}"
|
|
695
|
+
f"export_as_straight_boxes={self.export_as_straight_boxes}, "
|
|
696
|
+
f"keep_reading_order={self.keep_reading_order}"
|
|
283
697
|
)
|
|
284
698
|
|
|
285
699
|
def __call__(
|
|
@@ -292,6 +706,8 @@ class DocumentBuilder(NestedObject):
|
|
|
292
706
|
crop_orientations: list[dict[str, Any]],
|
|
293
707
|
orientations: list[dict[str, Any]] | None = None,
|
|
294
708
|
languages: list[dict[str, Any]] | None = None,
|
|
709
|
+
regions: list[dict[str, Any] | None] | None = None,
|
|
710
|
+
tables: Sequence[dict[str, Any] | list[dict[str, Any]] | None] | None = None,
|
|
295
711
|
) -> Document:
|
|
296
712
|
"""Re-arrange detected words into structured blocks
|
|
297
713
|
|
|
@@ -308,51 +724,89 @@ class DocumentBuilder(NestedObject):
|
|
|
308
724
|
where each element is a dictionary containing the orientation (orientation + confidence)
|
|
309
725
|
languages: optional, list of N elements,
|
|
310
726
|
where each element is a dictionary containing the language (language + confidence)
|
|
727
|
+
regions: optional, list of N elements, where each element is a layout prediction
|
|
728
|
+
`{"boxes": (R, 4|4x2), "class_names": [...], "scores": [...]}` attached to each page
|
|
729
|
+
tables: optional, list of N elements, where each element is the table structure prediction(s) of a
|
|
730
|
+
page: a single grid `{"cells": [...], "num_rows": int, "num_cols": int}` or a list of such grids
|
|
731
|
+
(one per table region detected by the layout model). Words assigned to any table are removed from
|
|
732
|
+
the `blocks` output of that page.
|
|
311
733
|
|
|
312
734
|
Returns:
|
|
313
735
|
document object
|
|
314
736
|
"""
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
737
|
+
expected_len = len(boxes)
|
|
738
|
+
if any(
|
|
739
|
+
len(arg) != expected_len for arg in (pages, text_preds, crop_orientations, objectness_scores, page_shapes)
|
|
740
|
+
):
|
|
318
741
|
raise ValueError("All arguments are expected to be lists of the same size")
|
|
319
742
|
|
|
320
|
-
_orientations = (
|
|
321
|
-
|
|
322
|
-
)
|
|
323
|
-
|
|
743
|
+
_orientations = orientations if isinstance(orientations, list) else [None] * len(boxes)
|
|
744
|
+
_languages = languages if isinstance(languages, list) else [None] * len(boxes)
|
|
745
|
+
_regions = regions if isinstance(regions, list) else [None] * len(boxes)
|
|
746
|
+
_tables = tables if isinstance(tables, list) else [None] * len(boxes)
|
|
324
747
|
if self.export_as_straight_boxes and len(boxes) > 0:
|
|
325
748
|
# If boxes are already straight OK, else fit a bounding rect
|
|
326
749
|
if boxes[0].ndim == 3:
|
|
327
750
|
# Iterate over pages and boxes
|
|
328
751
|
boxes = [np.concatenate((p_boxes.min(1), p_boxes.max(1)), 1) for p_boxes in boxes]
|
|
329
752
|
|
|
330
|
-
_pages = [
|
|
331
|
-
|
|
753
|
+
_pages = []
|
|
754
|
+
for (
|
|
755
|
+
page,
|
|
756
|
+
_idx,
|
|
757
|
+
shape,
|
|
758
|
+
page_boxes,
|
|
759
|
+
loc_scores,
|
|
760
|
+
word_preds,
|
|
761
|
+
word_crop_orientations,
|
|
762
|
+
orientation,
|
|
763
|
+
language,
|
|
764
|
+
page_regions,
|
|
765
|
+
page_table,
|
|
766
|
+
) in zip( # noqa: E501
|
|
767
|
+
pages,
|
|
768
|
+
range(len(boxes)),
|
|
769
|
+
page_shapes,
|
|
770
|
+
boxes,
|
|
771
|
+
objectness_scores,
|
|
772
|
+
text_preds,
|
|
773
|
+
crop_orientations,
|
|
774
|
+
_orientations,
|
|
775
|
+
_languages,
|
|
776
|
+
_regions,
|
|
777
|
+
_tables,
|
|
778
|
+
):
|
|
779
|
+
# Build the page tables and flag the words that belong to a table
|
|
780
|
+
page_tables, consumed = self._build_tables(page_boxes, word_preds, page_table)
|
|
781
|
+
if consumed.any():
|
|
782
|
+
# Remove the words assigned to a table from the regular blocks output
|
|
783
|
+
keep = ~consumed
|
|
784
|
+
page_boxes = page_boxes[keep]
|
|
785
|
+
loc_scores = loc_scores[keep]
|
|
786
|
+
word_preds = [wp for wp, k in zip(word_preds, keep) if k]
|
|
787
|
+
word_crop_orientations = [co for co, k in zip(word_crop_orientations, keep) if k]
|
|
788
|
+
|
|
789
|
+
page_blocks = self._build_blocks(
|
|
790
|
+
page_boxes,
|
|
791
|
+
loc_scores,
|
|
792
|
+
word_preds,
|
|
793
|
+
word_crop_orientations,
|
|
794
|
+
shape,
|
|
795
|
+
)
|
|
796
|
+
_page = Page(
|
|
332
797
|
page,
|
|
333
|
-
|
|
334
|
-
page_boxes,
|
|
335
|
-
loc_scores,
|
|
336
|
-
word_preds,
|
|
337
|
-
word_crop_orientations,
|
|
338
|
-
),
|
|
798
|
+
page_blocks,
|
|
339
799
|
_idx,
|
|
340
800
|
shape,
|
|
341
801
|
orientation,
|
|
342
802
|
language,
|
|
803
|
+
self._build_layout_elements(page_regions),
|
|
804
|
+
page_tables,
|
|
343
805
|
)
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
boxes,
|
|
349
|
-
objectness_scores,
|
|
350
|
-
text_preds,
|
|
351
|
-
crop_orientations,
|
|
352
|
-
_orientations,
|
|
353
|
-
_languages,
|
|
354
|
-
)
|
|
355
|
-
]
|
|
806
|
+
if self.keep_reading_order:
|
|
807
|
+
self._apply_reading_order(_page)
|
|
808
|
+
|
|
809
|
+
_pages.append(_page)
|
|
356
810
|
|
|
357
811
|
return Document(_pages)
|
|
358
812
|
|
|
@@ -366,6 +820,10 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
366
820
|
paragraph_break: relative length of the minimum space separating paragraphs
|
|
367
821
|
export_as_straight_boxes: if True, force straight boxes in the export (fit a rectangle
|
|
368
822
|
box to all rotated boxes). Else, keep the boxes format unchanged, no matter what it is.
|
|
823
|
+
keep_reading_order: if True, arrange the content of every page in reading order (cf.
|
|
824
|
+
:mod:`doctr.models.reading_order`). The reading direction is inferred from the recognized text.
|
|
825
|
+
When a layout is available it is always preferred: the text blocks and the page furniture
|
|
826
|
+
(headers, footers, ...) are taken from the layout regions.
|
|
369
827
|
"""
|
|
370
828
|
|
|
371
829
|
def __call__( # type: ignore[override]
|
|
@@ -378,6 +836,8 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
378
836
|
crop_orientations: list[dict[str, list[dict[str, Any]]]],
|
|
379
837
|
orientations: list[dict[str, Any]] | None = None,
|
|
380
838
|
languages: list[dict[str, Any]] | None = None,
|
|
839
|
+
regions: list[dict[str, Any] | None] | None = None,
|
|
840
|
+
tables: Sequence[dict[str, Any] | list[dict[str, Any]] | None] | None = None,
|
|
381
841
|
) -> KIEDocument:
|
|
382
842
|
"""Re-arrange detected words into structured predictions
|
|
383
843
|
|
|
@@ -394,18 +854,24 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
394
854
|
where each element is a dictionary containing the orientation (orientation + confidence)
|
|
395
855
|
languages: optional, list of N elements,
|
|
396
856
|
where each element is a dictionary containing the language (language + confidence)
|
|
857
|
+
regions: optional, list of N elements, where each element is a layout prediction
|
|
858
|
+
`{"boxes": (R, 4|4x2), "class_names": [...], "scores": [...]}` attached to each page
|
|
859
|
+
tables: optional, list of N elements, where each element is the table structure prediction(s) of a
|
|
860
|
+
page: a single grid `{"cells": [...], "num_rows": int, "num_cols": int}` or a list of such grids
|
|
861
|
+
(one per table region detected by the layout model). Words assigned to any table are removed from
|
|
862
|
+
the `blocks` output of that page. Unused for KIE documents, as tables are not supported in KIE.
|
|
397
863
|
|
|
398
864
|
Returns:
|
|
399
865
|
document object
|
|
400
866
|
"""
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
867
|
+
expected_len = len(boxes)
|
|
868
|
+
if any(
|
|
869
|
+
len(arg) != expected_len for arg in (pages, text_preds, crop_orientations, objectness_scores, page_shapes)
|
|
870
|
+
):
|
|
404
871
|
raise ValueError("All arguments are expected to be lists of the same size")
|
|
405
|
-
_orientations = (
|
|
406
|
-
|
|
407
|
-
)
|
|
408
|
-
_languages = languages if isinstance(languages, list) else [None] * len(boxes) # type: ignore[list-item]
|
|
872
|
+
_orientations = orientations if isinstance(orientations, list) else [None] * len(boxes)
|
|
873
|
+
_languages = languages if isinstance(languages, list) else [None] * len(boxes)
|
|
874
|
+
_regions = regions if isinstance(regions, list) else [None] * len(boxes)
|
|
409
875
|
if self.export_as_straight_boxes and len(boxes) > 0:
|
|
410
876
|
# If boxes are already straight OK, else fit a bounding rect
|
|
411
877
|
if next(iter(boxes[0].values())).ndim == 3:
|
|
@@ -428,6 +894,7 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
428
894
|
loc_scores[k],
|
|
429
895
|
word_preds[k],
|
|
430
896
|
word_crop_orientations[k],
|
|
897
|
+
shape,
|
|
431
898
|
)
|
|
432
899
|
for k in page_boxes.keys()
|
|
433
900
|
},
|
|
@@ -435,8 +902,9 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
435
902
|
shape,
|
|
436
903
|
orientation,
|
|
437
904
|
language,
|
|
905
|
+
self._build_layout_elements(page_regions),
|
|
438
906
|
)
|
|
439
|
-
for page, _idx, shape, page_boxes, loc_scores, word_preds, word_crop_orientations, orientation, language in zip( # noqa: E501
|
|
907
|
+
for page, _idx, shape, page_boxes, loc_scores, word_preds, word_crop_orientations, orientation, language, page_regions in zip( # noqa: E501
|
|
440
908
|
pages,
|
|
441
909
|
range(len(boxes)),
|
|
442
910
|
page_shapes,
|
|
@@ -446,6 +914,7 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
446
914
|
crop_orientations,
|
|
447
915
|
_orientations,
|
|
448
916
|
_languages,
|
|
917
|
+
_regions,
|
|
449
918
|
)
|
|
450
919
|
]
|
|
451
920
|
|
|
@@ -457,6 +926,7 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
457
926
|
objectness_scores: np.ndarray,
|
|
458
927
|
word_preds: list[tuple[str, float]],
|
|
459
928
|
crop_orientations: list[dict[str, Any]],
|
|
929
|
+
shape: tuple[int, int] | None = None,
|
|
460
930
|
) -> list[Prediction]:
|
|
461
931
|
"""Gather independent words in structured blocks
|
|
462
932
|
|
|
@@ -465,6 +935,7 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
465
935
|
objectness_scores: objectness scores of all detected words of the page
|
|
466
936
|
word_preds: list of all detected words of the page, of shape N
|
|
467
937
|
crop_orientations: list of orientations for each word crop
|
|
938
|
+
shape: the page dimensions (height, width), used to de-skew rotated pages exactly
|
|
468
939
|
|
|
469
940
|
Returns:
|
|
470
941
|
list of block elements
|
|
@@ -477,7 +948,7 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
477
948
|
|
|
478
949
|
# Decide whether we try to form lines
|
|
479
950
|
_boxes = boxes
|
|
480
|
-
idxs, _ = self._sort_boxes(_boxes if _boxes.ndim == 3 else _boxes[:, :4])
|
|
951
|
+
idxs, _ = self._sort_boxes(_boxes if _boxes.ndim == 3 else _boxes[:, :4], shape)
|
|
481
952
|
predictions = [
|
|
482
953
|
Prediction(
|
|
483
954
|
value=word_preds[idx][0],
|