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.
Files changed (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -35,12 +35,26 @@ RTL_LANGUAGES = {"ar", "arc", "ckb", "dv", "fa", "he", "iw", "ks", "ku", "nqo",
35
35
  # Unicode bidirectional categories of strong right-to-left characters (Hebrew-like & Arabic-like)
36
36
  _RTL_BIDI_CATEGORIES = {"R", "AL"}
37
37
 
38
- # Normalized layout labels (DocLayNet-style) grouped by their role in the reading order
39
- _HEADER_LABELS = {"page_header", "header", "running_header"}
40
- _FOOTER_LABELS = {"page_footer", "footer", "running_footer"}
41
- _FOOTNOTE_LABELS = {"footnote"}
42
- _CAPTION_LABELS = {"caption"}
43
- _FLOAT_LABELS = {"table", "picture", "figure", "image", "chart", "graphic"}
38
+ # Role in the reading order of the normalized layout labels (DocLayNet-style); any other label is body text
39
+ _LABEL_ROLES = {
40
+ **dict.fromkeys(("page_header", "header", "running_header"), "header"),
41
+ **dict.fromkeys(("page_footer", "footer", "running_footer"), "footer"),
42
+ "footnote": "footnote",
43
+ "caption": "caption",
44
+ **dict.fromkeys(("table", "picture", "figure", "image", "chart", "graphic"), "float"),
45
+ }
46
+ _FLOAT_LABELS = {label for label, role in _LABEL_ROLES.items() if role == "float"}
47
+ _FURNITURE_ROLES = ("header", "footer", "footnote")
48
+ # Normalized labels of the text lying in a float region without float element (e.g. a table without structure)
49
+ _FLOAT_TEXT_LABELS = {f"{label}_text" for label in _FLOAT_LABELS}
50
+
51
+ # Key-value rows (receipts, invoices, forms): a "column" of short values, each level with the text it belongs to and
52
+ # far from it, is not a text column. Below this number of column voters, such a split does not make a multi-column page
53
+ _KEY_VALUE_MAX_VOTERS = 60
54
+ # Maximum median aspect ratio (width / height) of the values: a number or a short label, not a line of running text
55
+ _KEY_VALUE_MAX_ASPECT = 8.0
56
+ # Minimum median gap between a value and the text level with it, in median element heights (a gutter is narrower)
57
+ _KEY_VALUE_MIN_GAP = 4.0
44
58
 
45
59
 
46
60
  def normalize_layout_label(label: str | None) -> str:
@@ -66,18 +80,12 @@ def layout_label_role(label: str | None) -> str:
66
80
  Returns:
67
81
  one of 'header', 'footer', 'footnote', 'caption', 'float' or 'body'
68
82
  """
69
- norm = normalize_layout_label(label)
70
- if norm in _HEADER_LABELS:
71
- return "header"
72
- if norm in _FOOTER_LABELS:
73
- return "footer"
74
- if norm in _FOOTNOTE_LABELS:
75
- return "footnote"
76
- if norm in _CAPTION_LABELS:
77
- return "caption"
78
- if norm in _FLOAT_LABELS:
79
- return "float"
80
- return "body"
83
+ return _LABEL_ROLES.get(normalize_layout_label(label), "body")
84
+
85
+
86
+ def _float_text_label(label: str) -> str:
87
+ """Return the label of a text element lying in a float region (e.g. 'Table' -> 'Table text')"""
88
+ return f"{label} text"
81
89
 
82
90
 
83
91
  def detect_text_direction(texts: Iterable[str], language: str | None = None) -> str:
@@ -89,7 +97,7 @@ def detect_text_direction(texts: Iterable[str], language: str | None = None) ->
89
97
  detection language-independent and robust to mixed content. When no strong character is found, the
90
98
  optional ISO 639 language code is used as a fallback hint.
91
99
 
92
- >>> from doctr.utils.reading_order import detect_text_direction
100
+ >>> from doctr.models.reading_order import detect_text_direction
93
101
  >>> detect_text_direction(["Hello", "world"])
94
102
  'ltr'
95
103
  >>> detect_text_direction(["مرحبا", "بالعالم"])
@@ -102,30 +110,31 @@ def detect_text_direction(texts: Iterable[str], language: str | None = None) ->
102
110
  Returns:
103
111
  either "ltr" or "rtl"
104
112
  """
105
- rtl_count = 0
106
- ltr_count = 0
113
+ rtl_count = ltr_count = 0
107
114
  for text in texts:
108
115
  if not isinstance(text, str):
109
116
  continue
110
117
  for char in text:
111
118
  bidi = unicodedata.bidirectional(char)
112
- if bidi in _RTL_BIDI_CATEGORIES:
113
- rtl_count += 1
114
- elif bidi == "L":
115
- ltr_count += 1
119
+ rtl_count += bidi in _RTL_BIDI_CATEGORIES
120
+ ltr_count += bidi == "L"
116
121
  if rtl_count == 0 and ltr_count == 0:
117
- if isinstance(language, str) and language.split("-")[0].lower() in RTL_LANGUAGES:
118
- return "rtl"
119
- return "ltr"
122
+ rtl_hint = isinstance(language, str) and language.split("-")[0].lower() in RTL_LANGUAGES
123
+ return "rtl" if rtl_hint else "ltr"
120
124
  return "rtl" if rtl_count > ltr_count else "ltr"
121
125
 
122
126
 
127
+ # --- Geometry helpers -------------------------------------------------------------------------------------------------
128
+
129
+
123
130
  def _geometry_to_xyxy(geometry: Any) -> tuple[float, float, float, float]:
131
+ """Return the enclosing box (xmin, ymin, xmax, ymax) of a box or a polygon"""
124
132
  pts = np.asarray(geometry, dtype=np.float64).reshape(-1, 2)
125
133
  return float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())
126
134
 
127
135
 
128
136
  def _to_boxes(geoms: Sequence[Any] | np.ndarray) -> np.ndarray:
137
+ """Return the (N, 4) enclosing boxes of geometries in any docTR format"""
129
138
  if isinstance(geoms, np.ndarray) and geoms.ndim == 2 and geoms.shape[1] >= 4:
130
139
  return geoms[:, :4].astype(np.float64)
131
140
  if isinstance(geoms, np.ndarray) and geoms.ndim == 3:
@@ -135,6 +144,25 @@ def _to_boxes(geoms: Sequence[Any] | np.ndarray) -> np.ndarray:
135
144
  return np.asarray([_geometry_to_xyxy(geom) for geom in geoms], dtype=np.float64)
136
145
 
137
146
 
147
+ def _box_areas(boxes: np.ndarray) -> np.ndarray:
148
+ return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
149
+
150
+
151
+ def _pairwise_overlaps(boxes: np.ndarray, others: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
152
+ """Width and height of the intersection of each (N, 4) box with each (M, 4) box (0 when they do not overlap)"""
153
+ inter_w = np.minimum(boxes[:, None, 2], others[None, :, 2]) - np.maximum(boxes[:, None, 0], others[None, :, 0])
154
+ inter_h = np.minimum(boxes[:, None, 3], others[None, :, 3]) - np.maximum(boxes[:, None, 1], others[None, :, 1])
155
+ return np.clip(inter_w, 0, None), np.clip(inter_h, 0, None)
156
+
157
+
158
+ def _is_inside(boxes: np.ndarray, idx: int, target: int, min_coverage: float = 0.5) -> bool:
159
+ """Check whether box `idx` lies inside box `target`, by at least `min_coverage` of its area"""
160
+ x0, y0, x1, y1 = boxes[idx]
161
+ tx0, ty0, tx1, ty1 = boxes[target]
162
+ inter = max(min(x1, tx1) - max(x0, tx0), 0.0) * max(min(y1, ty1) - max(y0, ty0), 0.0)
163
+ return inter >= min_coverage * max((x1 - x0) * (y1 - y0), 1e-9)
164
+
165
+
138
166
  def _to_canonical_ltr(boxes: np.ndarray, direction: str) -> np.ndarray:
139
167
  """Map boxes to a canonical left-to-right, top-to-bottom space for the given reading direction.
140
168
 
@@ -144,13 +172,12 @@ def _to_canonical_ltr(boxes: np.ndarray, direction: str) -> np.ndarray:
144
172
  if direction == "ltr" or boxes.shape[0] == 0:
145
173
  return boxes
146
174
  x0, y0, x1, y1 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
175
+ pivot = float(x0.min() + x1.max())
147
176
  if direction == "rtl": # mirror horizontally
148
- pivot = float(x0.min() + x1.max())
149
177
  return np.stack([pivot - x1, y0, pivot - x0, y1], axis=1)
150
178
  if direction == "ttb-ltr": # vertical lines, columns ordered left to right: swap axes
151
179
  return np.stack([y0, x0, y1, x1], axis=1)
152
180
  if direction == "ttb-rtl": # vertical lines, columns ordered right to left: swap axes & mirror
153
- pivot = float(x0.min() + x1.max())
154
181
  return np.stack([y0, pivot - x1, y1, pivot - x0], axis=1)
155
182
  raise ValueError(f"invalid reading direction '{direction}', should be one of {SUPPORTED_DIRECTIONS[1:]}")
156
183
 
@@ -177,7 +204,286 @@ def _strict_rank(primary: np.ndarray, secondary: np.ndarray) -> np.ndarray:
177
204
  return ranks
178
205
 
179
206
 
180
- def _topological_order(boxes: np.ndarray, x_overlap_threshold: float, y_overlap_threshold: float) -> list[int]:
207
+ def deskew_reading_geometries(
208
+ geoms: Sequence[Any] | np.ndarray,
209
+ region_geoms: Sequence[Any] | np.ndarray | None = None,
210
+ page_shape: tuple[int, int] | None = None,
211
+ angle_geoms: Sequence[Any] | np.ndarray | None = None,
212
+ min_angle: float = 1.0,
213
+ ) -> tuple[list[Any], list[Any]]:
214
+ """De-skew rotated geometries so the reading order can be computed in an upright frame.
215
+
216
+ Args:
217
+ geoms: geometries of the elements to order, in any docTR format (cf. `sort_reading_order`)
218
+ region_geoms: optional geometries of the layout regions, de-skewed together with the elements
219
+ page_shape: the page dimensions (height, width). Required for an exact angle on non-square pages with
220
+ relative coordinates, since relative coordinates distort angles by the aspect ratio.
221
+ angle_geoms: optional reading-oriented 4-point polygons used to estimate the page angle
222
+ min_angle: minimum estimated angle (in degrees) to trigger the de-skew. Ordering is affected as soon
223
+ as the drift along a line approaches the line height (about 1 degree for a page-wide line), and a
224
+ small rigid rotation cannot change the order of an upright page, hence the low default. Beyond 45
225
+ degrees the corner identification is ambiguous (an upstream orientation correction is needed) and
226
+ nothing is done.
227
+
228
+ Returns:
229
+ the (possibly de-skewed) element and region geometries
230
+ """
231
+ region_geoms = list(region_geoms) if region_geoms is not None else []
232
+ pts = [np.asarray(geom, dtype=np.float64).reshape(-1, 2) for geom in geoms]
233
+ if len(pts) == 0 or any(p.shape[0] != 4 for p in pts):
234
+ return list(geoms), region_geoms # straight geometries: nothing to de-skew
235
+ height, width = page_shape if page_shape is not None else (1, 1)
236
+ scale = np.array([width, height], dtype=np.float64)
237
+ angle_pts = [
238
+ np.asarray(geom, dtype=np.float64).reshape(-1, 2) for geom in (angle_geoms if angle_geoms is not None else [])
239
+ ]
240
+ if len(angle_pts) > 0 and all(p.shape[0] == 4 for p in angle_pts):
241
+ # Detection polygons are already reading-oriented (cf. `estimate_page_angle`): keep their vertex order
242
+ angle = estimate_page_angle(np.stack(angle_pts) * scale)
243
+ else:
244
+ # Normalize the vertex order (TL, TR, BR, BL) so the estimation does not depend on the vertex
245
+ angle = estimate_page_angle(np.stack([order_points(p * scale) for p in pts]))
246
+ if not np.isfinite(angle) or abs(angle) < min_angle or abs(angle) >= 45:
247
+ return list(geoms), region_geoms
248
+ # Rigid rotation zeroing the estimated angle, in pixels; the center is irrelevant for ordering purposes
249
+ theta = np.deg2rad(angle)
250
+ rot = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
251
+ center = (np.concatenate(pts, axis=0) * scale).mean(axis=0)
252
+
253
+ def _rotate(points: np.ndarray) -> np.ndarray:
254
+ if points.shape[0] != 4: # a straight region: rotate its 4 corners, not only its diagonal
255
+ (x0, y0), (x1, y1) = points.min(axis=0), points.max(axis=0)
256
+ points = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
257
+ return ((points * scale - center) @ rot.T + center) / scale
258
+
259
+ regions = [_rotate(np.asarray(geom, dtype=np.float64).reshape(-1, 2)) for geom in region_geoms]
260
+ return [_rotate(p) for p in pts], regions
261
+
262
+
263
+ # --- Layout regions ---------------------------------------------------------------------------------------------------
264
+
265
+
266
+ def _covering_regions(
267
+ boxes: np.ndarray,
268
+ regions: np.ndarray,
269
+ min_coverage: float,
270
+ region_labels: Sequence[str | None] | None = None,
271
+ ) -> list[int]:
272
+ """Return the index of the region covering each (N, 4) box by at least `min_coverage`, -1 if none
273
+
274
+ Regions covering a box (nearly) as much as the best one tie: the smallest one wins, unless it is a float tied with
275
+ page furniture.
276
+ """
277
+ inter_w, inter_h = _pairwise_overlaps(boxes, regions)
278
+ coverage = inter_w * inter_h / np.clip(_box_areas(boxes), 1e-9, None)[:, None]
279
+ region_areas = _box_areas(regions)
280
+ qualifies = coverage >= np.maximum(coverage.max(axis=1, keepdims=True) - 0.1, min_coverage)
281
+ # Regions nested in the best region of a box also tie when they cover most of it
282
+ reg_w, reg_h = _pairwise_overlaps(regions, regions)
283
+ nested = reg_w * reg_h >= 0.9 * np.clip(region_areas, 1e-9, None)[:, None] # nested[i, j]: region i lies inside j
284
+ qualifies |= (coverage >= max(min_coverage, 0.75)) & nested[:, coverage.argmax(axis=1)].T
285
+ ranked = np.where(qualifies, region_areas[None, :], np.inf)
286
+ best = ranked.argmin(axis=1)
287
+ result = [int(reg) if np.isfinite(ranked[idx, reg]) else -1 for idx, reg in enumerate(best)]
288
+ if region_labels is None or len(region_labels) != regions.shape[0]:
289
+ return result
290
+
291
+ roles = [layout_label_role(label) for label in region_labels]
292
+ is_float = np.array([role == "float" for role in roles], dtype=bool)
293
+ is_furniture = np.array([role in _FURNITURE_ROLES for role in roles], dtype=bool)
294
+ if not (is_float.any() and is_furniture.any()):
295
+ return result
296
+ # The text of a float tied with page furniture (e.g. a logo in the page header) is read with the furniture
297
+ furniture_ranked = np.where(qualifies & is_furniture[None, :], region_areas[None, :], np.inf)
298
+ for idx, reg in enumerate(result):
299
+ if reg >= 0 and is_float[reg] and np.isfinite(furniture_ranked[idx].min()):
300
+ result[idx] = int(furniture_ranked[idx].argmin())
301
+ return result
302
+
303
+
304
+ def _region_groups(regions: np.ndarray, labels: Sequence[str | None], min_overlap: float = 0.1) -> list[int]:
305
+ """Return the group of each (R, 4) layout region (the index of one of its members), grouping the regions of the
306
+ same label which overlap by more than `min_overlap` of the smaller one (e.g. two regions for a paragraph around a
307
+ figure)
308
+ """
309
+ norm = [normalize_layout_label(label) for label in labels]
310
+ areas = _box_areas(regions)
311
+ parent = list(range(regions.shape[0]))
312
+
313
+ def _find(idx: int) -> int:
314
+ while parent[idx] != idx:
315
+ parent[idx] = parent[parent[idx]]
316
+ idx = parent[idx]
317
+ return idx
318
+
319
+ # Pairwise with scalar min / max, as the comparisons of degenerate (NaN) boxes depend on the argument order
320
+ for i, j in ((i, j) for i in range(len(parent)) for j in range(i + 1, len(parent)) if norm[i] == norm[j]):
321
+ inter = max(min(regions[i, 2], regions[j, 2]) - max(regions[i, 0], regions[j, 0]), 0.0) * max(
322
+ min(regions[i, 3], regions[j, 3]) - max(regions[i, 1], regions[j, 1]), 0.0
323
+ )
324
+ if inter > min_overlap * min(areas[i], areas[j]):
325
+ parent[_find(i)] = _find(j)
326
+ return [_find(idx) for idx in range(len(parent))]
327
+
328
+
329
+ def assign_layout_labels(
330
+ geoms: Sequence[Any] | np.ndarray,
331
+ layout_geoms: Sequence[Any] | np.ndarray,
332
+ layout_labels: Sequence[str],
333
+ min_coverage: float = 0.5,
334
+ page_shape: tuple[int, int] | None = None,
335
+ angle_geoms: Sequence[Any] | np.ndarray | None = None,
336
+ ) -> list[str | None]:
337
+ """Assign a layout label to each element based on its overlap with the detected layout regions.
338
+
339
+ Each element receives the label of the region covering the largest share of its area, provided this share reaches
340
+ `min_coverage`; otherwise its label is None (treated as regular body content). Among nested regions, the smallest
341
+ one wins (e.g. 'Caption' over 'Picture'), except for a float nested in page furniture (e.g. a logo in the page
342
+ header): its text takes the furniture label.
343
+
344
+ Args:
345
+ geoms: geometries of the elements to label, in any docTR format
346
+ layout_geoms: geometries of the layout regions, in any docTR format
347
+ layout_labels: labels of the layout regions (e.g. `[region.type for region in page.layout]`)
348
+ min_coverage: minimum share of an element's area a region must cover to assign its label
349
+ page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly (cf.
350
+ `deskew_reading_geometries`)
351
+ angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
352
+ estimate the page angle on rotated pages (cf. `deskew_reading_geometries`)
353
+
354
+ Returns:
355
+ the label of each element (None when no region covers it enough)
356
+ """
357
+ # De-skew elements and regions together so the coverage is measured on tight boxes in the same frame
358
+ geoms, layout_geoms = deskew_reading_geometries(geoms, layout_geoms, page_shape=page_shape, angle_geoms=angle_geoms)
359
+ boxes, regions = _to_boxes(geoms), _to_boxes(layout_geoms)
360
+ if len(layout_labels) != regions.shape[0]:
361
+ raise ValueError(f"Incompatible number of labels ({len(layout_labels)}) and regions ({regions.shape[0]})")
362
+ if boxes.shape[0] == 0 or regions.shape[0] == 0:
363
+ return [None] * boxes.shape[0]
364
+ covering = _covering_regions(boxes, regions, min_coverage, layout_labels)
365
+ return [str(layout_labels[reg]) if reg >= 0 else None for reg in covering]
366
+
367
+
368
+ # --- Topological sort -------------------------------------------------------------------------------------------------
369
+
370
+
371
+ def _key_value_rows(
372
+ boxes: np.ndarray, voters: np.ndarray, split: float, y_overlap: np.ndarray, y_overlap_threshold: float, span: float
373
+ ) -> bool:
374
+ """Check whether the voters on the right of a column split are the values of key-value rows rather than a column
375
+
376
+ On a receipt or an invoice, the amounts form a narrow right-aligned "column": each amount is level with the item
377
+ it belongs to, far from it, and the rows must be read one after the other. In a text column, the lines are long
378
+ and the gutter separating them from the lines of the previous column is narrow.
379
+
380
+ Args:
381
+ boxes: the (N, 4) boxes in canonical LTR space
382
+ voters: the mask of the boxes used to detect the columns
383
+ split: the abscissa of the column split
384
+ y_overlap: the (N, N) vertical overlap ratios of the boxes
385
+ y_overlap_threshold: the vertical overlap above which two boxes lie on the same row
386
+ span: the horizontal extent of the voters
387
+
388
+ Returns:
389
+ whether the split separates the keys from the values of key-value rows
390
+ """
391
+ if np.count_nonzero(voters) > _KEY_VALUE_MAX_VOTERS:
392
+ return False
393
+ x0, y0, x1, y1 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
394
+ on_left = voters & ((x0 + x1) / 2 <= split)
395
+ left, right = np.flatnonzero(on_left), np.flatnonzero(voters & ~on_left)
396
+ height = float(np.median(y1[voters] - y0[voters]))
397
+ if right.size == 0 or left.size == 0 or not height > 0:
398
+ return False
399
+ aspect = float(np.median((x1[right] - x0[right]) / np.maximum(y1[right] - y0[right], 1e-9)))
400
+ if aspect >= _KEY_VALUE_MAX_ASPECT:
401
+ return False
402
+ # Gap between each value and the text level with it on its left
403
+ level = y_overlap[np.ix_(right, left)] > y_overlap_threshold
404
+ level &= x1[left][None, :] <= x0[right][:, None] + 0.02 * span
405
+ paired = level.any(axis=1)
406
+ if np.count_nonzero(paired) < 0.5 * right.size:
407
+ return False
408
+ ends = np.where(level, x1[left][None, :], -np.inf).max(axis=1)
409
+ return float(np.median((x0[right][paired] - ends[paired]) / height)) >= _KEY_VALUE_MIN_GAP
410
+
411
+
412
+ def _column_gutter(
413
+ boxes: np.ndarray, voters: np.ndarray, y_overlap: np.ndarray, y_overlap_threshold: float
414
+ ) -> float | None:
415
+ """Detect a multi-column page: a vertical line separating the voters into two groups crossed by few of them
416
+
417
+ Args:
418
+ boxes: the (N, 4) boxes in canonical LTR space
419
+ voters: the mask of the boxes used to detect the columns (all of them with fewer than 3 voters)
420
+ y_overlap: the (N, N) vertical overlap ratios of the boxes
421
+ y_overlap_threshold: the vertical overlap above which two boxes lie on the same row
422
+
423
+ Returns:
424
+ the position of the gutter for a multi-column page, None for a single-column page
425
+ """
426
+ if np.count_nonzero(voters) < 3:
427
+ voters = np.ones(boxes.shape[0], dtype=bool)
428
+ x0, x1 = boxes[:, 0], boxes[:, 2]
429
+ vx0, vx1, num_voters = x0[voters], x1[voters], int(np.count_nonzero(voters))
430
+ if num_voters < 3:
431
+ return None
432
+ vy = (boxes[voters, 1] + boxes[voters, 3]) / 2
433
+ # Measured on the voters only, so that a wide figure does not shift the search window
434
+ left_edge = float(vx0.min())
435
+ span = float(vx1.max()) - left_edge or 1.0
436
+ tolerance = max(1, int(0.05 * num_voters))
437
+ centers = (vx0 + vx1) / 2
438
+ lo, hi = left_edge + 0.25 * span, left_edge + 0.75 * span
439
+ for split in np.unique(vx1[(vx1 >= lo) & (vx1 <= hi)]):
440
+ across = np.minimum(vx1 - split, split - vx0) > 0.02 * span
441
+ on_left, on_right = ~across & (centers <= split), ~across & (centers > split)
442
+ if not on_left.any() or not on_right.any():
443
+ continue
444
+ # Elements above or below the columns (e.g. a title and its authors) do not count as crossing
445
+ columns_y = vy[on_left | on_right]
446
+ crossing = int(np.count_nonzero(across & (vy > columns_y.min()) & (vy < columns_y.max())))
447
+ left = int(np.count_nonzero(centers <= split))
448
+ if crossing <= tolerance and left >= 0.25 * num_voters and num_voters - left >= 0.25 * num_voters:
449
+ beside = voters.copy()
450
+ beside[np.flatnonzero(voters)[across]] = False
451
+ if _key_value_rows(boxes, beside, float(split), y_overlap, y_overlap_threshold, span):
452
+ return None # rows of keys and values (e.g. a receipt): read row after row
453
+ return float(split)
454
+ return None
455
+
456
+
457
+ def _detached_above(y0: np.ndarray, y1: np.ndarray, column: np.ndarray, top: float) -> np.ndarray:
458
+ """The elements of a column separated by a wide gap from both the rest of the column and the other columns below
459
+ them (e.g. a right-aligned title or address block above the columns of a page)
460
+
461
+ Args:
462
+ y0: the top of each box
463
+ y1: the bottom of each box
464
+ column: the indices of the elements of the column
465
+ top: the position the other columns start at
466
+
467
+ Returns:
468
+ the indices of the detached elements
469
+ """
470
+ column = column[np.argsort(y0[column], kind="stable")]
471
+ level = np.flatnonzero(y1[column] > top)
472
+ if level.size == 0 or level[0] == 0:
473
+ return column[:0]
474
+ first = int(level[0])
475
+ bottoms = np.maximum.accumulate(y1[column])
476
+ gaps = y0[column[1:]] - bottoms[:-1]
477
+ # Wide: more than 3 times the usual gap of the column, and than the height of an element
478
+ limit = max(3 * float(np.median(gaps[first:])) if gaps[first:].size else 0.0, float(np.median(y1 - y0)))
479
+ while first > 0 and gaps[first - 1] <= limit:
480
+ first -= 1
481
+ return column[:first] if first > 0 and top - bottoms[first - 1] > limit else column[:0]
482
+
483
+
484
+ def _topological_order(
485
+ boxes: np.ndarray, x_overlap_threshold: float, y_overlap_threshold: float, voters: np.ndarray | None = None
486
+ ) -> list[int]:
181
487
  """Order boxes (already in canonical LTR space) with a column-following topological sort.
182
488
 
183
489
  Two families of "reads-before" relations are used (cf. Breuel 2003):
@@ -189,7 +495,9 @@ def _topological_order(boxes: np.ndarray, x_overlap_threshold: float, y_overlap_
189
495
  The relations are resolved with Kahn's algorithm; among the available elements, the traversal favors the
190
496
  continuation of the current column (the closest element below the last emitted one with a horizontal
191
497
  overlap), which keeps multi-column bodies intact even for non-Manhattan layouts where recursive XY-cuts
192
- fail to find a valid split.
498
+ fail to find a valid split. `voters` optionally restricts the boxes used to detect a multi-column page. A split
499
+ separating the values of key-value rows from their keys (e.g. the amounts of a receipt, cf. `_key_value_rows`)
500
+ does not make the page multi-column.
193
501
  """
194
502
  num_boxes = boxes.shape[0]
195
503
  if num_boxes <= 1:
@@ -198,185 +506,336 @@ def _topological_order(boxes: np.ndarray, x_overlap_threshold: float, y_overlap_
198
506
  x0, y0, x1, y1 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
199
507
  x_overlap = _overlap_ratios(x0, x1)
200
508
  y_overlap = _overlap_ratios(y0, y1)
201
-
202
509
  # Strict total orders on both axes, so that the induced relations cannot create 2-cycles
203
- x_rank = _strict_rank(x0, x1)
204
- y_rank = _strict_rank(y0, y1)
510
+ x_rank, y_rank = _strict_rank(x0, x1), _strict_rank(y0, y1)
205
511
 
206
- # i -> j edges: i must be read before j. The matrices are combined in place: every intermediate is an
207
- # N x N array, so materializing them all at once dominates the memory of this function on dense pages.
512
+ # edges[i, j]: i must be read before j. The N x N matrices are combined in place, since materializing them all at
513
+ # once dominates the memory of this function on dense pages.
208
514
  x_linked = x_overlap > x_overlap_threshold
209
- edges = y_rank[:, None] < y_rank[None, :] # i is above j
210
- edges &= x_linked
515
+ edges = y_rank[:, None] < y_rank[None, :] # i is above j...
516
+ edges &= x_linked # ... in the same column
211
517
  same_row = y_overlap > y_overlap_threshold
212
518
  same_row &= ~x_linked
213
- same_row &= x_rank[:, None] < x_rank[None, :] # i is on the left of j
519
+ same_row &= x_rank[:, None] < x_rank[None, :] # i is on the left of j on the same row
520
+ # An element shifted between two rows (e.g. an amount on a crumpled receipt) only waits for the row it overlaps most
521
+ best_left = np.max(y_overlap, axis=0, where=same_row, initial=0.0)
522
+ weak_i, weak_j = np.nonzero(same_row & (y_overlap < best_left[None, :] - 0.1))
523
+ if weak_i.size > 0:
524
+ cols = np.unique(weak_j)
525
+ best = np.argmax(np.where(same_row[:, cols], y_overlap[:, cols], -1.0), axis=0)
526
+ other_row = y_overlap[weak_i, best[np.searchsorted(cols, weak_j)]] <= y_overlap_threshold
527
+ same_row[weak_i[other_row], weak_j[other_row]] = False
214
528
  edges |= same_row
215
529
  del same_row
216
530
  np.fill_diagonal(edges, False)
217
531
 
218
- in_degree = edges.sum(axis=0)
219
- emitted = np.zeros(num_boxes, dtype=bool)
220
- order: list[int] = []
221
- last = -1
222
-
223
- # Column components: elements connected through horizontal overlap, ignoring page-spanning lines (e.g.
224
- # titles) which would otherwise merge separate columns. This keeps the traversal inside a column even when
225
- # the direct top-to-bottom continuation is momentarily broken by a fragmented or misaligned OCR line.
226
- page_width = float(x1.max() - x0.min()) or 1.0
227
- spanning = (x1 - x0) > 0.5 * page_width
228
-
229
- # Reuse the horizontal-overlap matrix; keep the upper triangle only, so each pair is visited once
230
- col_edges = np.triu(x_linked, 1)
231
- col_edges &= ~spanning[:, None]
232
- col_edges &= ~spanning[None, :]
532
+ # A multi-column page favors the continuation of the current column (cf. `_continuation`)
533
+ span = float(x1.max() - x0.min()) or 1.0
534
+ spanning = (x1 - x0) > 0.5 * span
535
+ gutter = _column_gutter(
536
+ boxes, np.ones(num_boxes, dtype=bool) if voters is None else voters, y_overlap, y_overlap_threshold
537
+ )
538
+ multi_column = gutter is not None
539
+ crossing = np.zeros(num_boxes, dtype=bool)
540
+ # 1 for the columns after the gutter, read after the ones before it even when they start higher (only when both
541
+ # sides hold several elements)
542
+ after_gutter = np.zeros(num_boxes, dtype=int)
543
+ if gutter is not None:
544
+ crossing = np.minimum(x1 - gutter, gutter - x0) > 0.02 * span
545
+ after = x0 >= gutter - 0.02 * span
546
+ before = ~after & ~crossing
547
+ if np.count_nonzero(after) >= 2 and np.count_nonzero(before) >= 2:
548
+ after_gutter = after.astype(int)
549
+ after_gutter[_detached_above(y0, y1, np.flatnonzero(after), float(y0[before].min()))] = 0
550
+ # Column components: elements connected through horizontal overlap, except those which must not merge the columns
551
+ # (page-wide or crossing the gutter). This keeps the traversal inside a column even when the direct top-to-bottom
552
+ # continuation is momentarily broken by a fragmented or misaligned OCR line.
553
+ bridging = spanning | crossing
554
+ col_edges = np.triu(x_linked, 1) # each pair once
555
+ col_edges &= ~bridging[:, None]
556
+ col_edges &= ~bridging[None, :]
233
557
  component = connected_components(csr_matrix(col_edges), directed=False, return_labels=True)[1]
234
558
 
235
- # Detect whether the page is multi-column: if a vertical line can be drawn that separates the boxes into two
236
- # groups with a small number of crossing boxes, the page is considered multi-column. This is used to
237
- # favor the continuation of the current column when traversing the graph, which keeps multi-column bodies intact
238
- # even for non-Manhattan layouts where recursive XY-cuts fail to find a valid split.
239
- multi_column = False
240
- if num_boxes >= 3:
241
- span = page_width
242
- tolerance = max(1, int(0.05 * num_boxes))
243
- centers = (x0 + x1) / 2
244
- lo, hi = x0.min() + 0.25 * span, x0.min() + 0.75 * span
245
- for split in np.unique(x1[(x1 >= lo) & (x1 <= hi)]):
246
- crossing = int(np.count_nonzero(np.minimum(x1 - split, split - x0) > 0.02 * span))
247
- left = int(np.count_nonzero(centers <= split))
248
- if crossing <= tolerance and left >= 0.25 * num_boxes and num_boxes - left >= 0.25 * num_boxes:
249
- multi_column = True
250
- break
559
+ def _continuation(last: int, ready: np.ndarray) -> np.ndarray:
560
+ """The available elements continuing the reading after `last`: below it in its column (multi-column page),
561
+ else on its row, else in its column component"""
562
+ if multi_column:
563
+ below = ready[(x_overlap[last, ready] > x_overlap_threshold) & (y0[ready] >= y0[last])]
564
+ if below.size > 0:
565
+ return below
566
+ level = ready[y_overlap[last, ready] > y_overlap_threshold]
567
+ if level.size > 0 or spanning[last]:
568
+ return level if level.size > 0 else ready
569
+ same_column = ready[component[ready] == component[last]]
570
+ return same_column if same_column.size > 0 else ready
251
571
 
572
+ in_degree = edges.sum(axis=0)
573
+ emitted = np.zeros(num_boxes, dtype=bool)
574
+ order: list[int] = []
252
575
  while len(order) < num_boxes:
253
576
  ready = np.flatnonzero((in_degree == 0) & ~emitted)
254
577
  if ready.size == 0: # cycle safety net (can only happen with degenerate overlapping geometries)
255
- ready = np.flatnonzero(~emitted)
256
- candidates = ready
578
+ candidates = np.flatnonzero(~emitted)
257
579
  else:
258
- # Favor the continuation of the current column: the closest available element located below the
259
- # last emitted one with a horizontal overlap
260
- candidates = (
261
- ready[(x_overlap[last, ready] > x_overlap_threshold) & (y0[ready] >= y0[last])]
262
- if last >= 0 and multi_column
263
- else np.empty(0, dtype=int)
264
- )
265
- if candidates.size == 0 and last >= 0:
266
- candidates = ready[y_overlap[last, ready] > y_overlap_threshold]
267
- if candidates.size == 0 and last >= 0 and not spanning[last]:
268
- # Continuation broken (gap, fragment): stay in the same column before switching to another
269
- same_column = ready[component[ready] == component[last]]
270
- candidates = same_column if same_column.size else ready
271
- elif candidates.size == 0:
272
- candidates = ready
580
+ # The columns before the gutter first
581
+ ready = ready[after_gutter[ready] == after_gutter[ready].min()]
582
+ candidates = _continuation(order[-1], ready) if order else ready
273
583
  # Topmost first, then leftmost (in canonical space)
274
- next_idx = int(candidates[np.lexsort((x0[candidates], y0[candidates]))[0]])
584
+ next_idx = int(candidates[np.lexsort((x0[candidates], y0[candidates], after_gutter[candidates]))[0]])
275
585
  order.append(next_idx)
276
586
  emitted[next_idx] = True
277
587
  in_degree = in_degree - edges[next_idx]
278
- last = next_idx
279
-
280
588
  return order
281
589
 
282
590
 
591
+ # --- Floats & captions ------------------------------------------------------------------------------------------------
592
+
593
+
594
+ def _outer_floats(idcs: list[int], boxes: np.ndarray, labels: list[str]) -> list[int]:
595
+ """Return the floats among `idcs` that are not nested in a larger float"""
596
+ areas = _box_areas(boxes)
597
+ floats = [idx for idx in idcs if labels[idx] in _FLOAT_LABELS]
598
+ return [
599
+ idx
600
+ for idx in floats
601
+ if not any(areas[other] > areas[idx] and _is_inside(boxes, idx, other) for other in floats)
602
+ ]
603
+
604
+
605
+ def _float_members(idcs: list[int], boxes: np.ndarray, labels: list[str]) -> dict[int, list[int]]:
606
+ """Map each outer float to the elements inside it (e.g. the text of a figure)
607
+
608
+ An element belongs to the smallest outer float covering at least half of it.
609
+ """
610
+ areas = _box_areas(boxes)
611
+ outer = _outer_floats(idcs, boxes, labels)
612
+ members: dict[int, list[int]] = {}
613
+ for idx in idcs:
614
+ if idx in outer:
615
+ continue
616
+ containers = [flt for flt in outer if areas[flt] > areas[idx] and _is_inside(boxes, idx, flt)]
617
+ if containers:
618
+ members.setdefault(min(containers, key=lambda flt: areas[flt]), []).append(idx)
619
+ return members
620
+
621
+
622
+ def _stands_beside(boxes: np.ndarray, run: list[int], region: list[int]) -> bool:
623
+ """Check whether an element of a region stands beside a run of floats (level with it, not overlapping it)
624
+
625
+ Args:
626
+ boxes: the (N, 4) boxes of all elements
627
+ run: the floats of the run, with the elements read inside them
628
+ region: the other elements of the interrupted region
629
+
630
+ Returns:
631
+ True if an element of the region stands beside the run
632
+ """
633
+ rx0, ry0 = boxes[run, 0].min(), boxes[run, 1].min()
634
+ rx1, ry1 = boxes[run, 2].max(), boxes[run, 3].max()
635
+ for x0, y0, x1, y1 in boxes[region]:
636
+ # Level with the run: at least half of the element height
637
+ if min(y1, ry1) - max(y0, ry0) < 0.5 * max(y1 - y0, 1e-9):
638
+ continue
639
+ # Beside the run: horizontal overlap of at most 10% of the narrower width
640
+ if min(x1, rx1) - max(x0, rx0) <= 0.1 * max(min(x1 - x0, rx1 - rx0), 1e-9):
641
+ return True
642
+ return False
643
+
644
+
645
+ def _defer_floats(
646
+ order: list[int],
647
+ labels: list[str],
648
+ members: dict[int, list[int]],
649
+ groups: Sequence[int],
650
+ boxes: np.ndarray | None = None,
651
+ ) -> list[int]:
652
+ """Move the floats interrupting a layout region right after the end of that region
653
+
654
+ The traversal can read a figure standing beside a paragraph before the last lines of that paragraph.
655
+
656
+ Args:
657
+ order: the body elements in reading order, the elements inside a float right after it
658
+ labels: the normalized layout label of each element
659
+ members: the elements inside each float
660
+ groups: the layout region index of each element (-1 for none)
661
+ boxes: the (N, 4) boxes of all elements, to only move the floats standing beside the region
662
+
663
+ Returns:
664
+ the reordered body elements
665
+ """
666
+ inner = {idx for idcs in members.values() for idx in idcs}
667
+
668
+ def _is_float(idx: int) -> bool:
669
+ return labels[idx] in _FLOAT_LABELS or labels[idx] in _FLOAT_TEXT_LABELS or idx in inner
670
+
671
+ out = list(order)
672
+ pos = 0
673
+ while pos < len(out):
674
+ if not _is_float(out[pos]):
675
+ pos += 1
676
+ continue
677
+ # out[pos:end] is a run of floats, read after out[pos - 1]: does it interrupt the region of that element?
678
+ end = pos
679
+ while end < len(out) and _is_float(out[end]):
680
+ end += 1
681
+ group = int(groups[out[pos - 1]]) if pos > 0 else -1
682
+ interrupts = group >= 0 and end < len(out) and int(groups[out[end]]) == group
683
+ if interrupts and boxes is not None:
684
+ region = [idx for idx in out if int(groups[idx]) == group and not _is_float(idx)]
685
+ interrupts = _stands_beside(boxes, out[pos:end], region)
686
+ if not interrupts:
687
+ pos = end
688
+ continue
689
+ # Move the run after the rest of the region
690
+ stop = end
691
+ while stop < len(out) and not _is_float(out[stop]) and int(groups[out[stop]]) == group:
692
+ stop += 1
693
+ out[pos:stop] = out[end:stop] + out[pos:end]
694
+ pos = stop - (end - pos) # check the moved run again: it can interrupt the same region further down
695
+ return out
696
+
697
+
698
+ def _caption_distance(caption: Sequence[float], target: Sequence[float]) -> float:
699
+ """Distance from a caption box to a float box, penalizing horizontal shifts"""
700
+ x_gap = max(target[0] - caption[2], caption[0] - target[2], 0.0)
701
+ y_gap = max(target[1] - caption[3], caption[1] - target[3], 0.0)
702
+ return y_gap + 2 * x_gap
703
+
704
+
705
+ def _caption_units(caption_idcs: list[int], region_groups: Sequence[int] | None) -> list[list[int]]:
706
+ """Group the captions sharing a group id into units, in reading order (a caption without group is a unit)"""
707
+ units: list[list[int]] = []
708
+ by_group: dict[int, list[int]] = {}
709
+ for cap in caption_idcs:
710
+ group = -1 if region_groups is None else int(region_groups[cap])
711
+ if group < 0:
712
+ units.append([cap])
713
+ elif group in by_group:
714
+ by_group[group].append(cap)
715
+ else:
716
+ by_group[group] = [cap]
717
+ units.append(by_group[group])
718
+ return units
719
+
720
+
283
721
  def _attach_captions(
284
722
  order: list[int],
285
723
  caption_idcs: list[int],
286
724
  boxes: np.ndarray,
287
725
  labels: list[str],
288
726
  max_distance: float,
727
+ region_groups: Sequence[int] | None = None,
289
728
  ) -> list[int]:
290
- """Insert captions right before (resp. after) the closest float they sit above (resp. below).
729
+ """Insert the captions right before (resp. after) the closest float they sit above (resp. below)
291
730
 
292
- Captions without a float within reach keep their natural spatial position in the body.
731
+ The captions of a group (e.g. the lines of a caption region) move as a unit. A caption without a float within
732
+ reach is read in its column, right after the closest element above it.
293
733
  """
294
- float_idcs = [idx for idx in order if labels[idx] in _FLOAT_LABELS]
295
- for cap in caption_idcs:
296
- cx0, cy0, cx1, cy1 = boxes[cap]
297
- best_target, best_dist = -1, float("inf")
298
- for target in float_idcs:
299
- tx0, ty0, tx1, ty1 = boxes[target]
300
- x_gap = max(tx0 - cx1, cx0 - tx1, 0.0)
301
- y_gap = max(ty0 - cy1, cy0 - ty1, 0.0)
302
- # Captions are expected right above/below (or overlapping) their float: penalize horizontal shifts
303
- dist = y_gap + 2 * x_gap
734
+ captions = set(caption_idcs)
735
+ float_idcs = _outer_floats(order, boxes, labels)
736
+ below: dict[int, set[int]] = {} # captions already read after each element
737
+
738
+ def _read_after(target: int, unit: list[int]) -> int:
739
+ """Return the position after `target`, the elements inside it and the captions already read after it"""
740
+ attached = below.setdefault(target, set())
741
+ pos = order.index(target) + 1
742
+ while pos < len(order) and (
743
+ order[pos] in attached or (order[pos] not in captions and _is_inside(boxes, order[pos], target))
744
+ ):
745
+ pos += 1
746
+ attached.update(unit)
747
+ return pos
748
+
749
+ for unit in _caption_units(caption_idcs, region_groups):
750
+ cx0, cy0 = boxes[unit, 0].min(), boxes[unit, 1].min()
751
+ cx1, cy1 = boxes[unit, 2].max(), boxes[unit, 3].max()
752
+ target, best_dist = -1, float("inf")
753
+ for flt in float_idcs:
754
+ dist = _caption_distance((cx0, cy0, cx1, cy1), boxes[flt])
304
755
  if dist < best_dist:
305
- best_target, best_dist = target, dist
306
- if best_target >= 0 and best_dist <= max_distance:
307
- pos = order.index(best_target)
308
- # A caption located above (the center of) its float is read before it, otherwise after
309
- above = (cy0 + cy1) / 2 <= (boxes[best_target, 1] + boxes[best_target, 3]) / 2
310
- order.insert(pos if above else pos + 1, cap)
311
- else: # fallback: insert at the natural spatial position
312
- cap_y0 = boxes[cap, 1]
313
- pos = next((i for i, idx in enumerate(order) if boxes[idx, 1] >= cap_y0), len(order))
314
- order.insert(pos, cap)
756
+ target, best_dist = flt, dist
757
+ if target >= 0 and best_dist <= max_distance:
758
+ # Read right before the float when above its center, otherwise after it
759
+ above = (cy0 + cy1) / 2 <= (boxes[target, 1] + boxes[target, 3]) / 2
760
+ pos = order.index(target) if above else _read_after(target, unit)
761
+ else:
762
+ in_column = [idx for idx in order if min(boxes[idx, 2], cx1) - max(boxes[idx, 0], cx0) > 0]
763
+ above_idcs = [idx for idx in in_column if (boxes[idx, 1] + boxes[idx, 3]) / 2 < cy0]
764
+ if above_idcs:
765
+ pos = _read_after(max(above_idcs, key=lambda idx: boxes[idx, 3]), unit)
766
+ else: # at the top of its column
767
+ fallback = next((i for i, idx in enumerate(order) if boxes[idx, 1] >= cy0), len(order))
768
+ pos = min((order.index(idx) for idx in in_column), default=fallback)
769
+ order[pos:pos] = unit
315
770
  return order
316
771
 
317
772
 
318
- def deskew_reading_geometries(
773
+ # --- Public ordering functions ----------------------------------------------------------------------------------------
774
+
775
+
776
+ def _canonical_boxes(
319
777
  geoms: Sequence[Any] | np.ndarray,
320
- region_geoms: Sequence[Any] | np.ndarray | None = None,
321
- page_shape: tuple[int, int] | None = None,
322
- angle_geoms: Sequence[Any] | np.ndarray | None = None,
323
- min_angle: float = 1.0,
324
- ) -> tuple[list[Any], list[Any]]:
325
- """De-skew rotated geometries so the reading order can be computed in an upright frame.
778
+ direction: str,
779
+ labels: Sequence[str | None] | None,
780
+ region_groups: Sequence[int] | None,
781
+ page_shape: tuple[int, int] | None,
782
+ angle_geoms: Sequence[Any] | np.ndarray | None,
783
+ ) -> np.ndarray:
784
+ """Check the inputs of the ordering functions and return the de-skewed boxes in canonical LTR space"""
785
+ if direction not in SUPPORTED_DIRECTIONS[1:]:
786
+ raise ValueError(f"invalid reading direction '{direction}', should be one of {SUPPORTED_DIRECTIONS[1:]}")
787
+ geoms, _ = deskew_reading_geometries(geoms, page_shape=page_shape, angle_geoms=angle_geoms)
788
+ boxes = _to_boxes(geoms)
789
+ if labels is not None and len(labels) != boxes.shape[0]:
790
+ raise ValueError(f"Incompatible number of labels ({len(labels)}) and geometries ({boxes.shape[0]})")
791
+ if region_groups is not None and len(region_groups) != boxes.shape[0]:
792
+ raise ValueError(
793
+ f"Incompatible number of region groups ({len(region_groups)}) and geometries ({boxes.shape[0]})"
794
+ )
795
+ return _to_canonical_ltr(boxes, direction)
326
796
 
327
- Args:
328
- geoms: geometries of the elements to order, in any docTR format (cf. `sort_reading_order`)
329
- region_geoms: optional geometries of the layout regions, de-skewed together with the elements
330
- page_shape: the page dimensions (height, width). Required for an exact angle on non-square pages with
331
- relative coordinates, since relative coordinates distort angles by the aspect ratio.
332
- angle_geoms: optional reading-oriented 4-point polygons used to estimate the page angle
333
- min_angle: minimum estimated angle (in degrees) to trigger the de-skew. Ordering is affected as soon
334
- as the drift along a line approaches the line height (about 1 degree for a page-wide line), and a
335
- small rigid rotation cannot change the order of an upright page, hence the low default. Beyond 45
336
- degrees the corner identification is ambiguous (an upstream orientation correction is needed) and
337
- nothing is done.
338
797
 
339
- Returns:
340
- the (possibly de-skewed) element and region geometries
341
- """
342
- region_geoms = list(region_geoms) if region_geoms is not None else []
343
- pts = [np.asarray(geom, dtype=np.float64).reshape(-1, 2) for geom in geoms]
344
- if len(pts) == 0 or any(p.shape[0] != 4 for p in pts):
345
- return list(geoms), region_geoms # straight geometries: nothing to de-skew
346
- height, width = page_shape if page_shape is not None else (1, 1)
347
- scale = np.array([width, height], dtype=np.float64)
348
- angle_source = angle_geoms if angle_geoms is not None else []
349
- angle_pts = [np.asarray(geom, dtype=np.float64).reshape(-1, 2) for geom in angle_source]
350
- if len(angle_pts) > 0 and all(p.shape[0] == 4 for p in angle_pts):
351
- # Detection polygons are already reading-oriented (cf. `estimate_page_angle`): keep their vertex order
352
- angle = estimate_page_angle(np.stack(angle_pts) * scale)
353
- else:
354
- # Normalize the vertex order (TL, TR, BR, BL) so the estimation does not depend on the vertex
355
- angle = estimate_page_angle(np.stack([order_points(p * scale) for p in pts]))
356
- if not np.isfinite(angle) or abs(angle) < min_angle or abs(angle) >= 45:
357
- return list(geoms), region_geoms
358
- # Rigid rotation zeroing the estimated angle; the center is irrelevant for ordering purposes
359
- theta = np.deg2rad(angle)
360
- rot = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
361
- all_pts = np.concatenate(pts, axis=0) * scale
362
- center = all_pts.mean(axis=0)
798
+ def _sort(
799
+ canonical: np.ndarray,
800
+ labels: Sequence[str | None] | None,
801
+ x_overlap_threshold: float,
802
+ y_overlap_threshold: float,
803
+ caption_max_distance: float,
804
+ column_voters: Sequence[bool] | None,
805
+ region_groups: Sequence[int] | None,
806
+ ) -> list[int]:
807
+ """Order boxes in canonical LTR space (cf. `sort_reading_order`)"""
808
+ num_boxes = canonical.shape[0]
809
+ if num_boxes <= 1:
810
+ return list(range(num_boxes))
811
+ voters = np.ones(num_boxes, dtype=bool) if column_voters is None else np.asarray(column_voters, dtype=bool)
363
812
 
364
- def _rotate(points: np.ndarray) -> np.ndarray:
365
- return ((points * scale - center) @ rot.T + center) / scale
813
+ def _order(idcs: list[int]) -> list[int]:
814
+ sub_order = _topological_order(canonical[idcs], x_overlap_threshold, y_overlap_threshold, voters[idcs])
815
+ return [idcs[i] for i in sub_order]
366
816
 
367
- deskewed = [_rotate(p) for p in pts]
817
+ if labels is None:
818
+ return _order(list(range(num_boxes)))
368
819
 
369
- def _corners(points: np.ndarray) -> np.ndarray:
370
- # Straight ((xmin, ymin), (xmax, ymax)) regions must be expanded to their 4 corners before rotating,
371
- # otherwise only the diagonal would be rotated and the resulting extent would be underestimated
372
- if points.shape[0] == 4:
373
- return points
374
- (x0, y0), (x1, y1) = points.min(axis=0), points.max(axis=0)
375
- return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
820
+ norm_labels = [normalize_layout_label(label) for label in labels]
821
+ groups: dict[str, list[int]] = {"header": [], "body": [], "caption": [], "footnote": [], "footer": []}
822
+ for idx, label in enumerate(norm_labels):
823
+ role = layout_label_role(label)
824
+ groups["body" if role == "float" else role].append(idx)
376
825
 
377
- region_pts = [np.asarray(geom, dtype=np.float64).reshape(-1, 2) for geom in region_geoms]
378
- regions_out = [_rotate(_corners(p)) for p in region_pts]
379
- return deskewed, regions_out
826
+ # Read the elements inside a float (e.g. the text of a figure) right after it
827
+ members = _float_members(groups["body"], canonical, norm_labels)
828
+ owner = {idx: flt for flt, idcs in members.items() for idx in idcs}
829
+ body_order = _order(groups["body"])
830
+ inside = {flt: [idx for idx in body_order if owner.get(idx) == flt] for flt in members}
831
+ body_order = [elt for idx in body_order if idx not in owner for elt in (idx, *inside.get(idx, []))]
832
+ if region_groups is not None:
833
+ # A float standing beside a region must not interrupt it
834
+ body_order = _defer_floats(body_order, norm_labels, members, region_groups, canonical)
835
+ body_order = _attach_captions(
836
+ body_order, _order(groups["caption"]), canonical, norm_labels, caption_max_distance, region_groups
837
+ )
838
+ return _order(groups["header"]) + body_order + _order(groups["footnote"]) + _order(groups["footer"])
380
839
 
381
840
 
382
841
  def sort_reading_order(
@@ -388,6 +847,8 @@ def sort_reading_order(
388
847
  caption_max_distance: float = 0.1,
389
848
  page_shape: tuple[int, int] | None = None,
390
849
  angle_geoms: Sequence[Any] | np.ndarray | None = None,
850
+ column_voters: Sequence[bool] | None = None,
851
+ region_groups: Sequence[int] | None = None,
391
852
  ) -> list[int]:
392
853
  """Compute the reading order of document elements from their geometries (and optionally, layout labels).
393
854
 
@@ -420,41 +881,74 @@ def sort_reading_order(
420
881
  `deskew_reading_geometries`)
421
882
  angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
422
883
  estimate the page angle on rotated pages (cf. `deskew_reading_geometries`)
884
+ column_voters: optional mask of the elements used to detect a multi-column page (all by default)
885
+ region_groups: optional layout region index of each element (-1 for none), used to attach the captions of
886
+ a region as a unit and to read a float standing beside a region after it
423
887
 
424
888
  Returns:
425
889
  the permutation of the input indices which sorts the elements in reading order
426
890
  """
427
- if direction not in SUPPORTED_DIRECTIONS[1:]:
428
- raise ValueError(f"invalid reading direction '{direction}', should be one of {SUPPORTED_DIRECTIONS[1:]}")
429
- geoms, _ = deskew_reading_geometries(geoms, page_shape=page_shape, angle_geoms=angle_geoms)
430
- boxes = _to_boxes(geoms)
431
- num_boxes = boxes.shape[0]
432
- if labels is not None and len(labels) != num_boxes:
433
- raise ValueError(f"Incompatible number of labels ({len(labels)}) and geometries ({num_boxes})")
434
- if num_boxes <= 1:
435
- return list(range(num_boxes))
891
+ canonical = _canonical_boxes(geoms, direction, labels, region_groups, page_shape, angle_geoms)
892
+ return _sort(
893
+ canonical, labels, x_overlap_threshold, y_overlap_threshold, caption_max_distance, column_voters, region_groups
894
+ )
436
895
 
437
- canonical = _to_canonical_ltr(boxes, direction)
438
896
 
439
- def _order(idcs: list[int]) -> list[int]:
440
- if len(idcs) == 0:
441
- return []
442
- sub_order = _topological_order(canonical[idcs], x_overlap_threshold, y_overlap_threshold)
443
- return [idcs[i] for i in sub_order]
897
+ class _SegmentJoins:
898
+ """Criteria to join two consecutive elements of the reading order in the same segment (cf.
899
+ `resolve_reading_segments`), in canonical LTR space"""
444
900
 
445
- if labels is None:
446
- return _order(list(range(num_boxes)))
447
-
448
- norm_labels = [normalize_layout_label(label) for label in labels]
449
- groups: dict[str, list[int]] = {"header": [], "body": [], "caption": [], "footnote": [], "footer": []}
450
- for idx, label in enumerate(norm_labels):
451
- role = layout_label_role(label)
452
- groups["body" if role == "float" else role].append(idx)
901
+ def __init__(
902
+ self,
903
+ boxes: np.ndarray,
904
+ norm_labels: list[str],
905
+ region_groups: Sequence[int] | None,
906
+ x_overlap_threshold: float,
907
+ y_overlap_threshold: float,
908
+ ) -> None:
909
+ self.boxes, self.labels, self.groups = boxes, norm_labels, region_groups
910
+ self.roles = [layout_label_role(label) for label in norm_labels]
911
+ self.median_height = float(np.median(boxes[:, 3] - boxes[:, 1]))
912
+ self.x_overlap_threshold, self.y_overlap_threshold = x_overlap_threshold, y_overlap_threshold
913
+
914
+ @staticmethod
915
+ def _overlap(start: float, end: float, other_start: float, other_end: float) -> float:
916
+ """1D overlap of two intervals, relative to the shorter one"""
917
+ inter = min(end, other_end) - max(start, other_start)
918
+ return inter / max(min(end - start, other_end - other_start), 1e-9)
919
+
920
+ def _same_region(self, prev: int, cur: int) -> bool:
921
+ return self.groups is None or self.groups[prev] == self.groups[cur]
922
+
923
+ def compatible(self, prev: int, cur: int) -> bool:
924
+ """Same label (not a float) and same layout region"""
925
+ return self.labels[prev] == self.labels[cur] and self.roles[cur] != "float" and self._same_region(prev, cur)
926
+
927
+ def stacked(self, row: np.ndarray, cur: int, paragraph_gap: float) -> bool:
928
+ """Right below the last row of the segment, in the same column"""
929
+ box = self.boxes[cur]
930
+ return (
931
+ self._overlap(row[0], row[2], box[0], box[2]) > self.x_overlap_threshold
932
+ and box[1] - row[3] <= paragraph_gap * self.median_height
933
+ )
453
934
 
454
- body_order = _attach_captions(
455
- _order(groups["body"]), _order(groups["caption"]), canonical, norm_labels, caption_max_distance
456
- )
457
- return _order(groups["header"]) + body_order + _order(groups["footnote"]) + _order(groups["footer"])
935
+ def same_row(self, prev: int, cur: int, row_gap: float, aspect: float) -> bool:
936
+ """On the row of the previous element, after it: the rest of a line split at a wide word gap (at most
937
+ `row_gap` median heights, any gap within a region of body text)"""
938
+ box, prev_box = self.boxes[cur], self.boxes[prev]
939
+ return (
940
+ self._overlap(prev_box[1], prev_box[3], box[1], box[3]) > self.y_overlap_threshold
941
+ and box[0] > prev_box[0]
942
+ and (
943
+ (box[0] - prev_box[2]) * aspect <= row_gap * self.median_height
944
+ or (
945
+ self.groups is not None
946
+ and self.groups[cur] >= 0
947
+ and self._same_region(prev, cur)
948
+ and self.roles[cur] == "body"
949
+ )
950
+ )
951
+ )
458
952
 
459
953
 
460
954
  def resolve_reading_segments(
@@ -467,12 +961,16 @@ def resolve_reading_segments(
467
961
  paragraph_gap: float = 0.8,
468
962
  page_shape: tuple[int, int] | None = None,
469
963
  angle_geoms: Sequence[Any] | np.ndarray | None = None,
964
+ column_voters: Sequence[bool] | None = None,
965
+ region_groups: Sequence[int] | None = None,
966
+ row_gap: float = 1.5,
470
967
  ) -> list[list[int]]:
471
968
  """Order elements in reading order and group consecutive ones into segments (paragraphs or regions).
472
969
 
473
970
  This is typically used to regroup individual lines into paragraphs once they have been put in reading
474
971
  order: two consecutive elements are merged into the same segment when they share the same (possibly None)
475
- layout label, belong to the same column and are vertically close enough.
972
+ layout label and layout region, and either belong to the same column and are vertically close enough, or
973
+ continue the same visual row.
476
974
 
477
975
  Args:
478
976
  geoms: sequence of geometries in any docTR format (cf. `sort_reading_order`)
@@ -491,93 +989,55 @@ def resolve_reading_segments(
491
989
  `deskew_reading_geometries`)
492
990
  angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
493
991
  estimate the page angle on rotated pages (cf. `deskew_reading_geometries`)
992
+ column_voters: optional mask of the elements used to detect a multi-column page (all by default)
993
+ region_groups: optional layout region index of each element (-1 for none), used to attach the captions of
994
+ a region as a unit, to read a float standing beside a region after it, and to keep distinct regions in
995
+ distinct segments
996
+ row_gap: maximum horizontal gap between two consecutive elements of a visual row to join them, as a multiple
997
+ of the median element height (not applied to body text of the same layout region)
494
998
 
495
999
  Returns:
496
1000
  a partition of the input indices into reading-ordered segments (each segment being itself in
497
1001
  reading order)
498
1002
  """
499
- # De-skew once so the ordering and the vertical-gap measurement share the same upright frame
500
- geoms, _ = deskew_reading_geometries(geoms, page_shape=page_shape, angle_geoms=angle_geoms)
1003
+ # The elements are ordered on their upright geometries, in which the gaps between them are measured as well
1004
+ upright, _ = deskew_reading_geometries(geoms, page_shape=page_shape, angle_geoms=angle_geoms)
501
1005
  order = sort_reading_order(
502
- geoms,
1006
+ upright,
503
1007
  direction=direction,
504
1008
  labels=labels,
505
1009
  x_overlap_threshold=x_overlap_threshold,
506
1010
  y_overlap_threshold=y_overlap_threshold,
507
1011
  caption_max_distance=caption_max_distance,
1012
+ column_voters=column_voters,
1013
+ region_groups=region_groups,
508
1014
  )
509
1015
  if len(order) == 0:
510
1016
  return []
511
- canonical = _to_canonical_ltr(_to_boxes(geoms), direction)
512
- median_height = float(np.median(canonical[:, 3] - canonical[:, 1]))
1017
+ canonical = _to_canonical_ltr(_to_boxes(upright), direction)
1018
+ aspect = 1.0 # horizontal distances in the height unit
1019
+ if page_shape is not None and page_shape[0] > 0 and page_shape[1] > 0:
1020
+ aspect = page_shape[0] / page_shape[1] if direction.startswith("ttb") else page_shape[1] / page_shape[0]
513
1021
  norm_labels = [normalize_layout_label(labels[idx] if labels is not None else None) for idx in range(len(order))]
514
-
1022
+ joins = _SegmentJoins(canonical, norm_labels, region_groups, x_overlap_threshold, y_overlap_threshold)
515
1023
  segments: list[list[int]] = [[order[0]]]
1024
+ row = canonical[order[0]].copy() # extent of the last visual row of the current segment
516
1025
  for prev, cur in zip(order[:-1], order[1:]):
517
- x_gap = min(canonical[prev, 2], canonical[cur, 2]) - max(canonical[prev, 0], canonical[cur, 0])
518
- x_overlap = x_gap / max(
519
- min(canonical[prev, 2] - canonical[prev, 0], canonical[cur, 2] - canonical[cur, 0]), 1e-9
520
- )
521
- same_segment = (
522
- norm_labels[prev] == norm_labels[cur]
523
- and layout_label_role(norm_labels[cur]) != "float"
524
- and x_overlap > x_overlap_threshold
525
- and canonical[cur, 1] - canonical[prev, 3] <= paragraph_gap * median_height
526
- )
527
- if same_segment:
1026
+ stacked, same_row = joins.stacked(row, cur, paragraph_gap), joins.same_row(prev, cur, row_gap, aspect)
1027
+ joined = joins.compatible(prev, cur) and (stacked or same_row)
1028
+ if joined:
528
1029
  segments[-1].append(cur)
529
1030
  else:
530
1031
  segments.append([cur])
1032
+ box = canonical[cur]
1033
+ row = (
1034
+ np.concatenate((np.minimum(row[:2], box[:2]), np.maximum(row[2:], box[2:])))
1035
+ if joined and same_row and not stacked
1036
+ else box.copy()
1037
+ )
531
1038
  return segments
532
1039
 
533
1040
 
534
- def assign_layout_labels(
535
- geoms: Sequence[Any] | np.ndarray,
536
- layout_geoms: Sequence[Any] | np.ndarray,
537
- layout_labels: Sequence[str],
538
- min_coverage: float = 0.5,
539
- page_shape: tuple[int, int] | None = None,
540
- angle_geoms: Sequence[Any] | np.ndarray | None = None,
541
- ) -> list[str | None]:
542
- """Assign a layout label to each element based on its overlap with the detected layout regions.
543
-
544
- Each element receives the label of the region covering the largest share of its area, provided this share
545
- reaches `min_coverage`; otherwise its label is None (treated as regular body content).
546
-
547
- Args:
548
- geoms: geometries of the elements to label, in any docTR format
549
- layout_geoms: geometries of the layout regions, in any docTR format
550
- layout_labels: labels of the layout regions (e.g. `[region.type for region in page.layout]`)
551
- min_coverage: minimum share of an element's area a region must cover to assign its label
552
- page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly (cf.
553
- `deskew_reading_geometries`)
554
- angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
555
- estimate the page angle on rotated pages (cf. `deskew_reading_geometries`)
556
-
557
- Returns:
558
- the label of each element (None when no region covers it enough)
559
- """
560
- # De-skew elements and regions together so the coverage is measured on tight boxes in the same frame
561
- geoms, layout_geoms = deskew_reading_geometries(geoms, layout_geoms, page_shape=page_shape, angle_geoms=angle_geoms)
562
- boxes, regions = _to_boxes(geoms), _to_boxes(layout_geoms)
563
- if len(layout_labels) != regions.shape[0]:
564
- raise ValueError(f"Incompatible number of labels ({len(layout_labels)}) and regions ({regions.shape[0]})")
565
- if boxes.shape[0] == 0 or regions.shape[0] == 0:
566
- return [None] * boxes.shape[0]
567
-
568
- inter_w = np.minimum(boxes[:, None, 2], regions[None, :, 2]) - np.maximum(boxes[:, None, 0], regions[None, :, 0])
569
- inter_h = np.minimum(boxes[:, None, 3], regions[None, :, 3]) - np.maximum(boxes[:, None, 1], regions[None, :, 1])
570
- inter = np.clip(inter_w, 0, None) * np.clip(inter_h, 0, None)
571
- areas = np.clip((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]), 1e-9, None)
572
- coverage = inter / areas[:, None]
573
-
574
- best = coverage.argmax(axis=1)
575
- return [
576
- str(layout_labels[reg_idx]) if coverage[box_idx, reg_idx] >= min_coverage else None
577
- for box_idx, reg_idx in enumerate(best)
578
- ]
579
-
580
-
581
1041
  class ReadingOrderPredictor(NestedObject):
582
1042
  """Language-independent reading order estimation for document elements.
583
1043