python-doctr 1.0.1__py3-none-any.whl → 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/models/builder.py CHANGED
@@ -4,17 +4,44 @@
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
9
+ from collections.abc import Sequence
7
10
  from typing import Any
8
11
 
9
12
  import numpy as np
10
13
  from scipy.cluster.hierarchy import fclusterdata
11
14
 
12
- from doctr.io.elements import Block, Document, KIEDocument, KIEPage, Line, Page, Prediction, Word
13
- from doctr.utils.geometry import estimate_page_angle, resolve_enclosing_bbox, resolve_enclosing_rbbox, rotate_boxes
15
+ from doctr.io.elements import (
16
+ Block,
17
+ Document,
18
+ Formula,
19
+ KIEDocument,
20
+ KIEPage,
21
+ LayoutElement,
22
+ Line,
23
+ Page,
24
+ Prediction,
25
+ Table,
26
+ TableCell,
27
+ Word,
28
+ )
29
+ from doctr.models.table_structure.grid import assemble_page_table
30
+ from doctr.utils.geometry import (
31
+ estimate_page_angle,
32
+ resolve_enclosing_bbox,
33
+ resolve_enclosing_rbbox,
34
+ rotate_boxes,
35
+ )
14
36
  from doctr.utils.repr import NestedObject
15
37
 
16
38
  __all__ = ["DocumentBuilder"]
17
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
+
18
45
 
19
46
  class DocumentBuilder(NestedObject):
20
47
  """Implements a document builder
@@ -22,9 +49,13 @@ class DocumentBuilder(NestedObject):
22
49
  Args:
23
50
  resolve_lines: whether words should be automatically grouped into lines
24
51
  resolve_blocks: whether lines should be automatically grouped into blocks
25
- 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)
26
53
  export_as_straight_boxes: if True, force straight boxes in the export (fit a rectangle
27
54
  box to all rotated boxes). Else, keep the boxes format unchanged, no matter what it is.
55
+ keep_reading_order: if True, arrange the content of every page in reading order (cf.
56
+ :mod:`doctr.models.reading_order`). The reading direction is inferred from the recognized text.
57
+ When a layout is available it is always preferred: the text blocks and the page furniture
58
+ (headers, footers, ...) are taken from the layout regions.
28
59
  """
29
60
 
30
61
  def __init__(
@@ -33,18 +64,21 @@ class DocumentBuilder(NestedObject):
33
64
  resolve_blocks: bool = False,
34
65
  paragraph_break: float = 0.035,
35
66
  export_as_straight_boxes: bool = False,
67
+ keep_reading_order: bool = False,
36
68
  ) -> None:
37
69
  self.resolve_lines = resolve_lines
38
70
  self.resolve_blocks = resolve_blocks
39
71
  self.paragraph_break = paragraph_break
40
72
  self.export_as_straight_boxes = export_as_straight_boxes
73
+ self.keep_reading_order = keep_reading_order
41
74
 
42
75
  @staticmethod
