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
@@ -0,0 +1,1127 @@
1
+ # Copyright (C) 2021-2026, Mindee.
2
+
3
+ # This program is licensed under the Apache License 2.0.
4
+ # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
+
6
+ import unicodedata
7
+ from collections.abc import Iterable, Sequence
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ from scipy.sparse import csr_matrix
12
+ from scipy.sparse.csgraph import connected_components
13
+
14
+ from doctr.utils.geometry import estimate_page_angle, order_points
15
+ from doctr.utils.repr import NestedObject
16
+
17
+ __all__ = [
18
+ "ReadingOrderPredictor",
19
+ "assign_layout_labels",
20
+ "deskew_reading_geometries",
21
+ "detect_text_direction",
22
+ "layout_label_role",
23
+ "normalize_layout_label",
24
+ "resolve_reading_segments",
25
+ "sort_reading_order",
26
+ ]
27
+
28
+ # Directions supported by the ordering functions
29
+ SUPPORTED_DIRECTIONS = ("auto", "ltr", "rtl", "ttb-rtl", "ttb-ltr")
30
+
31
+ # ISO 639 codes of languages predominantly written right-to-left (used as a fallback hint when no text is
32
+ # available, e.g. from the `langdetect` prediction attached to a page)
33
+ RTL_LANGUAGES = {"ar", "arc", "ckb", "dv", "fa", "he", "iw", "ks", "ku", "nqo", "ps", "sd", "syr", "ug", "ur", "yi"}
34
+
35
+ # Unicode bidirectional categories of strong right-to-left characters (Hebrew-like & Arabic-like)
36
+ _RTL_BIDI_CATEGORIES = {"R", "AL"}
37
+
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
58
+
59
+
60
+ def normalize_layout_label(label: str | None) -> str:
61
+ """Normalize a layout label to lower snake case (e.g. 'Page-header' -> 'page_header')
62
+
63
+ Args:
64
+ label: the layout label to normalize (None is mapped to an empty string)
65
+
66
+ Returns:
67
+ the normalized label
68
+ """
69
+ if label is None:
70
+ return ""
71
+ return "".join(c if c.isalnum() else "_" for c in label.strip().lower())
72
+
73
+
74
+ def layout_label_role(label: str | None) -> str:
75
+ """Resolve the role of a layout label in the reading order.
76
+
77
+ Args:
78
+ label: the layout label (e.g. a DocLayNet class such as 'Page-header' or 'Caption')
79
+
80
+ Returns:
81
+ one of 'header', 'footer', 'footnote', 'caption', 'float' or 'body'
82
+ """
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"
89
+
90
+
91
+ def detect_text_direction(texts: Iterable[str], language: str | None = None) -> str:
92
+ """Infer the horizontal base direction of a document from its text content.
93
+
94
+ The detection relies on the Unicode bidirectional property of each character: strong right-to-left
95
+ characters (bidirectional categories `R` and `AL`, covering among others Hebrew, Arabic, Syriac,
96
+ Thaana, N'Ko) are counted against strong left-to-right characters (category `L`). This makes the
97
+ detection language-independent and robust to mixed content. When no strong character is found, the
98
+ optional ISO 639 language code is used as a fallback hint.
99
+
100
+ >>> from doctr.models.reading_order import detect_text_direction
101
+ >>> detect_text_direction(["Hello", "world"])
102
+ 'ltr'
103
+ >>> detect_text_direction(["مرحبا", "بالعالم"])
104
+ 'rtl'
105
+
106
+ Args:
107
+ texts: iterable of text strings (e.g. all the words of a page)
108
+ language: optional ISO 639 language code used as a fallback when the script is inconclusive
109
+
110
+ Returns:
111
+ either "ltr" or "rtl"
112
+ """
113
+ rtl_count = ltr_count = 0
114
+ for text in texts:
115
+ if not isinstance(text, str):
116
+ continue
117
+ for char in text:
118
+ bidi = unicodedata.bidirectional(char)
119
+ rtl_count += bidi in _RTL_BIDI_CATEGORIES
120
+ ltr_count += bidi == "L"
121
+ if rtl_count == 0 and ltr_count == 0:
122
+ rtl_hint = isinstance(language, str) and language.split("-")[0].lower() in RTL_LANGUAGES
123
+ return "rtl" if rtl_hint else "ltr"
124
+ return "rtl" if rtl_count > ltr_count else "ltr"
125
+
126
+
127
+ # --- Geometry helpers -------------------------------------------------------------------------------------------------
128
+
129
+
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"""
132
+ pts = np.asarray(geometry, dtype=np.float64).reshape(-1, 2)
133
+ return float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())
134
+
135
+
136
+ def _to_boxes(geoms: Sequence[Any] | np.ndarray) -> np.ndarray:
137
+ """Return the (N, 4) enclosing boxes of geometries in any docTR format"""
138
+ if isinstance(geoms, np.ndarray) and geoms.ndim == 2 and geoms.shape[1] >= 4:
139
+ return geoms[:, :4].astype(np.float64)
140
+ if isinstance(geoms, np.ndarray) and geoms.ndim == 3:
141
+ return np.concatenate((geoms.min(axis=1), geoms.max(axis=1)), axis=-1).astype(np.float64)
142
+ if len(geoms) == 0:
143
+ return np.zeros((0, 4), dtype=np.float64)
144
+ return np.asarray([_geometry_to_xyxy(geom) for geom in geoms], dtype=np.float64)
145
+
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
+
166
+ def _to_canonical_ltr(boxes: np.ndarray, direction: str) -> np.ndarray:
167
+ """Map boxes to a canonical left-to-right, top-to-bottom space for the given reading direction.
168
+
169
+ Mirroring & axis swapping are performed around the extent of the boxes themselves, so both relative and
170
+ absolute coordinates are supported.
171
+ """
172
+ if direction == "ltr" or boxes.shape[0] == 0:
173
+ return boxes
174
+ x0, y0, x1, y1 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
175
+ pivot = float(x0.min() + x1.max())
176
+ if direction == "rtl": # mirror horizontally
177
+ return np.stack([pivot - x1, y0, pivot - x0, y1], axis=1)
178
+ if direction == "ttb-ltr": # vertical lines, columns ordered left to right: swap axes
179
+ return np.stack([y0, x0, y1, x1], axis=1)
180
+ if direction == "ttb-rtl": # vertical lines, columns ordered right to left: swap axes & mirror
181
+ return np.stack([y0, pivot - x1, y1, pivot - x0], axis=1)
182
+ raise ValueError(f"invalid reading direction '{direction}', should be one of {SUPPORTED_DIRECTIONS[1:]}")
183
+
184
+
185
+ def _overlap_ratios(starts: np.ndarray, ends: np.ndarray) -> np.ndarray:
186
+ """Compute the pairwise 1D overlap of intervals, normalized by the length of the smaller interval"""
187
+ starts = starts.astype(np.float32, copy=False)
188
+ ends = ends.astype(np.float32, copy=False)
189
+ lengths = ends - starts
190
+ inter = np.minimum(ends[:, None], ends[None, :])
191
+ inter -= np.maximum(starts[:, None], starts[None, :])
192
+ np.clip(inter, 0, None, out=inter)
193
+ min_len = np.minimum(lengths, lengths[:, None])
194
+ np.clip(min_len, 1e-9, None, out=min_len)
195
+ inter /= min_len
196
+ return inter
197
+
198
+
199
+ def _strict_rank(primary: np.ndarray, secondary: np.ndarray) -> np.ndarray:
200
+ """Return the rank of each element in the strict total order given by (primary, secondary, index)"""
201
+ order = np.lexsort((np.arange(primary.shape[0]), secondary, primary))
202
+ ranks = np.empty_like(order)
203
+ ranks[order] = np.arange(order.shape[0])
204
+ return ranks
205
+
206
+
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]:
487
+ """Order boxes (already in canonical LTR space) with a column-following topological sort.
488
+
489
+ Two families of "reads-before" relations are used (cf. Breuel 2003):
490
+
491
+ * `i` precedes `j` when they overlap horizontally and `i` lies above `j`
492
+ * `i` precedes `j` when they lie on the same visual row (vertical overlap, no horizontal overlap)
493
+ and `i` is on the left of `j`
494
+
495
+ The relations are resolved with Kahn's algorithm; among the available elements, the traversal favors the
496
+ continuation of the current column (the closest element below the last emitted one with a horizontal
497
+ overlap), which keeps multi-column bodies intact even for non-Manhattan layouts where recursive XY-cuts
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.
501
+ """
502
+ num_boxes = boxes.shape[0]
503
+ if num_boxes <= 1:
504
+ return list(range(num_boxes))
505
+
506
+ x0, y0, x1, y1 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
507
+ x_overlap = _overlap_ratios(x0, x1)
508
+ y_overlap = _overlap_ratios(y0, y1)
509
+ # Strict total orders on both axes, so that the induced relations cannot create 2-cycles
510
+ x_rank, y_rank = _strict_rank(x0, x1), _strict_rank(y0, y1)
511
+
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.
514
+ x_linked = x_overlap > x_overlap_threshold
515
+ edges = y_rank[:, None] < y_rank[None, :] # i is above j...
516
+ edges &= x_linked # ... in the same column
517
+ same_row = y_overlap > y_overlap_threshold
518
+ same_row &= ~x_linked
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
528
+ edges |= same_row
529
+ del same_row
530
+ np.fill_diagonal(edges, False)
531
+
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, :]
557
+ component = connected_components(csr_matrix(col_edges), directed=False, return_labels=True)[1]
558
+
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
571
+
572
+ in_degree = edges.sum(axis=0)
573
+ emitted = np.zeros(num_boxes, dtype=bool)
574
+ order: list[int] = []
575
+ while len(order) < num_boxes:
576
+ ready = np.flatnonzero((in_degree == 0) & ~emitted)
577
+ if ready.size == 0: # cycle safety net (can only happen with degenerate overlapping geometries)
578
+ candidates = np.flatnonzero(~emitted)
579
+ else:
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
583
+ # Topmost first, then leftmost (in canonical space)
584
+ next_idx = int(candidates[np.lexsort((x0[candidates], y0[candidates], after_gutter[candidates]))[0]])
585
+ order.append(next_idx)
586
+ emitted[next_idx] = True
587
+ in_degree = in_degree - edges[next_idx]
588
+ return order
589
+
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
+
721
+ def _attach_captions(
722
+ order: list[int],
723
+ caption_idcs: list[int],
724
+ boxes: np.ndarray,
725
+ labels: list[str],
726
+ max_distance: float,
727
+ region_groups: Sequence[int] | None = None,
728
+ ) -> list[int]:
729
+ """Insert the captions right before (resp. after) the closest float they sit above (resp. below)
730
+
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.
733
+ """
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])
755
+ if dist < best_dist:
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
770
+ return order
771
+
772
+
773
+ # --- Public ordering functions ----------------------------------------------------------------------------------------
774
+
775
+
776
+ def _canonical_boxes(
777
+ geoms: Sequence[Any] | np.ndarray,
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)
796
+
797
+
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)
812
+
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]
816
+
817
+ if labels is None:
818
+ return _order(list(range(num_boxes)))
819
+
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)
825
+
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"])
839
+
840
+
841
+ def sort_reading_order(
842
+ geoms: Sequence[Any] | np.ndarray,
843
+ direction: str = "ltr",
844
+ labels: Sequence[str | None] | None = None,
845
+ x_overlap_threshold: float = 0.2,
846
+ y_overlap_threshold: float = 0.5,
847
+ caption_max_distance: float = 0.1,
848
+ page_shape: tuple[int, int] | None = None,
849
+ angle_geoms: Sequence[Any] | np.ndarray | None = None,
850
+ column_voters: Sequence[bool] | None = None,
851
+ region_groups: Sequence[int] | None = None,
852
+ ) -> list[int]:
853
+ """Compute the reading order of document elements from their geometries (and optionally, layout labels).
854
+
855
+ >>> from doctr.models.reading_order import sort_reading_order
856
+ >>> # A title spanning two columns of text
857
+ >>> geoms = [
858
+ ... ((0.55, 0.2), (0.9, 0.8)), # right column
859
+ ... ((0.1, 0.05), (0.9, 0.15)), # title
860
+ ... ((0.1, 0.2), (0.45, 0.8)), # left column
861
+ ... ]
862
+ >>> sort_reading_order(geoms)
863
+ [1, 2, 0]
864
+
865
+ Args:
866
+ geoms: sequence of geometries in any docTR format (((xmin, ymin), (xmax, ymax)) boxes, 4-point
867
+ polygons, or a (N, 4) / (N, 4, 2) numpy array), in relative or absolute coordinates
868
+ direction: reading direction, one of 'ltr' (Latin, Cyrillic, CJK horizontal, ...), 'rtl' (Arabic,
869
+ Hebrew, ...), 'ttb-rtl' (vertical lines with columns ordered right-to-left, e.g. traditional
870
+ Chinese/Japanese) or 'ttb-ltr' (vertical lines with columns ordered left-to-right)
871
+ labels: optional layout labels (one per geometry, e.g. DocLayNet classes from a docTR layout
872
+ predictor). When provided, page headers are moved first, footnotes and page footers last, and
873
+ captions are attached to the closest figure or table. Unknown or None labels are treated as body.
874
+ x_overlap_threshold: minimum relative horizontal overlap for two elements to be considered vertically
875
+ stacked (same column)
876
+ y_overlap_threshold: minimum relative vertical overlap for two non-stacked elements to be considered
877
+ on the same visual row
878
+ caption_max_distance: maximum relative distance between a caption and a float (table or figure) for
879
+ the caption to be attached to it
880
+ page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly (cf.
881
+ `deskew_reading_geometries`)
882
+ angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
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
887
+
888
+ Returns:
889
+ the permutation of the input indices which sorts the elements in reading order
890
+ """
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
+ )
895
+
896
+
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"""
900
+
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
+ )
934
+
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
+ )
952
+
953
+
954
+ def resolve_reading_segments(
955
+ geoms: Sequence[Any] | np.ndarray,
956
+ direction: str = "ltr",
957
+ labels: Sequence[str | None] | None = None,
958
+ x_overlap_threshold: float = 0.2,
959
+ y_overlap_threshold: float = 0.5,
960
+ caption_max_distance: float = 0.1,
961
+ paragraph_gap: float = 0.8,
962
+ page_shape: tuple[int, int] | None = None,
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,
967
+ ) -> list[list[int]]:
968
+ """Order elements in reading order and group consecutive ones into segments (paragraphs or regions).
969
+
970
+ This is typically used to regroup individual lines into paragraphs once they have been put in reading
971
+ order: two consecutive elements are merged into the same segment when they share the same (possibly None)
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.
974
+
975
+ Args:
976
+ geoms: sequence of geometries in any docTR format (cf. `sort_reading_order`)
977
+ direction: reading direction, one of 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
978
+ labels: optional layout labels (one per geometry), cf. `sort_reading_order`. Elements with a 'float'
979
+ role (tables, pictures) are never merged with their neighbors.
980
+ x_overlap_threshold: minimum relative horizontal overlap for two elements to be considered vertically
981
+ stacked (same column)
982
+ y_overlap_threshold: minimum relative vertical overlap for two non-stacked elements to be considered
983
+ on the same visual row
984
+ caption_max_distance: maximum relative distance between a caption and a float (table or figure) for
985
+ the caption to be attached to it
986
+ paragraph_gap: maximum vertical gap between two consecutive elements to belong to the same segment,
987
+ as a multiple of the median element height
988
+ page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly (cf.
989
+ `deskew_reading_geometries`)
990
+ angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
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)
998
+
999
+ Returns:
1000
+ a partition of the input indices into reading-ordered segments (each segment being itself in
1001
+ reading order)
1002
+ """
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)
1005
+ order = sort_reading_order(
1006
+ upright,
1007
+ direction=direction,
1008
+ labels=labels,
1009
+ x_overlap_threshold=x_overlap_threshold,
1010
+ y_overlap_threshold=y_overlap_threshold,
1011
+ caption_max_distance=caption_max_distance,
1012
+ column_voters=column_voters,
1013
+ region_groups=region_groups,
1014
+ )
1015
+ if len(order) == 0:
1016
+ return []
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]
1021
+ norm_labels = [normalize_layout_label(labels[idx] if labels is not None else None) for idx in range(len(order))]
1022
+ joins = _SegmentJoins(canonical, norm_labels, region_groups, x_overlap_threshold, y_overlap_threshold)
1023
+ segments: list[list[int]] = [[order[0]]]
1024
+ row = canonical[order[0]].copy() # extent of the last visual row of the current segment
1025
+ for prev, cur in zip(order[:-1], order[1:]):
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:
1029
+ segments[-1].append(cur)
1030
+ else:
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
+ )
1038
+ return segments
1039
+
1040
+
1041
+ class ReadingOrderPredictor(NestedObject):
1042
+ """Language-independent reading order estimation for document elements.
1043
+
1044
+ >>> import numpy as np
1045
+ >>> from doctr.models.reading_order import ReadingOrderPredictor
1046
+ >>> predictor = ReadingOrderPredictor()
1047
+ >>> geoms = np.array([[0.55, 0.2, 0.9, 0.8], [0.1, 0.05, 0.9, 0.15], [0.1, 0.2, 0.45, 0.8]])
1048
+ >>> predictor(geoms, texts=["First words of each element", "of the page", "to detect the direction"])
1049
+ [1, 2, 0]
1050
+
1051
+ Args:
1052
+ direction: reading direction, one of 'auto' (inferred from the text content), 'ltr', 'rtl', 'ttb-rtl'
1053
+ or 'ttb-ltr' (cf. `sort_reading_order`). Automatic detection covers horizontal scripts only.
1054
+ x_overlap_threshold: minimum relative horizontal overlap for two elements to be considered vertically
1055
+ stacked (same column)
1056
+ y_overlap_threshold: minimum relative vertical overlap for two non-stacked elements to be considered
1057
+ on the same visual row
1058
+ caption_max_distance: maximum relative distance between a caption and a float (table or figure) for
1059
+ the caption to be attached to it
1060
+ """
1061
+
1062
+ def __init__(
1063
+ self,
1064
+ direction: str = "auto",
1065
+ x_overlap_threshold: float = 0.2,
1066
+ y_overlap_threshold: float = 0.5,
1067
+ caption_max_distance: float = 0.1,
1068
+ ) -> None:
1069
+ if direction not in SUPPORTED_DIRECTIONS:
1070
+ raise ValueError(f"invalid reading direction '{direction}', should be one of {SUPPORTED_DIRECTIONS}")
1071
+ self.direction = direction
1072
+ self.x_overlap_threshold = x_overlap_threshold
1073
+ self.y_overlap_threshold = y_overlap_threshold
1074
+ self.caption_max_distance = caption_max_distance
1075
+
1076
+ def resolve_direction(self, texts: Iterable[str] | None = None, language: str | None = None) -> str:
1077
+ """Resolve the effective reading direction for the given content.
1078
+
1079
+ Args:
1080
+ texts: text content used for the automatic detection (ignored when the direction is explicit)
1081
+ language: optional ISO 639 language code used as a fallback hint
1082
+
1083
+ Returns:
1084
+ the effective reading direction ('ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr')
1085
+ """
1086
+ if self.direction != "auto":
1087
+ return self.direction
1088
+ return detect_text_direction(texts if texts is not None else [], language=language)
1089
+
1090
+ def extra_repr(self) -> str:
1091
+ return f"direction='{self.direction}'"
1092
+
1093
+ def __call__(
1094
+ self,
1095
+ geoms: Sequence[Any] | np.ndarray,
1096
+ texts: Sequence[str] | None = None,
1097
+ labels: Sequence[str | None] | None = None,
1098
+ language: str | None = None,
1099
+ page_shape: tuple[int, int] | None = None,
1100
+ angle_geoms: Sequence[Any] | np.ndarray | None = None,
1101
+ ) -> list[int]:
1102
+ """Compute the reading order of document elements.
1103
+
1104
+ Args:
1105
+ geoms: sequence of geometries in any docTR format (cf. `sort_reading_order`)
1106
+ texts: optional text content of each element (or any text of the page), used for the automatic
1107
+ direction detection
1108
+ labels: optional layout labels (one per geometry), used to handle page furniture & captions
1109
+ language: optional ISO 639 language code used as a fallback hint for the direction detection
1110
+ page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly on
1111
+ non-square pages
1112
+ angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used
1113
+ to estimate the page angle on rotated pages
1114
+
1115
+ Returns:
1116
+ the permutation of the input indices which sorts the elements in reading order
1117
+ """
1118
+ return sort_reading_order(
1119
+ geoms,
1120
+ direction=self.resolve_direction(texts, language=language),
1121
+ labels=labels,
1122
+ x_overlap_threshold=self.x_overlap_threshold,
1123
+ y_overlap_threshold=self.y_overlap_threshold,
1124
+ caption_max_distance=self.caption_max_distance,
1125
+ page_shape=page_shape,
1126
+ angle_geoms=angle_geoms,
1127
+ )