python-doctr 1.1.0__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/models/builder.py
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
import bisect
|
|
8
|
+
import statistics
|
|
7
9
|
from collections.abc import Sequence
|
|
8
10
|
from typing import Any
|
|
9
11
|
|
|
@@ -13,6 +15,7 @@ from scipy.cluster.hierarchy import fclusterdata
|
|
|
13
15
|
from doctr.io.elements import (
|
|
14
16
|
Block,
|
|
15
17
|
Document,
|
|
18
|
+
Formula,
|
|
16
19
|
KIEDocument,
|
|
17
20
|
KIEPage,
|
|
18
21
|
LayoutElement,
|
|
@@ -23,9 +26,9 @@ from doctr.io.elements import (
|
|
|
23
26
|
TableCell,
|
|
24
27
|
Word,
|
|
25
28
|
)
|
|
29
|
+
from doctr.models.table_structure.grid import assemble_page_table
|
|
26
30
|
from doctr.utils.geometry import (
|
|
27
31
|
estimate_page_angle,
|
|
28
|
-
order_points,
|
|
29
32
|
resolve_enclosing_bbox,
|
|
30
33
|
resolve_enclosing_rbbox,
|
|
31
34
|
rotate_boxes,
|
|
@@ -34,6 +37,11 @@ from doctr.utils.repr import NestedObject
|
|
|
34
37
|
|
|
35
38
|
__all__ = ["DocumentBuilder"]
|
|
36
39
|
|
|
40
|
+
# Median word height of body text relative to the page width, above which `paragraph_break` is scaled up
|
|
41
|
+
_BODY_WORD_HEIGHT = 0.02
|
|
42
|
+
# Weight of the horizontal distance to a row, relative to the vertical offset, when several rows are level with a box
|
|
43
|
+
_ROW_DISTANCE_WEIGHT = 0.02
|
|
44
|
+
|
|
37
45
|
|
|
38
46
|
class DocumentBuilder(NestedObject):
|
|
39
47
|
"""Implements a document builder
|
|
@@ -41,7 +49,7 @@ class DocumentBuilder(NestedObject):
|
|
|
41
49
|
Args:
|
|
42
50
|
resolve_lines: whether words should be automatically grouped into lines
|
|
43
51
|
resolve_blocks: whether lines should be automatically grouped into blocks
|
|
44
|
-
paragraph_break: relative length of the minimum space separating paragraphs
|
|
52
|
+
paragraph_break: relative length of the minimum space separating paragraphs (scaled up for large type)
|
|
45
53
|
export_as_straight_boxes: if True, force straight boxes in the export (fit a rectangle
|
|
46
54
|
box to all rotated boxes). Else, keep the boxes format unchanged, no matter what it is.
|
|
47
55
|
keep_reading_order: if True, arrange the content of every page in reading order (cf.
|
|
@@ -105,7 +113,11 @@ class DocumentBuilder(NestedObject):
|
|
|
105
113
|
return (boxes[:, 0] + 2 * boxes[:, 3] / med_height).argsort(), boxes
|
|
106
114
|
|
|
107
115
|
def _resolve_sub_lines(
|
|
108
|
-
self,
|
|
116
|
+
self,
|
|
117
|
+
boxes: np.ndarray,
|
|
118
|
+
word_idcs: list[int],
|
|
119
|
+
break_dist: float | None = None,
|
|
120
|
+
word_regions: tuple[np.ndarray, np.ndarray] | None = None,
|
|
109
121
|
) -> list[list[int]]:
|
|
110
122
|
"""Split a line in sub_lines
|
|
111
123
|
|
|
@@ -113,45 +125,195 @@ class DocumentBuilder(NestedObject):
|
|
|
113
125
|
boxes: bounding boxes of shape (N, 4)
|
|
114
126
|
word_idcs: list of indexes for the words of the line
|
|
115
127
|
break_dist: horizontal distance above which the line is split (defaults to `self.paragraph_break`)
|
|
128
|
+
word_regions: optional region group of each box and coverage by each group (cf. `_word_regions`): the
|
|
129
|
+
line is also split between two distinct regions, unless one box lies in the region of the other
|
|
116
130
|
|
|
117
131
|
Returns:
|
|
118
132
|
A list of (sub-)lines computed from the original line (words)
|
|
119
133
|
"""
|
|
120
134
|
break_dist = self.paragraph_break if break_dist is None else break_dist
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
135
|
+
groups, coverage = word_regions if word_regions is not None else (None, None)
|
|
136
|
+
lines: list[list[int]] = []
|
|
137
|
+
right, region, prev = 0.0, -1, -1 # right edge, region and last word of the current sub-line
|
|
138
|
+
for idx in [word_idcs[i] for i in boxes[word_idcs, 0].argsort().tolist()]:
|
|
139
|
+
box_region = -1 if groups is None else int(groups[idx])
|
|
140
|
+
# A new sub-line after a gap of at least `break_dist` from the sub-line (a box can be nested in an earlier
|
|
141
|
+
# one: its max right edge is used), or between two distinct regions (e.g. columns with a narrow gutter)
|
|
142
|
+
if (
|
|
143
|
+
not lines
|
|
144
|
+
or not boxes[idx, 0] - right < break_dist
|
|
145
|
+
or (
|
|
146
|
+
coverage is not None
|
|
147
|
+
and box_region >= 0
|
|
148
|
+
and region >= 0
|
|
149
|
+
and box_region != region
|
|
150
|
+
and coverage[idx, region] < 0.5
|
|
151
|
+
and coverage[prev, box_region] < 0.5
|
|
152
|
+
)
|
|
153
|
+
):
|
|
154
|
+
lines.append([])
|
|
155
|
+
right, region = boxes[idx, 2], -1
|
|
156
|
+
lines[-1].append(idx)
|
|
157
|
+
right = max(right, boxes[idx, 2])
|
|
158
|
+
region = box_region if region < 0 else region
|
|
159
|
+
prev = idx
|
|
160
|
+
return lines
|
|
124
161
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
162
|
+
@staticmethod
|
|
163
|
+
def _word_regions(
|
|
164
|
+
boxes: np.ndarray,
|
|
165
|
+
region_geoms: list[Any],
|
|
166
|
+
region_labels: list[str],
|
|
167
|
+
shape: tuple[int, int] | None = None,
|
|
168
|
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
|
169
|
+
"""Assign each box to the group of the layout region covering it (or holding it horizontally)
|
|
132
170
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
horiz_break = False
|
|
171
|
+
Args:
|
|
172
|
+
boxes: bounding boxes of shape (N, 4) or (N, 4, 2)
|
|
173
|
+
region_geoms: the geometries of the layout regions
|
|
174
|
+
region_labels: the labels of the layout regions
|
|
175
|
+
shape: the page dimensions (height, width), used to de-skew rotated pages exactly
|
|
139
176
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
177
|
+
Returns:
|
|
178
|
+
the region group of each box (-1 for none) and the coverage of each box by each group, None without regions
|
|
179
|
+
"""
|
|
180
|
+
from doctr.models.reading_order.base import (
|
|
181
|
+
_box_areas,
|
|
182
|
+
_covering_regions,
|
|
183
|
+
_pairwise_overlaps,
|
|
184
|
+
_region_groups,
|
|
185
|
+
_to_boxes,
|
|
186
|
+
deskew_reading_geometries,
|
|
187
|
+
)
|
|
143
188
|
|
|
144
|
-
|
|
145
|
-
|
|
189
|
+
if len(region_geoms) == 0 or boxes.shape[0] == 0:
|
|
190
|
+
return None
|
|
191
|
+
word_geoms: Any = boxes
|
|
192
|
+
if boxes.ndim == 3: # de-skew the words and the regions together
|
|
193
|
+
word_geoms, region_geoms = deskew_reading_geometries(
|
|
194
|
+
list(boxes), region_geoms, page_shape=shape, angle_geoms=list(boxes)
|
|
195
|
+
)
|
|
196
|
+
regions, words = _to_boxes(region_geoms), _to_boxes(word_geoms)
|
|
197
|
+
groups = np.asarray(_region_groups(regions, region_labels))
|
|
198
|
+
covering = np.asarray(_covering_regions(words, regions, 0.5, region_labels))
|
|
199
|
+
inter_w, inter_h = _pairwise_overlaps(words, regions)
|
|
200
|
+
x_cov = inter_w / np.clip(words[:, 2:3] - words[:, 0:1], 1e-9, None)
|
|
201
|
+
y_cov = inter_h / np.clip(words[:, 3:4] - words[:, 1:2], 1e-9, None)
|
|
202
|
+
uncovered = np.flatnonzero(covering < 0)
|
|
203
|
+
if (
|
|
204
|
+
uncovered.size > 0
|
|
205
|
+
): # e.g. a word sticking out of a region slightly too short: the smallest region holding it
|
|
206
|
+
holding = (x_cov[uncovered] >= 0.9) & (y_cov[uncovered] >= 0.3)
|
|
207
|
+
smallest = np.where(holding, _box_areas(regions)[None, :], np.inf).argmin(axis=1)
|
|
208
|
+
covering[uncovered] = np.where(holding.any(axis=1), smallest, -1)
|
|
209
|
+
coverage = np.zeros((words.shape[0], regions.shape[0]))
|
|
210
|
+
np.maximum.at(coverage.T, groups, (x_cov * y_cov).T)
|
|
211
|
+
return np.where(covering >= 0, groups[covering], -1), coverage
|
|
146
212
|
|
|
147
|
-
|
|
213
|
+
@staticmethod
|
|
214
|
+
def _resolve_rows(boxes: np.ndarray, idxs: np.ndarray, y_med: float) -> list[list[int]]:
|
|
215
|
+
"""Group straight boxes into visual rows
|
|
216
|
+
|
|
217
|
+
A box joins the row whose horizontally closest boxes are the best aligned with it (less than half a median
|
|
218
|
+
height apart), which follows slanted lines and keeps the rows of offset columns apart. A box right under or over
|
|
219
|
+
one of them, away from the others (e.g. stacked figure labels), does not join the row.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
boxes: straight bounding boxes of shape (N, 4)
|
|
223
|
+
idxs: the order in which the boxes are visited (cf. `_sort_boxes`)
|
|
224
|
+
y_med: the median box height
|
|
148
225
|
|
|
149
|
-
|
|
226
|
+
Returns:
|
|
227
|
+
the rows (lists of box indices)
|
|
228
|
+
"""
|
|
229
|
+
if not y_med > 0:
|
|
230
|
+
return [[idx] for idx in idxs.tolist()]
|
|
231
|
+
lefts, rights = boxes[:, 0].tolist(), boxes[:, 2].tolist()
|
|
232
|
+
centers = ((boxes[:, 1] + boxes[:, 3]) / 2).tolist()
|
|
233
|
+
heights = (boxes[:, 3] - boxes[:, 1]).tolist()
|
|
234
|
+
row_lefts: list[list[float]] = [] # sorted left edges of the boxes of each row
|
|
235
|
+
row_boxes: list[list[int]] = [] # boxes of each row, sorted by left edge
|
|
236
|
+
spans: list[list[float]] = [] # highest and lowest box center of each row
|
|
237
|
+
|
|
238
|
+
def _stacked(idx: int, other: int, median: float) -> bool:
|
|
239
|
+
"""Whether two full-height boxes lie one over the other, `other` being level with its row"""
|
|
240
|
+
overlap = min(rights[idx], rights[other]) - max(lefts[idx], lefts[other])
|
|
241
|
+
return (
|
|
242
|
+
overlap >= 0.5 * min(rights[idx] - lefts[idx], rights[other] - lefts[other])
|
|
243
|
+
and abs(centers[idx] - centers[other]) >= y_med / 2
|
|
244
|
+
and abs(centers[other] - median) < y_med / 2
|
|
245
|
+
and min(heights[idx], heights[other]) >= 0.75 * y_med
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def _best_row(idx: int, rows: list[int]) -> int:
|
|
249
|
+
center, left, right = centers[idx], lefts[idx], rights[idx]
|
|
250
|
+
best, best_key = -1, (float("inf"), float("inf"))
|
|
251
|
+
for row in rows:
|
|
252
|
+
if spans[row][0] >= center + y_med / 2 or spans[row][1] <= center - y_med / 2 or not row_boxes[row]:
|
|
253
|
+
continue
|
|
254
|
+
# A few neighbors rather than one, so that a small mark (accent, punctuation) can't steer the box
|
|
255
|
+
pos = bisect.bisect_left(row_lefts[row], left)
|
|
256
|
+
nearest = sorted(
|
|
257
|
+
(max(lefts[other] - right, left - rights[other], 0.0), other)
|
|
258
|
+
for other in row_boxes[row][max(pos - 3, 0) : pos + 3]
|
|
259
|
+
)[:3]
|
|
260
|
+
median = statistics.median(centers[other] for _, other in nearest)
|
|
261
|
+
stacked = [_stacked(idx, other, median) for _, other in nearest]
|
|
262
|
+
if any(stacked) and all(dist >= y_med for (dist, _), flag in zip(nearest, stacked) if not flag):
|
|
263
|
+
continue
|
|
264
|
+
offset = abs(median - center)
|
|
265
|
+
# The distance breaks ties on slanted lines, where the next line can start before this one ends
|
|
266
|
+
key = (offset + _ROW_DISTANCE_WEIGHT * nearest[0][0], nearest[0][0])
|
|
267
|
+
if offset < y_med / 2 and key < best_key:
|
|
268
|
+
best, best_key = row, key
|
|
269
|
+
return best
|
|
270
|
+
|
|
271
|
+
def _add(row: int, idx: int) -> None:
|
|
272
|
+
if row == len(row_boxes):
|
|
273
|
+
row_lefts.append([])
|
|
274
|
+
row_boxes.append([])
|
|
275
|
+
spans.append([centers[idx], centers[idx]])
|
|
276
|
+
pos = bisect.bisect_right(row_lefts[row], lefts[idx])
|
|
277
|
+
row_lefts[row].insert(pos, lefts[idx])
|
|
278
|
+
row_boxes[row].insert(pos, idx)
|
|
279
|
+
spans[row] = [min(spans[row][0], centers[idx]), max(spans[row][1], centers[idx])]
|
|
280
|
+
|
|
281
|
+
row_of: dict[int, int] = {}
|
|
282
|
+
active: list[int] = [] # rows which can still receive a box: the boxes come roughly top to bottom
|
|
283
|
+
for idx in idxs.tolist():
|
|
284
|
+
active = [row for row in active if spans[row][1] > centers[idx] - 2 * y_med]
|
|
285
|
+
row = _best_row(idx, active)
|
|
286
|
+
if row < 0:
|
|
287
|
+
row = len(row_boxes)
|
|
288
|
+
active.append(row)
|
|
289
|
+
_add(row, idx)
|
|
290
|
+
row_of[idx] = row
|
|
291
|
+
# Assign each box again once all rows exist: a box visited before the rest of its line (e.g. a short word
|
|
292
|
+
# ending higher) may have joined a level row of another column
|
|
293
|
+
highest, lowest = np.asarray(spans).T
|
|
294
|
+
for idx in idxs.tolist():
|
|
295
|
+
own = row_of[idx]
|
|
296
|
+
pos = row_boxes[own].index(idx)
|
|
297
|
+
del row_boxes[own][pos], row_lefts[own][pos]
|
|
298
|
+
candidates = np.flatnonzero((highest < centers[idx] + y_med / 2) & (lowest > centers[idx] - y_med / 2))
|
|
299
|
+
row = _best_row(idx, candidates.tolist())
|
|
300
|
+
row_of[idx] = own if row < 0 else row
|
|
301
|
+
_add(row_of[idx], idx)
|
|
302
|
+
|
|
303
|
+
return [row for row in row_boxes if row]
|
|
304
|
+
|
|
305
|
+
def _resolve_lines(
|
|
306
|
+
self,
|
|
307
|
+
boxes: np.ndarray,
|
|
308
|
+
shape: tuple[int, int] | None = None,
|
|
309
|
+
word_regions: tuple[np.ndarray, np.ndarray] | None = None,
|
|
310
|
+
) -> list[list[int]]:
|
|
150
311
|
"""Order boxes to group them in lines
|
|
151
312
|
|
|
152
313
|
Args:
|
|
153
314
|
boxes: bounding boxes of shape (N, 4) or (N, 4, 2) in case of rotated bbox
|
|
154
315
|
shape: the page dimensions (height, width), used to de-skew rotated pages exactly
|
|
316
|
+
word_regions: optional region group of each box and coverage by each group (cf. `_word_regions`)
|
|
155
317
|
|
|
156
318
|
Returns:
|
|
157
319
|
nested list of box indices
|
|
@@ -163,31 +325,7 @@ class DocumentBuilder(NestedObject):
|
|
|
163
325
|
y_med = np.median(boxes[:, 3] - boxes[:, 1])
|
|
164
326
|
|
|
165
327
|
# Group the words into visual rows
|
|
166
|
-
rows =
|
|
167
|
-
words = [idxs[0]] # Assign the top-left word to the first line
|
|
168
|
-
# Define a mean y-center for the line
|
|
169
|
-
y_center_sum = boxes[idxs[0]][[1, 3]].mean()
|
|
170
|
-
|
|
171
|
-
for idx in idxs[1:]:
|
|
172
|
-
vert_break = True
|
|
173
|
-
|
|
174
|
-
# Compute y_dist
|
|
175
|
-
y_dist = abs(boxes[idx][[1, 3]].mean() - y_center_sum / len(words))
|
|
176
|
-
# If y-center of the box is close enough to mean y-center of the line, same line
|
|
177
|
-
if y_dist < y_med / 2:
|
|
178
|
-
vert_break = False
|
|
179
|
-
|
|
180
|
-
if vert_break:
|
|
181
|
-
rows.append(words)
|
|
182
|
-
words = []
|
|
183
|
-
y_center_sum = 0
|
|
184
|
-
|
|
185
|
-
words.append(idx)
|
|
186
|
-
y_center_sum += boxes[idx][[1, 3]].mean()
|
|
187
|
-
|
|
188
|
-
# Use the remaining words to form the last row
|
|
189
|
-
if len(words) > 0:
|
|
190
|
-
rows.append(words)
|
|
328
|
+
rows = self._resolve_rows(boxes, idxs, float(y_med))
|
|
191
329
|
|
|
192
330
|
# Split the rows horizontally, using a break distance adapted to the page spacing.
|
|
193
331
|
# The gaps are collected with one vectorized pass per row (the loop is over rows, not word pairs).
|
|
@@ -199,22 +337,23 @@ class DocumentBuilder(NestedObject):
|
|
|
199
337
|
row_idcs = np.asarray(row)
|
|
200
338
|
row_idcs = row_idcs[np.argsort(boxes[row_idcs, 0], kind="stable")]
|
|
201
339
|
n_pairs += row_idcs.shape[0] - 1
|
|
202
|
-
gap_chunks.append(boxes[row_idcs[1:], 0] - boxes[row_idcs
|
|
340
|
+
gap_chunks.append(boxes[row_idcs[1:], 0] - np.maximum.accumulate(boxes[row_idcs, 2])[:-1])
|
|
203
341
|
all_gaps = np.concatenate(gap_chunks) if gap_chunks else np.empty(0, dtype=boxes.dtype)
|
|
204
342
|
pos_gaps = all_gaps[all_gaps > 0]
|
|
205
343
|
# Median word height, converted to width units
|
|
206
344
|
aspect = (shape[0] / shape[1]) if shape is not None else 1.0
|
|
207
345
|
floor = float(y_med) * aspect
|
|
346
|
+
cap = self.paragraph_break * max(1.0, floor / _BODY_WORD_HEIGHT)
|
|
208
347
|
if pos_gaps.shape[0] >= 5 and pos_gaps.shape[0] >= 0.5 * n_pairs:
|
|
209
|
-
break_dist = min(
|
|
348
|
+
break_dist = min(cap, max(3.0 * float(np.median(pos_gaps)), floor))
|
|
210
349
|
elif n_pairs >= 5:
|
|
211
|
-
break_dist = min(
|
|
350
|
+
break_dist = min(cap, floor)
|
|
212
351
|
else:
|
|
213
352
|
break_dist = self.paragraph_break
|
|
214
353
|
|
|
215
354
|
lines = []
|
|
216
355
|
for row in rows:
|
|
217
|
-
lines.extend(self._resolve_sub_lines(boxes, row, break_dist))
|
|
356
|
+
lines.extend(self._resolve_sub_lines(boxes, row, break_dist, word_regions))
|
|
218
357
|
|
|
219
358
|
return lines
|
|
220
359
|
|
|
@@ -311,273 +450,109 @@ class DocumentBuilder(NestedObject):
|
|
|
311
450
|
elements.append(LayoutElement(layout_type=str(cname), confidence=float(score), geometry=geometry))
|
|
312
451
|
return elements
|
|
313
452
|
|
|
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
453
|
def _build_tables(
|
|
425
454
|
self,
|
|
426
455
|
boxes: np.ndarray,
|
|
427
456
|
word_preds: list[tuple[str, float]],
|
|
428
457
|
page_table: dict[str, Any] | list[dict[str, Any]] | None,
|
|
458
|
+
page_shape: tuple[int, int],
|
|
429
459
|
) -> tuple[list[Table], np.ndarray]:
|
|
430
|
-
"""
|
|
460
|
+
"""Build the tables of a page from their structure and the words of the page.
|
|
431
461
|
|
|
432
462
|
Args:
|
|
433
463
|
boxes: word boxes of the page, of shape (N, 4) or (N, 4, 2), in relative coordinates
|
|
434
464
|
word_preds: list of (text, confidence) for each of the N words
|
|
435
465
|
page_table: the table structure prediction(s) for the page. Either a single grid
|
|
436
466
|
`{"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
|
|
467
|
+
"num_cols"}` (cell geometries in page-relative coordinates), a list of such grids, or None. The cells
|
|
468
|
+
may list the indices of their words (`"words"`, cf. `TablePredictor.predict_regions`), otherwise the
|
|
469
|
+
words are assigned to them
|
|
470
|
+
page_shape: the (height, width) of the page
|
|
438
471
|
|
|
439
472
|
Returns:
|
|
440
473
|
a tuple with the list of `Table` objects of the page (one per provided table) and a boolean mask of
|
|
441
474
|
shape (N,) that is True for words assigned to a table (to be removed from `blocks`)
|
|
442
475
|
"""
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
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]] = []
|
|
476
|
+
consumed = np.zeros(boxes.shape[0], dtype=bool)
|
|
477
|
+
raw_tables = [] if page_table is None else [page_table] if isinstance(page_table, dict) else list(page_table)
|
|
478
|
+
# Geometries follow the word boxes: 2-point boxes for (N, 4), 4-point polygons for (N, 4, 2)
|
|
479
|
+
straight = boxes.ndim != 3
|
|
480
|
+
tables: list[Table] = []
|
|
451
481
|
for raw in raw_tables:
|
|
452
482
|
if not raw or len(raw.get("cells", [])) == 0:
|
|
453
483
|
continue
|
|
454
|
-
cells,
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
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())
|
|
484
|
+
cells, num_rows, num_cols = assemble_page_table(raw["cells"], boxes, page_shape, consumed)
|
|
485
|
+
table_cells = []
|
|
486
|
+
for cell in cells:
|
|
487
|
+
words = [word_preds[idx] for idx in cell["words"]]
|
|
549
488
|
table_cells.append(
|
|
550
489
|
TableCell(
|
|
551
|
-
value=value,
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
490
|
+
value=" ".join(value for value, _ in words),
|
|
491
|
+
# An empty cell falls back to the score of the table model
|
|
492
|
+
confidence=float(np.mean([conf for _, conf in words])) if words else float(cell["score"] or 0),
|
|
493
|
+
geometry=self._export_geometry(cell["geometry"], straight),
|
|
494
|
+
row_start=cell["row_start"],
|
|
495
|
+
row_end=cell["row_end"],
|
|
496
|
+
col_start=cell["col_start"],
|
|
497
|
+
col_end=cell["col_end"],
|
|
498
|
+
objectness_score=cell["score"],
|
|
558
499
|
)
|
|
559
500
|
)
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
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(
|
|
501
|
+
pts = np.concatenate([cell["geometry"] for cell in cells])
|
|
502
|
+
(xmin, ymin), (xmax, ymax) = pts.min(axis=0), pts.max(axis=0)
|
|
503
|
+
# The cells made from words have no score
|
|
504
|
+
scores = [cell["score"] for cell in cells if cell["score"] is not None]
|
|
505
|
+
tables.append(
|
|
571
506
|
Table(
|
|
572
507
|
cells=table_cells,
|
|
573
|
-
num_rows=
|
|
574
|
-
num_cols=
|
|
575
|
-
geometry=
|
|
576
|
-
|
|
508
|
+
num_rows=num_rows,
|
|
509
|
+
num_cols=num_cols,
|
|
510
|
+
geometry=self._export_geometry(
|
|
511
|
+
np.array([[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]), straight
|
|
512
|
+
),
|
|
513
|
+
confidence=float(np.mean(scores)) if scores else 0.0,
|
|
514
|
+
)
|
|
515
|
+
)
|
|
516
|
+
return tables, consumed
|
|
517
|
+
|
|
518
|
+
def _build_formulas(self, page_formulas: list[dict[str, Any]] | None, straight: bool) -> list[Formula]:
|
|
519
|
+
"""Build the formulas of a page from their recognition
|
|
520
|
+
|
|
521
|
+
Args:
|
|
522
|
+
page_formulas: the formulas recognized on the page `{"geometry", "value", "confidence", "score"}`
|
|
523
|
+
(cf. `FormulaPredictor.predict_regions`), with a straight box (4,) or a polygon (4, 2) in relative
|
|
524
|
+
coordinates, or None
|
|
525
|
+
straight: whether to export the geometries as straight boxes (else as polygons)
|
|
526
|
+
|
|
527
|
+
Returns:
|
|
528
|
+
the list of `Formula` objects of the page, the empty predictions left out
|
|
529
|
+
"""
|
|
530
|
+
formulas: list[Formula] = []
|
|
531
|
+
for raw in page_formulas or []:
|
|
532
|
+
if not raw.get("value"):
|
|
533
|
+
continue
|
|
534
|
+
geom = np.asarray(raw["geometry"], dtype=np.float64)
|
|
535
|
+
if geom.ndim == 1: # (xmin, ymin, xmax, ymax)
|
|
536
|
+
geom = np.array([[geom[0], geom[1]], [geom[2], geom[1]], [geom[2], geom[3]], [geom[0], geom[3]]])
|
|
537
|
+
formulas.append(
|
|
538
|
+
Formula(
|
|
539
|
+
value=raw["value"],
|
|
540
|
+
confidence=float(raw["confidence"]),
|
|
541
|
+
geometry=self._export_geometry(geom, straight or self.export_as_straight_boxes),
|
|
542
|
+
objectness_score=None if raw.get("score") is None else float(raw["score"]),
|
|
577
543
|
)
|
|
578
544
|
)
|
|
545
|
+
return formulas
|
|
579
546
|
|
|
580
|
-
|
|
547
|
+
@staticmethod
|
|
548
|
+
def _export_geometry(poly: np.ndarray, straight: bool) -> Any:
|
|
549
|
+
"""Export a (4, 2) polygon as a straight 2-point box or as a 4-point polygon, with Python floats"""
|
|
550
|
+
if straight:
|
|
551
|
+
return (
|
|
552
|
+
(float(poly[:, 0].min()), float(poly[:, 1].min())),
|
|
553
|
+
(float(poly[:, 0].max()), float(poly[:, 1].max())),
|
|
554
|
+
)
|
|
555
|
+
return tuple(tuple(float(c) for c in pt) for pt in poly.tolist())
|
|
581
556
|
|
|
582
557
|
def _build_blocks(
|
|
583
558
|
self,
|
|
@@ -586,6 +561,7 @@ class DocumentBuilder(NestedObject):
|
|
|
586
561
|
word_preds: list[tuple[str, float]],
|
|
587
562
|
crop_orientations: list[dict[str, Any]],
|
|
588
563
|
shape: tuple[int, int] | None = None,
|
|
564
|
+
layout: list[LayoutElement] | None = None,
|
|
589
565
|
) -> list[Block]:
|
|
590
566
|
"""Gather independent words in structured blocks
|
|
591
567
|
|
|
@@ -597,6 +573,7 @@ class DocumentBuilder(NestedObject):
|
|
|
597
573
|
the general orientation (orientations + confidences) of the crops
|
|
598
574
|
shape: the page dimensions (height, width), used to de-skew rotated pages exactly when
|
|
599
575
|
resolving lines
|
|
576
|
+
layout: optional layout regions of the page
|
|
600
577
|
|
|
601
578
|
Returns:
|
|
602
579
|
list of block elements
|
|
@@ -607,44 +584,32 @@ class DocumentBuilder(NestedObject):
|
|
|
607
584
|
if boxes.shape[0] == 0:
|
|
608
585
|
return []
|
|
609
586
|
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
lines = self.
|
|
614
|
-
# Decide whether we try to form blocks
|
|
615
|
-
if self.resolve_blocks and len(lines) > 1:
|
|
616
|
-
_blocks = self._resolve_blocks(_boxes if _boxes.ndim == 3 else _boxes[:, :4], lines)
|
|
617
|
-
else:
|
|
618
|
-
_blocks = [lines]
|
|
587
|
+
straight_or_rotated = boxes if boxes.ndim == 3 else boxes[:, :4]
|
|
588
|
+
if not self.resolve_lines:
|
|
589
|
+
# One line for all boxes, one block for the line
|
|
590
|
+
lines = [self._sort_boxes(straight_or_rotated, shape)[0].tolist()]
|
|
619
591
|
else:
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
crop_orientations[idx],
|
|
632
|
-
)
|
|
633
|
-
if boxes.ndim == 3
|
|
634
|
-
else Word(
|
|
635
|
-
*word_preds[idx],
|
|
636
|
-
((boxes[idx, 0], boxes[idx, 1]), (boxes[idx, 2], boxes[idx, 3])),
|
|
637
|
-
float(objectness_scores[idx]),
|
|
638
|
-
crop_orientations[idx],
|
|
639
|
-
)
|
|
640
|
-
for idx in line
|
|
641
|
-
])
|
|
642
|
-
for line in lines
|
|
643
|
-
])
|
|
644
|
-
for lines in _blocks
|
|
645
|
-
]
|
|
592
|
+
word_regions = (
|
|
593
|
+
self._word_regions(boxes, [elt.geometry for elt in layout], [elt.type for elt in layout], shape)
|
|
594
|
+
if layout
|
|
595
|
+
else None
|
|
596
|
+
)
|
|
597
|
+
lines = self._resolve_lines(straight_or_rotated, shape, word_regions)
|
|
598
|
+
blocks = (
|
|
599
|
+
self._resolve_blocks(straight_or_rotated, lines)
|
|
600
|
+
if self.resolve_lines and self.resolve_blocks and len(lines) > 1
|
|
601
|
+
else [lines]
|
|
602
|
+
)
|
|
646
603
|
|
|
647
|
-
|
|
604
|
+
def _word(idx: int) -> Word:
|
|
605
|
+
geometry = (
|
|
606
|
+
tuple(tuple(pt) for pt in boxes[idx].tolist())
|
|
607
|
+
if boxes.ndim == 3
|
|
608
|
+
else ((boxes[idx, 0], boxes[idx, 1]), (boxes[idx, 2], boxes[idx, 3]))
|
|
609
|
+
)
|
|
610
|
+
return Word(*word_preds[idx], geometry, float(objectness_scores[idx]), crop_orientations[idx]) # type: ignore[arg-type]
|
|
611
|
+
|
|
612
|
+
return [Block([Line([_word(idx) for idx in line]) for line in block]) for block in blocks]
|
|
648
613
|
|
|
649
614
|
@staticmethod
|
|
650
615
|
def _words_to_boxes(words: list[Word]) -> np.ndarray:
|
|
@@ -672,10 +637,15 @@ class DocumentBuilder(NestedObject):
|
|
|
672
637
|
words = [word for block in page.blocks for line in block.lines for word in line.words]
|
|
673
638
|
if len(words) < 2:
|
|
674
639
|
return
|
|
675
|
-
|
|
640
|
+
word_boxes = self._words_to_boxes(words)
|
|
641
|
+
word_regions = self._word_regions(
|
|
642
|
+
word_boxes, [elt.geometry for elt in page.layout], [elt.type for elt in page.layout], page.dimensions
|
|
643
|
+
)
|
|
644
|
+
groups = self._resolve_lines(word_boxes, page.dimensions, word_regions)
|
|
676
645
|
page.blocks = [Block([Line([words[idx] for idx in group]) for group in groups])]
|
|
677
646
|
|
|
678
|
-
|
|
647
|
+
# With the figures: the result is stored back in the cache read by the exports
|
|
648
|
+
items, labels, direction = page_reading_order(page, include_figures=True)
|
|
679
649
|
blocks = [item for item in items if isinstance(item, Block)]
|
|
680
650
|
page.blocks = (
|
|
681
651
|
[Block(lines=[Line([word for block in blocks for line in block.lines for word in line.words])])]
|
|
@@ -708,6 +678,7 @@ class DocumentBuilder(NestedObject):
|
|
|
708
678
|
languages: list[dict[str, Any]] | None = None,
|
|
709
679
|
regions: list[dict[str, Any] | None] | None = None,
|
|
710
680
|
tables: Sequence[dict[str, Any] | list[dict[str, Any]] | None] | None = None,
|
|
681
|
+
formulas: Sequence[list[dict[str, Any]] | None] | None = None,
|
|
711
682
|
) -> Document:
|
|
712
683
|
"""Re-arrange detected words into structured blocks
|
|
713
684
|
|
|
@@ -730,6 +701,8 @@ class DocumentBuilder(NestedObject):
|
|
|
730
701
|
page: a single grid `{"cells": [...], "num_rows": int, "num_cols": int}` or a list of such grids
|
|
731
702
|
(one per table region detected by the layout model). Words assigned to any table are removed from
|
|
732
703
|
the `blocks` output of that page.
|
|
704
|
+
formulas: optional, list of N elements, where each element is the list of formulas recognized on a page
|
|
705
|
+
`{"geometry", "value", "confidence", "score"}` (cf. `FormulaPredictor.predict_regions`)
|
|
733
706
|
|
|
734
707
|
Returns:
|
|
735
708
|
document object
|
|
@@ -744,6 +717,7 @@ class DocumentBuilder(NestedObject):
|
|
|
744
717
|
_languages = languages if isinstance(languages, list) else [None] * len(boxes)
|
|
745
718
|
_regions = regions if isinstance(regions, list) else [None] * len(boxes)
|
|
746
719
|
_tables = tables if isinstance(tables, list) else [None] * len(boxes)
|
|
720
|
+
_formulas = formulas if isinstance(formulas, list) else [None] * len(boxes)
|
|
747
721
|
if self.export_as_straight_boxes and len(boxes) > 0:
|
|
748
722
|
# If boxes are already straight OK, else fit a bounding rect
|
|
749
723
|
if boxes[0].ndim == 3:
|
|
@@ -763,6 +737,7 @@ class DocumentBuilder(NestedObject):
|
|
|
763
737
|
language,
|
|
764
738
|
page_regions,
|
|
765
739
|
page_table,
|
|
740
|
+
page_formulas,
|
|
766
741
|
) in zip( # noqa: E501
|
|
767
742
|
pages,
|
|
768
743
|
range(len(boxes)),
|
|
@@ -775,9 +750,10 @@ class DocumentBuilder(NestedObject):
|
|
|
775
750
|
_languages,
|
|
776
751
|
_regions,
|
|
777
752
|
_tables,
|
|
753
|
+
_formulas,
|
|
778
754
|
):
|
|
779
755
|
# 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)
|
|
756
|
+
page_tables, consumed = self._build_tables(page_boxes, word_preds, page_table, shape)
|
|
781
757
|
if consumed.any():
|
|
782
758
|
# Remove the words assigned to a table from the regular blocks output
|
|
783
759
|
keep = ~consumed
|
|
@@ -786,12 +762,14 @@ class DocumentBuilder(NestedObject):
|
|
|
786
762
|
word_preds = [wp for wp, k in zip(word_preds, keep) if k]
|
|
787
763
|
word_crop_orientations = [co for co, k in zip(word_crop_orientations, keep) if k]
|
|
788
764
|
|
|
765
|
+
page_layout = self._build_layout_elements(page_regions)
|
|
789
766
|
page_blocks = self._build_blocks(
|
|
790
767
|
page_boxes,
|
|
791
768
|
loc_scores,
|
|
792
769
|
word_preds,
|
|
793
770
|
word_crop_orientations,
|
|
794
771
|
shape,
|
|
772
|
+
page_layout,
|
|
795
773
|
)
|
|
796
774
|
_page = Page(
|
|
797
775
|
page,
|
|
@@ -800,8 +778,9 @@ class DocumentBuilder(NestedObject):
|
|
|
800
778
|
shape,
|
|
801
779
|
orientation,
|
|
802
780
|
language,
|
|
803
|
-
|
|
781
|
+
page_layout,
|
|
804
782
|
page_tables,
|
|
783
|
+
self._build_formulas(page_formulas, straight=page_boxes.ndim != 3),
|
|
805
784
|
)
|
|
806
785
|
if self.keep_reading_order:
|
|
807
786
|
self._apply_reading_order(_page)
|
|
@@ -817,7 +796,7 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
817
796
|
Args:
|
|
818
797
|
resolve_lines: whether words should be automatically grouped into lines
|
|
819
798
|
resolve_blocks: whether lines should be automatically grouped into blocks
|
|
820
|
-
paragraph_break: relative length of the minimum space separating paragraphs
|
|
799
|
+
paragraph_break: relative length of the minimum space separating paragraphs (scaled up for large type)
|
|
821
800
|
export_as_straight_boxes: if True, force straight boxes in the export (fit a rectangle
|
|
822
801
|
box to all rotated boxes). Else, keep the boxes format unchanged, no matter what it is.
|
|
823
802
|
keep_reading_order: if True, arrange the content of every page in reading order (cf.
|
|
@@ -838,6 +817,7 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
838
817
|
languages: list[dict[str, Any]] | None = None,
|
|
839
818
|
regions: list[dict[str, Any] | None] | None = None,
|
|
840
819
|
tables: Sequence[dict[str, Any] | list[dict[str, Any]] | None] | None = None,
|
|
820
|
+
formulas: Sequence[list[dict[str, Any]] | None] | None = None,
|
|
841
821
|
) -> KIEDocument:
|
|
842
822
|
"""Re-arrange detected words into structured predictions
|
|
843
823
|
|
|
@@ -860,6 +840,8 @@ class KIEDocumentBuilder(DocumentBuilder):
|
|
|
860
840
|
page: a single grid `{"cells": [...], "num_rows": int, "num_cols": int}` or a list of such grids
|
|
861
841
|
(one per table region detected by the layout model). Words assigned to any table are removed from
|
|
862
842
|
the `blocks` output of that page. Unused for KIE documents, as tables are not supported in KIE.
|
|
843
|
+
formulas: optional, list of N elements, where each element is the list of formulas recognized on a page.
|
|
844
|
+
Unused for KIE documents, as formulas are not supported in KIE.
|
|
863
845
|
|
|
864
846
|
Returns:
|
|
865
847
|
document object
|