43
- def _sort_boxes(boxes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
76
+ def _sort_boxes(boxes: np.ndarray, shape: tuple[int, int] | None = None) -> tuple[np.ndarray, np.ndarray]:
44
77
  """Sort bounding boxes from top to bottom, left to right
45
78
 
46
79
  Args:
47
- boxes: bounding boxes of shape (N, 4) or (N, 4, 2) (in case of rotated bbox)
80
+ boxes: bounding boxes of shape (N, 4) or (N, 4, 2)
81
+ shape: the page dimensions (height, width)
48
82
 
49
83
  Returns:
50
84
  tuple: indices of ordered boxes of shape (N,), boxes
@@ -53,95 +87,273 @@ class DocumentBuilder(NestedObject):
53
87
  so that we fit the lines afterwards to the straigthened page
54
88
  """
55
89
  if boxes.ndim == 3:
56
- boxes = rotate_boxes(
90
+ height, width = shape if shape is not None else (1024, 1024)
91
+ scale = np.array([width, height], dtype=boxes.dtype)
92
+ angle = estimate_page_angle(boxes * scale)
93
+ rotated = rotate_boxes(
57
94
  loc_preds=boxes,
58
- angle=-estimate_page_angle(boxes),
59
- orig_shape=(1024, 1024),
60
- min_angle=5.0,
95
+ angle=-angle,
96
+ orig_shape=(height, width),
97
+ min_angle=1.0,
61
98
  )
62
- boxes = np.concatenate((boxes.min(1), boxes.max(1)), -1)
63
- return (boxes[:, 0] + 2 * boxes[:, 3] / np.median(boxes[:, 3] - boxes[:, 1])).argsort(), boxes
64
-
65
- def _resolve_sub_lines(self, boxes: np.ndarray, word_idcs: list[int]) -> list[list[int]]:
99
+ # On rotated pages, detectors can output a mix of properly rotated polygons and axis-aligned
100
+ # enclosing boxes. A box that is not itself rotated carries no rotation to remove
101
+ if abs(angle) >= 1.0:
102
+ edges = (boxes[:, 1] - boxes[:, 0]) * scale
103
+ own_angle = np.rad2deg(np.arctan2(-edges[:, 1], edges[:, 0]))
104
+ keep = np.abs(own_angle) < abs(angle) / 2
105
+ if keep.any():
106
+ centers = boxes.mean(axis=1, keepdims=True)
107
+ new_centers = rotated.mean(axis=1, keepdims=True)
108
+ rotated[keep] = boxes[keep] - centers[keep] + new_centers[keep]
109
+ boxes = np.concatenate((rotated.min(1), rotated.max(1)), -1)
110
+ med_height = float(np.median(boxes[:, 3] - boxes[:, 1]))
111
+ if not np.isfinite(med_height) or med_height <= 0:
112
+ med_height = 1.0
113
+ return (boxes[:, 0] + 2 * boxes[:, 3] / med_height).argsort(), boxes
114
+
115
+ def _resolve_sub_lines(
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,
121
+ ) -> list[list[int]]:
66
122
  """Split a line in sub_lines
67
123
 
68
124
  Args:
69
125
  boxes: bounding boxes of shape (N, 4)
70
126
  word_idcs: list of indexes for the words of the line
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
71
130
 
72
131
  Returns:
73
132
  A list of (sub-)lines computed from the original line (words)
74
133
  """
75
- lines = []
76
- # Sort words horizontally
77
- word_idcs = [word_idcs[idx] for idx in boxes[word_idcs, 0].argsort().tolist()]
134
+ break_dist = self.paragraph_break if break_dist is None else break_dist
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
78
161
 
79
- # Eventually split line horizontally
80
- if len(word_idcs) < 2:
81
- lines.append(word_idcs)
82
- else:
83
- sub_line = [word_idcs[0]]
84
- for i in word_idcs[1:]:
85
- horiz_break = True
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)
86
170
 
87
- prev_box = boxes[sub_line[-1]]
88
- # Compute distance between boxes
89
- dist = boxes[i, 0] - prev_box[2]
90
- # If distance between boxes is lower than paragraph break, same sub-line
91
- if dist < self.paragraph_break:
92
- 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
93
176
 
94
- if horiz_break:
95
- lines.append(sub_line)
96
- sub_line = []
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
+ )
188
+
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
97
212
 
98
- sub_line.append(i)
99
- lines.append(sub_line)
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
100
216
 
101
- return lines
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
225
+
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
+ )
102
247
 
103
- def _resolve_lines(self, boxes: np.ndarray) -> list[list[int]]:
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]]:
104
311
  """Order boxes to group them in lines
105
312
 
106
313
  Args:
107
314
  boxes: bounding boxes of shape (N, 4) or (N, 4, 2) in case of rotated bbox
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`)
108
317
 
109
318
  Returns:
110
319
  nested list of box indices
111
320
  """
112
321
  # Sort boxes, and straighten the boxes if they are rotated
113
- idxs, boxes = self._sort_boxes(boxes)
322
+ idxs, boxes = self._sort_boxes(boxes, shape)
114
323
 
115
324
  # Compute median for boxes heights
116
325
  y_med = np.median(boxes[:, 3] - boxes[:, 1])
117
326
 
118
- lines = []
119
- words = [idxs[0]] # Assign the top-left word to the first line
120
- # Define a mean y-center for the line
121
- y_center_sum = boxes[idxs[0]][[1, 3]].mean()
122
-
123
- for idx in idxs[1:]:
124
- vert_break = True
125
-
126
- # Compute y_dist
127
- y_dist = abs(boxes[idx][[1, 3]].mean() - y_center_sum / len(words))
128
- # If y-center of the box is close enough to mean y-center of the line, same line
129
- if y_dist < y_med / 2:
130
- vert_break = False
131
-
132
- if vert_break:
133
- # Compute sub-lines (horizontal split)
134
- lines.extend(self._resolve_sub_lines(boxes, words))
135
- words = []
136
- y_center_sum = 0
137
-
138
- words.append(idx)
139
- y_center_sum += boxes[idx][[1, 3]].mean()
327
+ # Group the words into visual rows
328
+ rows = self._resolve_rows(boxes, idxs, float(y_med))
329
+
330
+ # Split the rows horizontally, using a break distance adapted to the page spacing.
331
+ # The gaps are collected with one vectorized pass per row (the loop is over rows, not word pairs).
332
+ gap_chunks = []
333
+ n_pairs = 0
334
+ for row in rows:
335
+ if len(row) < 2:
336
+ continue
337
+ row_idcs = np.asarray(row)
338
+ row_idcs = row_idcs[np.argsort(boxes[row_idcs, 0], kind="stable")]
339
+ n_pairs += row_idcs.shape[0] - 1
340
+ gap_chunks.append(boxes[row_idcs[1:], 0] - np.maximum.accumulate(boxes[row_idcs, 2])[:-1])
341
+ all_gaps = np.concatenate(gap_chunks) if gap_chunks else np.empty(0, dtype=boxes.dtype)
342
+ pos_gaps = all_gaps[all_gaps > 0]
343
+ # Median word height, converted to width units
344
+ aspect = (shape[0] / shape[1]) if shape is not None else 1.0
345
+ floor = float(y_med) * aspect
346
+ cap = self.paragraph_break * max(1.0, floor / _BODY_WORD_HEIGHT)
347
+ if pos_gaps.shape[0] >= 5 and pos_gaps.shape[0] >= 0.5 * n_pairs:
348
+ break_dist = min(cap, max(3.0 * float(np.median(pos_gaps)), floor))
349
+ elif n_pairs >= 5:
350
+ break_dist = min(cap, floor)
351
+ else:
352
+ break_dist = self.paragraph_break
140
353
 
141
- # Use the remaining words to form the last(s) line(s)
142
- if len(words) > 0:
143
- # Compute sub-lines (horizontal split)
144
- lines.extend(self._resolve_sub_lines(boxes, words))
354
+ lines = []
355
+ for row in rows:
356
+ lines.extend(self._resolve_sub_lines(boxes, row, break_dist, word_regions))
145
357
 
146
358
  return lines
147
359
 
@@ -211,12 +423,145 @@ class DocumentBuilder(NestedObject):
211
423
 
212
424
  return blocks
213
425
 
426
+ @staticmethod
427
+ def _build_layout_elements(regions: dict[str, Any] | None) -> list[LayoutElement]:
428
+ """Convert a raw layout prediction into exportable `LayoutElement` objects.
429
+
430
+ Args:
431
+ regions: a layout prediction `{"boxes": (R, 4) | (R, 4, 2), "class_names": [...], "scores": [...]}`
432
+ as returned by a `LayoutPredictor`, or None.
433
+
434
+ Returns:
435
+ list of `LayoutElement` (empty if no layout was provided).
436
+ """
437
+ if regions is None or len(regions.get("boxes", [])) == 0:
438
+ return []
439
+ boxes = np.asarray(regions["boxes"])
440
+ class_names = regions.get("class_names") or ["" for _ in range(len(boxes))]
441
+ scores = regions.get("scores")
442
+ scores = scores if scores is not None else [1.0 for _ in range(len(boxes))]
443
+
444
+ elements: list[LayoutElement] = []
445
+ for box, cname, score in zip(boxes, class_names, scores):
446
+ if box.ndim == 2: # rotated polygon (4, 2)
447
+ geometry: Any = tuple(tuple(float(c) for c in pt) for pt in box.tolist())
448
+ else: # straight (x1, y1, x2, y2)
449
+ geometry = ((float(box[0]), float(box[1])), (float(box[2]), float(box[3])))
450
+ elements.append(LayoutElement(layout_type=str(cname), confidence=float(score), geometry=geometry))
451
+ return elements
452
+
453
+ def _build_tables(
454
+ self,
455
+ boxes: np.ndarray,
456
+ word_preds: list[tuple[str, float]],
457
+ page_table: dict[str, Any] | list[dict[str, Any]] | None,
458
+ page_shape: tuple[int, int],
459
+ ) -> tuple[list[Table], np.ndarray]:
460
+ """Build the tables of a page from their structure and the words of the page.
461
+
462
+ Args:
463
+ boxes: word boxes of the page, of shape (N, 4) or (N, 4, 2), in relative coordinates
464
+ word_preds: list of (text, confidence) for each of the N words
465
+ page_table: the table structure prediction(s) for the page. Either a single grid
466
+ `{"cells": [{"geometry", "score", "row_start", "row_end", "col_start", "col_end"}], "num_rows",
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
471
+
472
+ Returns:
473
+ a tuple with the list of `Table` objects of the page (one per provided table) and a boolean mask of
474
+ shape (N,) that is True for words assigned to a table (to be removed from `blocks`)
475
+ """
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] = []
481
+ for raw in raw_tables:
482
+ if not raw or len(raw.get("cells", [])) == 0:
483
+ continue
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"]]
488
+ table_cells.append(
489
+ TableCell(
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"],
499
+ )
500
+ )
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(
506
+ Table(
507
+ cells=table_cells,
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"]),
543
+ )
544
+ )
545
+ return formulas
546
+
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())
556
+
214
557
  def _build_blocks(
215
558
  self,
216
559
  boxes: np.ndarray,
217
560
  objectness_scores: np.ndarray,
218
561
  word_preds: list[tuple[str, float]],
219
562
  crop_orientations: list[dict[str, Any]],
563
+ shape: tuple[int, int] | None = None,
564
+ layout: list[LayoutElement] | None = None,
220
565
  ) -> list[Block]:
221
566
  """Gather independent words in structured blocks
222
567
 
@@ -226,6 +571,9 @@ class DocumentBuilder(NestedObject):
226
571
  word_preds: list of all detected words of the page, of shape N
227
572
  crop_orientations: list of dictoinaries containing
228
573
  the general orientation (orientations + confidences) of the crops
574
+ shape: the page dimensions (height, width), used to de-skew rotated pages exactly when
575
+ resolving lines
576
+ layout: optional layout regions of the page
229
577
 
230
578
  Returns:
231
579
  list of block elements
@@ -236,50 +584,86 @@ class DocumentBuilder(NestedObject):
236
584
  if boxes.shape[0] == 0:
237
585
  return []
238
586
 
239
- # Decide whether we try to form lines
240
- _boxes = boxes
241
- if self.resolve_lines:
242
- lines = self._resolve_lines(_boxes if _boxes.ndim == 3 else _boxes[:, :4])
243
- # Decide whether we try to form blocks
244
- if self.resolve_blocks and len(lines) > 1:
245
- _blocks = self._resolve_blocks(_boxes if _boxes.ndim == 3 else _boxes[:, :4], lines)
246
- else:
247
- _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()]
248
591
  else:
249
- # 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]
251
- _blocks = [lines]
252
-
253
- blocks = [
254
- Block([
255
- Line([
256
- Word(
257
- *word_preds[idx],
258
- tuple(tuple(pt) for pt in boxes[idx].tolist()), # type: ignore[arg-type]
259
- float(objectness_scores[idx]),
260
- crop_orientations[idx],
261
- )
262
- if boxes.ndim == 3
263
- else Word(
264
- *word_preds[idx],
265
- ((boxes[idx, 0], boxes[idx, 1]), (boxes[idx, 2], boxes[idx, 3])),
266
- float(objectness_scores[idx]),
267
- crop_orientations[idx],
268
- )
269
- for idx in line
270
- ])
271
- for line in lines
272
- ])
273
- for lines in _blocks
274
- ]
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
+ )
275
603
 
276
- return blocks
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]
613
+
614
+ @staticmethod
615
+ def _words_to_boxes(words: list[Word]) -> np.ndarray:
616
+ """Rebuild a localization array from word geometries (rotated polygons or straight boxes)."""
617
+ geoms = [np.asarray(word.geometry, dtype=np.float32) for word in words]
618
+ if len(geoms) > 0 and geoms[0].shape == (4, 2):
619
+ return np.stack(geoms) # (N, 4, 2) rotated polygons
620
+ return np.asarray(
621
+ [[g[0][0], g[0][1], g[1][0], g[1][1]] for g in geoms], dtype=np.float32
622
+ ) # (N, 4) straight boxes
623
+
624
+ def _apply_reading_order(self, page: Page) -> None:
625
+ """Arrange the blocks of a page in reading order, in place.
626
+
627
+ Args:
628
+ page: the page whose blocks should be reordered in place
629
+ """
630
+ from doctr.io.exporters import _reading_order_signature, _store_reading_order, page_reading_order
631
+
632
+ if not page.blocks:
633
+ return
634
+
635
+ collapse = not self.resolve_lines
636
+ if collapse:
637
+ words = [word for block in page.blocks for line in block.lines for word in line.words]
638
+ if len(words) < 2:
639
+ return
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)
645
+ page.blocks = [Block([Line([words[idx] for idx in group]) for group in groups])]
646
+
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)
649
+ blocks = [item for item in items if isinstance(item, Block)]
650
+ page.blocks = (
651
+ [Block(lines=[Line([word for block in blocks for line in block.lines for word in line.words])])]
652
+ if collapse
653
+ else blocks
654
+ )
655
+ if not collapse:
656
+ # The page now *is* the reading order, so an export would recompute the very same linearization.
657
+ # Re-key the cached result to the new block list so the first export reuses it.
658
+ # Skipped when collapsing: the single flattened line no longer matches the line-level items.
659
+ _store_reading_order(page, _reading_order_signature(page, "auto"), (items, labels, direction))
277
660
 
278
661
  def extra_repr(self) -> str:
279
662
  return (
280
663
  f"resolve_lines={self.resolve_lines}, resolve_blocks={self.resolve_blocks}, "
281
664
  f"paragraph_break={self.paragraph_break}, "
282
- f"export_as_straight_boxes={self.export_as_straight_boxes}"
665
+ f"export_as_straight_boxes={self.export_as_straight_boxes}, "
666
+ f"keep_reading_order={self.keep_reading_order}"
283
667
  )
284
668
 
285
669
  def __call__(
@@ -292,6 +676,9 @@ class DocumentBuilder(NestedObject):
292
676
  crop_orientations: list[dict[str, Any]],
293
677
  orientations: list[dict[str, Any]] | None = None,
294
678
  languages: list[dict[str, Any]] | None = None,
679
+ regions: list[dict[str, Any] | None] | None = None,
680
+ tables: Sequence[dict[str, Any] | list[dict[str, Any]] | None] | None = None,
681
+ formulas: Sequence[list[dict[str, Any]] | None] | None = None,
295
682
  ) -> Document:
296
683
  """Re-arrange detected words into structured blocks
297
684
 
@@ -308,51 +695,97 @@ class DocumentBuilder(NestedObject):
308
695
  where each element is a dictionary containing the orientation (orientation + confidence)
309
696
  languages: optional, list of N elements,
310
697
  where each element is a dictionary containing the language (language + confidence)
698
+ regions: optional, list of N elements, where each element is a layout prediction
699
+ `{"boxes": (R, 4|4x2), "class_names": [...], "scores": [...]}` attached to each page
700
+ tables: optional, list of N elements, where each element is the table structure prediction(s) of a
701
+ page: a single grid `{"cells": [...], "num_rows": int, "num_cols": int}` or a list of such grids
702
+ (one per table region detected by the layout model). Words assigned to any table are removed from
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`)
311
706
 
312
707
  Returns:
313
708
  document object
314
709
  """
315
- if len(boxes) != len(text_preds) != len(crop_orientations) != len(objectness_scores) or len(boxes) != len(
316
- page_shapes
317
- ) != len(crop_orientations) != len(objectness_scores):
710
+ expected_len = len(boxes)
711
+ if any(
712
+ len(arg) != expected_len for arg in (pages, text_preds, crop_orientations, objectness_scores, page_shapes)
713
+ ):
318
714
  raise ValueError("All arguments are expected to be lists of the same size")
319
715
 
320
- _orientations = (
321
- orientations if isinstance(orientations, list) else [None] * len(boxes) # type: ignore[list-item]
322
- )
323
- _languages = languages if isinstance(languages, list) else [None] * len(boxes) # type: ignore[list-item]
716
+ _orientations = orientations if isinstance(orientations, list) else [None] * len(boxes)
717
+ _languages = languages if isinstance(languages, list) else [None] * len(boxes)
718
+ _regions = regions if isinstance(regions, list) else [None] * len(boxes)
719
+ _tables = tables if isinstance(tables, list) else [None] * len(boxes)
720
+ _formulas = formulas if isinstance(formulas, list) else [None] * len(boxes)
324
721
  if self.export_as_straight_boxes and len(boxes) > 0:
325
722
  # If boxes are already straight OK, else fit a bounding rect
326
723
  if boxes[0].ndim == 3:
327
724
  # Iterate over pages and boxes
328
725
  boxes = [np.concatenate((p_boxes.min(1), p_boxes.max(1)), 1) for p_boxes in boxes]
329
726
 
330
- _pages = [
331
- Page(
727
+ _pages = []
728
+ for (
729
+ page,
730
+ _idx,
731
+ shape,
732
+ page_boxes,
733
+ loc_scores,
734
+ word_preds,
735
+ word_crop_orientations,
736
+ orientation,
737
+ language,
738
+ page_regions,
739
+ page_table,
740
+ page_formulas,
741
+ ) in zip( # noqa: E501
742
+ pages,
743
+ range(len(boxes)),
744
+ page_shapes,
745
+ boxes,
746
+ objectness_scores,
747
+ text_preds,
748
+ crop_orientations,
749
+ _orientations,
750
+ _languages,
751
+ _regions,
752
+ _tables,
753
+ _formulas,
754
+ ):
755
+ # Build the page tables and flag the words that belong to a table
756
+ page_tables, consumed = self._build_tables(page_boxes, word_preds, page_table, shape)
757
+ if consumed.any():
758
+ # Remove the words assigned to a table from the regular blocks output
759
+ keep = ~consumed
760
+ page_boxes = page_boxes[keep]
761
+ loc_scores = loc_scores[keep]
762
+ word_preds = [wp for wp, k in zip(word_preds, keep) if k]
763
+ word_crop_orientations = [co for co, k in zip(word_crop_orientations, keep) if k]
764
+
765
+ page_layout = self._build_layout_elements(page_regions)
766
+ page_blocks = self._build_blocks(
767
+ page_boxes,
768
+ loc_scores,
769
+ word_preds,
770
+ word_crop_orientations,
771
+ shape,
772
+ page_layout,
773
+ )
774
+ _page = Page(
332
775
  page,
333
- self._build_blocks(
334
- page_boxes,
335
- loc_scores,
336
- word_preds,
337
- word_crop_orientations,
338
- ),
776
+ page_blocks,
339
777
  _idx,
340
778
  shape,
341
779
  orientation,
342
780
  language,
781
+ page_layout,
782
+ page_tables,
783
+ self._build_formulas(page_formulas, straight=page_boxes.ndim != 3),
343
784
  )
344
- for page, _idx, shape, page_boxes, loc_scores, word_preds, word_crop_orientations, orientation, language in zip( # noqa: E501
345
- pages,
346
- range(len(boxes)),
347
- page_shapes,
348
- boxes,
349
- objectness_scores,
350
- text_preds,
351
- crop_orientations,
352
- _orientations,
353
- _languages,
354
- )
355
- ]
785
+ if self.keep_reading_order:
786
+ self._apply_reading_order(_page)
787
+
788
+ _pages.append(_page)
356
789
 
357
790
  return Document(_pages)
358
791
 
@@ -363,9 +796,13 @@ class KIEDocumentBuilder(DocumentBuilder):
363
796
  Args:
364
797
  resolve_lines: whether words should be automatically grouped into lines
365
798
  resolve_blocks: whether lines should be automatically grouped into blocks
366
- 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)
367
800
  export_as_straight_boxes: if True, force straight boxes in the export (fit a rectangle
368
801
  box to all rotated boxes). Else, keep the boxes format unchanged, no matter what it is.
802
+ keep_reading_order: if True, arrange the content of every page in reading order (cf.
803
+ :mod:`doctr.models.reading_order`). The reading direction is inferred from the recognized text.
804
+ When a layout is available it is always preferred: the text blocks and the page furniture
805
+ (headers, footers, ...) are taken from the layout regions.
369
806
  """
370
807
 
371
808
  def __call__( # type: ignore[override]
@@ -378,6 +815,9 @@ class KIEDocumentBuilder(DocumentBuilder):
378
815
  crop_orientations: list[dict[str, list[dict[str, Any]]]],
379
816
  orientations: list[dict[str, Any]] | None = None,
380
817
  languages: list[dict[str, Any]] | None = None,
818
+ regions: list[dict[str, Any] | None] | None = None,
819
+ tables: Sequence[dict[str, Any] | list[dict[str, Any]] | None] | None = None,
820
+ formulas: Sequence[list[dict[str, Any]] | None] | None = None,
381
821
  ) -> KIEDocument:
382
822
  """Re-arrange detected words into structured predictions
383
823
 
@@ -394,18 +834,26 @@ class KIEDocumentBuilder(DocumentBuilder):
394
834
  where each element is a dictionary containing the orientation (orientation + confidence)
395
835
  languages: optional, list of N elements,
396
836
  where each element is a dictionary containing the language (language + confidence)
837
+ regions: optional, list of N elements, where each element is a layout prediction
838
+ `{"boxes": (R, 4|4x2), "class_names": [...], "scores": [...]}` attached to each page
839
+ tables: optional, list of N elements, where each element is the table structure prediction(s) of a
840
+ page: a single grid `{"cells": [...], "num_rows": int, "num_cols": int}` or a list of such grids
841
+ (one per table region detected by the layout model). Words assigned to any table are removed from
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.
397
845
 
398
846
  Returns:
399
847
  document object
400
848
  """
401
- if len(boxes) != len(text_preds) != len(crop_orientations) != len(objectness_scores) or len(boxes) != len(
402
- page_shapes
403
- ) != len(crop_orientations) != len(objectness_scores):
849
+ expected_len = len(boxes)
850
+ if any(
851
+ len(arg) != expected_len for arg in (pages, text_preds, crop_orientations, objectness_scores, page_shapes)
852
+ ):
404
853
  raise ValueError("All arguments are expected to be lists of the same size")
405
- _orientations = (
406
- orientations if isinstance(orientations, list) else [None] * len(boxes) # type: ignore[list-item]
407
- )
408
- _languages = languages if isinstance(languages, list) else [None] * len(boxes) # type: ignore[list-item]
854
+ _orientations = orientations if isinstance(orientations, list) else [None] * len(boxes)
855
+ _languages = languages if isinstance(languages, list) else [None] * len(boxes)
856
+ _regions = regions if isinstance(regions, list) else [None] * len(boxes)
409
857
  if self.export_as_straight_boxes and len(boxes) > 0:
410
858
  # If boxes are already straight OK, else fit a bounding rect
411
859
  if next(iter(boxes[0].values())).ndim == 3:
@@ -428,6 +876,7 @@ class KIEDocumentBuilder(DocumentBuilder):
428
876
  loc_scores[k],
429
877
  word_preds[k],
430
878
  word_crop_orientations[k],
879
+ shape,
431
880
  )
432
881
  for k in page_boxes.keys()
433
882
  },
@@ -435,8 +884,9 @@ class KIEDocumentBuilder(DocumentBuilder):
435
884
  shape,
436
885
  orientation,
437
886
  language,
887
+ self._build_layout_elements(page_regions),
438
888
  )
439
- for page, _idx, shape, page_boxes, loc_scores, word_preds, word_crop_orientations, orientation, language in zip( # noqa: E501
889
+ for page, _idx, shape, page_boxes, loc_scores, word_preds, word_crop_orientations, orientation, language, page_regions in zip( # noqa: E501
440
890
  pages,
441
891
  range(len(boxes)),
442
892
  page_shapes,
@@ -446,6 +896,7 @@ class KIEDocumentBuilder(DocumentBuilder):
446
896
  crop_orientations,
447
897
  _orientations,
448
898
  _languages,
899
+ _regions,
449
900
  )
450
901
  ]
451
902
 
@@ -457,6 +908,7 @@ class KIEDocumentBuilder(DocumentBuilder):
457
908
  objectness_scores: np.ndarray,
458
909
  word_preds: list[tuple[str, float]],
459
910
  crop_orientations: list[dict[str, Any]],
911
+ shape: tuple[int, int] | None = None,
460
912
  ) -> list[Prediction]:
461
913
  """Gather independent words in structured blocks
462
914
 
@@ -465,6 +917,7 @@ class KIEDocumentBuilder(DocumentBuilder):
465
917
  objectness_scores: objectness scores of all detected words of the page
466
918
  word_preds: list of all detected words of the page, of shape N
467
919
  crop_orientations: list of orientations for each word crop
920
+ shape: the page dimensions (height, width), used to de-skew rotated pages exactly
468
921
 
469
922
  Returns:
470
923
  list of block elements
@@ -477,7 +930,7 @@ class KIEDocumentBuilder(DocumentBuilder):
477
930
 
478
931
  # Decide whether we try to form lines
479
932
  _boxes = boxes
480
- idxs, _ = self._sort_boxes(_boxes if _boxes.ndim == 3 else _boxes[:, :4])
933
+ idxs, _ = self._sort_boxes(_boxes if _boxes.ndim == 3 else _boxes[:, :4], shape)
481
934
  predictions = [
482
935
  Prediction(
483
936
  value=word_preds[idx][0],