python-doctr 1.0.0__py3-none-any.whl → 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +506 -0
- doctr/contrib/artefacts.py +1 -1
- doctr/contrib/base.py +1 -1
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +5 -3
- doctr/datasets/cord.py +3 -2
- doctr/datasets/datasets/base.py +13 -25
- doctr/datasets/datasets/pytorch.py +15 -5
- doctr/datasets/detection.py +3 -2
- doctr/datasets/doc_artefacts.py +3 -2
- doctr/datasets/funsd.py +3 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +4 -3
- doctr/datasets/ic13.py +5 -3
- doctr/datasets/iiit5k.py +3 -2
- doctr/datasets/iiithws.py +5 -3
- doctr/datasets/imgur5k.py +5 -3
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +5 -3
- doctr/datasets/ocr.py +3 -2
- doctr/datasets/orientation.py +3 -2
- doctr/datasets/recognition.py +3 -2
- doctr/datasets/sroie.py +3 -2
- doctr/datasets/svhn.py +3 -2
- doctr/datasets/svt.py +4 -3
- doctr/datasets/synthtext.py +3 -2
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +15 -6
- doctr/datasets/vocabs.py +3 -1
- doctr/datasets/wildreceipt.py +5 -3
- doctr/file_utils.py +4 -2
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +253 -261
- doctr/io/exporters.py +1275 -0
- doctr/io/html.py +1 -1
- doctr/io/image/base.py +4 -3
- doctr/io/image/pytorch.py +6 -4
- doctr/io/pdf.py +1 -1
- doctr/io/reader.py +1 -1
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +111 -25
- doctr/models/builder.py +533 -62
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +2 -2
- doctr/models/classification/mobilenet/pytorch.py +7 -7
- doctr/models/classification/predictor/pytorch.py +7 -3
- doctr/models/classification/resnet/pytorch.py +6 -6
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +7 -6
- doctr/models/classification/vgg/pytorch.py +4 -3
- doctr/models/classification/vip/layers/pytorch.py +5 -5
- doctr/models/classification/vip/pytorch.py +5 -5
- doctr/models/classification/vit/pytorch.py +4 -4
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +4 -1
- doctr/models/core.py +1 -1
- doctr/models/detection/_utils/base.py +24 -8
- doctr/models/detection/_utils/pytorch.py +1 -1
- doctr/models/detection/core.py +34 -19
- doctr/models/detection/differentiable_binarization/base.py +7 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
- doctr/models/detection/fast/base.py +6 -2
- doctr/models/detection/fast/pytorch.py +4 -4
- doctr/models/detection/linknet/base.py +6 -2
- doctr/models/detection/linknet/pytorch.py +4 -4
- doctr/models/detection/predictor/pytorch.py +4 -3
- doctr/models/detection/zoo.py +3 -3
- doctr/models/factory/hub.py +72 -52
- doctr/models/kie_predictor/base.py +17 -2
- doctr/models/kie_predictor/pytorch.py +42 -11
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +140 -4
- doctr/models/modules/transformer/pytorch.py +1 -1
- doctr/models/modules/vision_transformer/pytorch.py +1 -1
- doctr/models/predictor/base.py +138 -16
- doctr/models/predictor/pytorch.py +151 -9
- doctr/models/preprocessor/pytorch.py +78 -23
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/core.py +1 -1
- doctr/models/recognition/crnn/pytorch.py +6 -8
- doctr/models/recognition/master/base.py +1 -1
- doctr/models/recognition/master/pytorch.py +7 -8
- doctr/models/recognition/parseq/base.py +1 -1
- doctr/models/recognition/parseq/pytorch.py +5 -5
- doctr/models/recognition/predictor/_utils.py +1 -1
- doctr/models/recognition/predictor/pytorch.py +2 -2
- doctr/models/recognition/sar/pytorch.py +2 -2
- doctr/models/recognition/utils.py +9 -11
- doctr/models/recognition/viptr/pytorch.py +4 -6
- doctr/models/recognition/vitstr/base.py +1 -1
- doctr/models/recognition/vitstr/pytorch.py +6 -6
- doctr/models/recognition/zoo.py +6 -7
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +316 -16
- doctr/models/zoo.py +91 -3
- doctr/transforms/functional/base.py +3 -2
- doctr/transforms/functional/pytorch.py +1 -1
- doctr/transforms/modules/base.py +248 -83
- doctr/transforms/modules/pytorch.py +213 -74
- doctr/utils/common_types.py +22 -2
- doctr/utils/data.py +5 -4
- doctr/utils/fonts.py +56 -17
- doctr/utils/geometry.py +136 -19
- doctr/utils/metrics.py +351 -19
- doctr/utils/multithreading.py +6 -3
- doctr/utils/reconstitution.py +697 -133
- doctr/utils/repr.py +1 -1
- doctr/utils/visualization.py +63 -4
- doctr/version.py +1 -1
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.0.dist-info/RECORD +0 -149
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
|
@@ -0,0 +1,667 @@
|
|
|
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
|
+
# 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"}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def normalize_layout_label(label: str | None) -> str:
|
|
47
|
+
"""Normalize a layout label to lower snake case (e.g. 'Page-header' -> 'page_header')
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
label: the layout label to normalize (None is mapped to an empty string)
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
the normalized label
|
|
54
|
+
"""
|
|
55
|
+
if label is None:
|
|
56
|
+
return ""
|
|
57
|
+
return "".join(c if c.isalnum() else "_" for c in label.strip().lower())
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def layout_label_role(label: str | None) -> str:
|
|
61
|
+
"""Resolve the role of a layout label in the reading order.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
label: the layout label (e.g. a DocLayNet class such as 'Page-header' or 'Caption')
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
one of 'header', 'footer', 'footnote', 'caption', 'float' or 'body'
|
|
68
|
+
"""
|
|
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"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def detect_text_direction(texts: Iterable[str], language: str | None = None) -> str:
|
|
84
|
+
"""Infer the horizontal base direction of a document from its text content.
|
|
85
|
+
|
|
86
|
+
The detection relies on the Unicode bidirectional property of each character: strong right-to-left
|
|
87
|
+
characters (bidirectional categories `R` and `AL`, covering among others Hebrew, Arabic, Syriac,
|
|
88
|
+
Thaana, N'Ko) are counted against strong left-to-right characters (category `L`). This makes the
|
|
89
|
+
detection language-independent and robust to mixed content. When no strong character is found, the
|
|
90
|
+
optional ISO 639 language code is used as a fallback hint.
|
|
91
|
+
|
|
92
|
+
>>> from doctr.utils.reading_order import detect_text_direction
|
|
93
|
+
>>> detect_text_direction(["Hello", "world"])
|
|
94
|
+
'ltr'
|
|
95
|
+
>>> detect_text_direction(["مرحبا", "بالعالم"])
|
|
96
|
+
'rtl'
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
texts: iterable of text strings (e.g. all the words of a page)
|
|
100
|
+
language: optional ISO 639 language code used as a fallback when the script is inconclusive
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
either "ltr" or "rtl"
|
|
104
|
+
"""
|
|
105
|
+
rtl_count = 0
|
|
106
|
+
ltr_count = 0
|
|
107
|
+
for text in texts:
|
|
108
|
+
if not isinstance(text, str):
|
|
109
|
+
continue
|
|
110
|
+
for char in text:
|
|
111
|
+
bidi = unicodedata.bidirectional(char)
|
|
112
|
+
if bidi in _RTL_BIDI_CATEGORIES:
|
|
113
|
+
rtl_count += 1
|
|
114
|
+
elif bidi == "L":
|
|
115
|
+
ltr_count += 1
|
|
116
|
+
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"
|
|
120
|
+
return "rtl" if rtl_count > ltr_count else "ltr"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _geometry_to_xyxy(geometry: Any) -> tuple[float, float, float, float]:
|
|
124
|
+
pts = np.asarray(geometry, dtype=np.float64).reshape(-1, 2)
|
|
125
|
+
return float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _to_boxes(geoms: Sequence[Any] | np.ndarray) -> np.ndarray:
|
|
129
|
+
if isinstance(geoms, np.ndarray) and geoms.ndim == 2 and geoms.shape[1] >= 4:
|
|
130
|
+
return geoms[:, :4].astype(np.float64)
|
|
131
|
+
if isinstance(geoms, np.ndarray) and geoms.ndim == 3:
|
|
132
|
+
return np.concatenate((geoms.min(axis=1), geoms.max(axis=1)), axis=-1).astype(np.float64)
|
|
133
|
+
if len(geoms) == 0:
|
|
134
|
+
return np.zeros((0, 4), dtype=np.float64)
|
|
135
|
+
return np.asarray([_geometry_to_xyxy(geom) for geom in geoms], dtype=np.float64)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _to_canonical_ltr(boxes: np.ndarray, direction: str) -> np.ndarray:
|
|
139
|
+
"""Map boxes to a canonical left-to-right, top-to-bottom space for the given reading direction.
|
|
140
|
+
|
|
141
|
+
Mirroring & axis swapping are performed around the extent of the boxes themselves, so both relative and
|
|
142
|
+
absolute coordinates are supported.
|
|
143
|
+
"""
|
|
144
|
+
if direction == "ltr" or boxes.shape[0] == 0:
|
|
145
|
+
return boxes
|
|
146
|
+
x0, y0, x1, y1 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
|
|
147
|
+
if direction == "rtl": # mirror horizontally
|
|
148
|
+
pivot = float(x0.min() + x1.max())
|
|
149
|
+
return np.stack([pivot - x1, y0, pivot - x0, y1], axis=1)
|
|
150
|
+
if direction == "ttb-ltr": # vertical lines, columns ordered left to right: swap axes
|
|
151
|
+
return np.stack([y0, x0, y1, x1], axis=1)
|
|
152
|
+
if direction == "ttb-rtl": # vertical lines, columns ordered right to left: swap axes & mirror
|
|
153
|
+
pivot = float(x0.min() + x1.max())
|
|
154
|
+
return np.stack([y0, pivot - x1, y1, pivot - x0], axis=1)
|
|
155
|
+
raise ValueError(f"invalid reading direction '{direction}', should be one of {SUPPORTED_DIRECTIONS[1:]}")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _overlap_ratios(starts: np.ndarray, ends: np.ndarray) -> np.ndarray:
|
|
159
|
+
"""Compute the pairwise 1D overlap of intervals, normalized by the length of the smaller interval"""
|
|
160
|
+
starts = starts.astype(np.float32, copy=False)
|
|
161
|
+
ends = ends.astype(np.float32, copy=False)
|
|
162
|
+
lengths = ends - starts
|
|
163
|
+
inter = np.minimum(ends[:, None], ends[None, :])
|
|
164
|
+
inter -= np.maximum(starts[:, None], starts[None, :])
|
|
165
|
+
np.clip(inter, 0, None, out=inter)
|
|
166
|
+
min_len = np.minimum(lengths, lengths[:, None])
|
|
167
|
+
np.clip(min_len, 1e-9, None, out=min_len)
|
|
168
|
+
inter /= min_len
|
|
169
|
+
return inter
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _strict_rank(primary: np.ndarray, secondary: np.ndarray) -> np.ndarray:
|
|
173
|
+
"""Return the rank of each element in the strict total order given by (primary, secondary, index)"""
|
|
174
|
+
order = np.lexsort((np.arange(primary.shape[0]), secondary, primary))
|
|
175
|
+
ranks = np.empty_like(order)
|
|
176
|
+
ranks[order] = np.arange(order.shape[0])
|
|
177
|
+
return ranks
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _topological_order(boxes: np.ndarray, x_overlap_threshold: float, y_overlap_threshold: float) -> list[int]:
|
|
181
|
+
"""Order boxes (already in canonical LTR space) with a column-following topological sort.
|
|
182
|
+
|
|
183
|
+
Two families of "reads-before" relations are used (cf. Breuel 2003):
|
|
184
|
+
|
|
185
|
+
* `i` precedes `j` when they overlap horizontally and `i` lies above `j`
|
|
186
|
+
* `i` precedes `j` when they lie on the same visual row (vertical overlap, no horizontal overlap)
|
|
187
|
+
and `i` is on the left of `j`
|
|
188
|
+
|
|
189
|
+
The relations are resolved with Kahn's algorithm; among the available elements, the traversal favors the
|
|
190
|
+
continuation of the current column (the closest element below the last emitted one with a horizontal
|
|
191
|
+
overlap), which keeps multi-column bodies intact even for non-Manhattan layouts where recursive XY-cuts
|
|
192
|
+
fail to find a valid split.
|
|
193
|
+
"""
|
|
194
|
+
num_boxes = boxes.shape[0]
|
|
195
|
+
if num_boxes <= 1:
|
|
196
|
+
return list(range(num_boxes))
|
|
197
|
+
|
|
198
|
+
x0, y0, x1, y1 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
|
|
199
|
+
x_overlap = _overlap_ratios(x0, x1)
|
|
200
|
+
y_overlap = _overlap_ratios(y0, y1)
|
|
201
|
+
|
|
202
|
+
# 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)
|
|
205
|
+
|
|
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.
|
|
208
|
+
x_linked = x_overlap > x_overlap_threshold
|
|
209
|
+
edges = y_rank[:, None] < y_rank[None, :] # i is above j
|
|
210
|
+
edges &= x_linked
|
|
211
|
+
same_row = y_overlap > y_overlap_threshold
|
|
212
|
+
same_row &= ~x_linked
|
|
213
|
+
same_row &= x_rank[:, None] < x_rank[None, :] # i is on the left of j
|
|
214
|
+
edges |= same_row
|
|
215
|
+
del same_row
|
|
216
|
+
np.fill_diagonal(edges, False)
|
|
217
|
+
|
|
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, :]
|
|
233
|
+
component = connected_components(csr_matrix(col_edges), directed=False, return_labels=True)[1]
|
|
234
|
+
|
|
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
|
|
251
|
+
|
|
252
|
+
while len(order) < num_boxes:
|
|
253
|
+
ready = np.flatnonzero((in_degree == 0) & ~emitted)
|
|
254
|
+
if ready.size == 0: # cycle safety net (can only happen with degenerate overlapping geometries)
|
|
255
|
+
ready = np.flatnonzero(~emitted)
|
|
256
|
+
candidates = ready
|
|
257
|
+
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
|
|
273
|
+
# Topmost first, then leftmost (in canonical space)
|
|
274
|
+
next_idx = int(candidates[np.lexsort((x0[candidates], y0[candidates]))[0]])
|
|
275
|
+
order.append(next_idx)
|
|
276
|
+
emitted[next_idx] = True
|
|
277
|
+
in_degree = in_degree - edges[next_idx]
|
|
278
|
+
last = next_idx
|
|
279
|
+
|
|
280
|
+
return order
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _attach_captions(
|
|
284
|
+
order: list[int],
|
|
285
|
+
caption_idcs: list[int],
|
|
286
|
+
boxes: np.ndarray,
|
|
287
|
+
labels: list[str],
|
|
288
|
+
max_distance: float,
|
|
289
|
+
) -> list[int]:
|
|
290
|
+
"""Insert captions right before (resp. after) the closest float they sit above (resp. below).
|
|
291
|
+
|
|
292
|
+
Captions without a float within reach keep their natural spatial position in the body.
|
|
293
|
+
"""
|
|
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
|
|
304
|
+
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)
|
|
315
|
+
return order
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def deskew_reading_geometries(
|
|
319
|
+
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.
|
|
326
|
+
|
|
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
|
+
|
|
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)
|
|
363
|
+
|
|
364
|
+
def _rotate(points: np.ndarray) -> np.ndarray:
|
|
365
|
+
return ((points * scale - center) @ rot.T + center) / scale
|
|
366
|
+
|
|
367
|
+
deskewed = [_rotate(p) for p in pts]
|
|
368
|
+
|
|
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]])
|
|
376
|
+
|
|
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
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def sort_reading_order(
|
|
383
|
+
geoms: Sequence[Any] | np.ndarray,
|
|
384
|
+
direction: str = "ltr",
|
|
385
|
+
labels: Sequence[str | None] | None = None,
|
|
386
|
+
x_overlap_threshold: float = 0.2,
|
|
387
|
+
y_overlap_threshold: float = 0.5,
|
|
388
|
+
caption_max_distance: float = 0.1,
|
|
389
|
+
page_shape: tuple[int, int] | None = None,
|
|
390
|
+
angle_geoms: Sequence[Any] | np.ndarray | None = None,
|
|
391
|
+
) -> list[int]:
|
|
392
|
+
"""Compute the reading order of document elements from their geometries (and optionally, layout labels).
|
|
393
|
+
|
|
394
|
+
>>> from doctr.models.reading_order import sort_reading_order
|
|
395
|
+
>>> # A title spanning two columns of text
|
|
396
|
+
>>> geoms = [
|
|
397
|
+
... ((0.55, 0.2), (0.9, 0.8)), # right column
|
|
398
|
+
... ((0.1, 0.05), (0.9, 0.15)), # title
|
|
399
|
+
... ((0.1, 0.2), (0.45, 0.8)), # left column
|
|
400
|
+
... ]
|
|
401
|
+
>>> sort_reading_order(geoms)
|
|
402
|
+
[1, 2, 0]
|
|
403
|
+
|
|
404
|
+
Args:
|
|
405
|
+
geoms: sequence of geometries in any docTR format (((xmin, ymin), (xmax, ymax)) boxes, 4-point
|
|
406
|
+
polygons, or a (N, 4) / (N, 4, 2) numpy array), in relative or absolute coordinates
|
|
407
|
+
direction: reading direction, one of 'ltr' (Latin, Cyrillic, CJK horizontal, ...), 'rtl' (Arabic,
|
|
408
|
+
Hebrew, ...), 'ttb-rtl' (vertical lines with columns ordered right-to-left, e.g. traditional
|
|
409
|
+
Chinese/Japanese) or 'ttb-ltr' (vertical lines with columns ordered left-to-right)
|
|
410
|
+
labels: optional layout labels (one per geometry, e.g. DocLayNet classes from a docTR layout
|
|
411
|
+
predictor). When provided, page headers are moved first, footnotes and page footers last, and
|
|
412
|
+
captions are attached to the closest figure or table. Unknown or None labels are treated as body.
|
|
413
|
+
x_overlap_threshold: minimum relative horizontal overlap for two elements to be considered vertically
|
|
414
|
+
stacked (same column)
|
|
415
|
+
y_overlap_threshold: minimum relative vertical overlap for two non-stacked elements to be considered
|
|
416
|
+
on the same visual row
|
|
417
|
+
caption_max_distance: maximum relative distance between a caption and a float (table or figure) for
|
|
418
|
+
the caption to be attached to it
|
|
419
|
+
page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly (cf.
|
|
420
|
+
`deskew_reading_geometries`)
|
|
421
|
+
angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
|
|
422
|
+
estimate the page angle on rotated pages (cf. `deskew_reading_geometries`)
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
the permutation of the input indices which sorts the elements in reading order
|
|
426
|
+
"""
|
|
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))
|
|
436
|
+
|
|
437
|
+
canonical = _to_canonical_ltr(boxes, direction)
|
|
438
|
+
|
|
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]
|
|
444
|
+
|
|
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)
|
|
453
|
+
|
|
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"])
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def resolve_reading_segments(
|
|
461
|
+
geoms: Sequence[Any] | np.ndarray,
|
|
462
|
+
direction: str = "ltr",
|
|
463
|
+
labels: Sequence[str | None] | None = None,
|
|
464
|
+
x_overlap_threshold: float = 0.2,
|
|
465
|
+
y_overlap_threshold: float = 0.5,
|
|
466
|
+
caption_max_distance: float = 0.1,
|
|
467
|
+
paragraph_gap: float = 0.8,
|
|
468
|
+
page_shape: tuple[int, int] | None = None,
|
|
469
|
+
angle_geoms: Sequence[Any] | np.ndarray | None = None,
|
|
470
|
+
) -> list[list[int]]:
|
|
471
|
+
"""Order elements in reading order and group consecutive ones into segments (paragraphs or regions).
|
|
472
|
+
|
|
473
|
+
This is typically used to regroup individual lines into paragraphs once they have been put in reading
|
|
474
|
+
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.
|
|
476
|
+
|
|
477
|
+
Args:
|
|
478
|
+
geoms: sequence of geometries in any docTR format (cf. `sort_reading_order`)
|
|
479
|
+
direction: reading direction, one of 'ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr'
|
|
480
|
+
labels: optional layout labels (one per geometry), cf. `sort_reading_order`. Elements with a 'float'
|
|
481
|
+
role (tables, pictures) are never merged with their neighbors.
|
|
482
|
+
x_overlap_threshold: minimum relative horizontal overlap for two elements to be considered vertically
|
|
483
|
+
stacked (same column)
|
|
484
|
+
y_overlap_threshold: minimum relative vertical overlap for two non-stacked elements to be considered
|
|
485
|
+
on the same visual row
|
|
486
|
+
caption_max_distance: maximum relative distance between a caption and a float (table or figure) for
|
|
487
|
+
the caption to be attached to it
|
|
488
|
+
paragraph_gap: maximum vertical gap between two consecutive elements to belong to the same segment,
|
|
489
|
+
as a multiple of the median element height
|
|
490
|
+
page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly (cf.
|
|
491
|
+
`deskew_reading_geometries`)
|
|
492
|
+
angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used to
|
|
493
|
+
estimate the page angle on rotated pages (cf. `deskew_reading_geometries`)
|
|
494
|
+
|
|
495
|
+
Returns:
|
|
496
|
+
a partition of the input indices into reading-ordered segments (each segment being itself in
|
|
497
|
+
reading order)
|
|
498
|
+
"""
|
|
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)
|
|
501
|
+
order = sort_reading_order(
|
|
502
|
+
geoms,
|
|
503
|
+
direction=direction,
|
|
504
|
+
labels=labels,
|
|
505
|
+
x_overlap_threshold=x_overlap_threshold,
|
|
506
|
+
y_overlap_threshold=y_overlap_threshold,
|
|
507
|
+
caption_max_distance=caption_max_distance,
|
|
508
|
+
)
|
|
509
|
+
if len(order) == 0:
|
|
510
|
+
return []
|
|
511
|
+
canonical = _to_canonical_ltr(_to_boxes(geoms), direction)
|
|
512
|
+
median_height = float(np.median(canonical[:, 3] - canonical[:, 1]))
|
|
513
|
+
norm_labels = [normalize_layout_label(labels[idx] if labels is not None else None) for idx in range(len(order))]
|
|
514
|
+
|
|
515
|
+
segments: list[list[int]] = [[order[0]]]
|
|
516
|
+
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:
|
|
528
|
+
segments[-1].append(cur)
|
|
529
|
+
else:
|
|
530
|
+
segments.append([cur])
|
|
531
|
+
return segments
|
|
532
|
+
|
|
533
|
+
|
|
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
|
+
class ReadingOrderPredictor(NestedObject):
|
|
582
|
+
"""Language-independent reading order estimation for document elements.
|
|
583
|
+
|
|
584
|
+
>>> import numpy as np
|
|
585
|
+
>>> from doctr.models.reading_order import ReadingOrderPredictor
|
|
586
|
+
>>> predictor = ReadingOrderPredictor()
|
|
587
|
+
>>> 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]])
|
|
588
|
+
>>> predictor(geoms, texts=["First words of each element", "of the page", "to detect the direction"])
|
|
589
|
+
[1, 2, 0]
|
|
590
|
+
|
|
591
|
+
Args:
|
|
592
|
+
direction: reading direction, one of 'auto' (inferred from the text content), 'ltr', 'rtl', 'ttb-rtl'
|
|
593
|
+
or 'ttb-ltr' (cf. `sort_reading_order`). Automatic detection covers horizontal scripts only.
|
|
594
|
+
x_overlap_threshold: minimum relative horizontal overlap for two elements to be considered vertically
|
|
595
|
+
stacked (same column)
|
|
596
|
+
y_overlap_threshold: minimum relative vertical overlap for two non-stacked elements to be considered
|
|
597
|
+
on the same visual row
|
|
598
|
+
caption_max_distance: maximum relative distance between a caption and a float (table or figure) for
|
|
599
|
+
the caption to be attached to it
|
|
600
|
+
"""
|
|
601
|
+
|
|
602
|
+
def __init__(
|
|
603
|
+
self,
|
|
604
|
+
direction: str = "auto",
|
|
605
|
+
x_overlap_threshold: float = 0.2,
|
|
606
|
+
y_overlap_threshold: float = 0.5,
|
|
607
|
+
caption_max_distance: float = 0.1,
|
|
608
|
+
) -> None:
|
|
609
|
+
if direction not in SUPPORTED_DIRECTIONS:
|
|
610
|
+
raise ValueError(f"invalid reading direction '{direction}', should be one of {SUPPORTED_DIRECTIONS}")
|
|
611
|
+
self.direction = direction
|
|
612
|
+
self.x_overlap_threshold = x_overlap_threshold
|
|
613
|
+
self.y_overlap_threshold = y_overlap_threshold
|
|
614
|
+
self.caption_max_distance = caption_max_distance
|
|
615
|
+
|
|
616
|
+
def resolve_direction(self, texts: Iterable[str] | None = None, language: str | None = None) -> str:
|
|
617
|
+
"""Resolve the effective reading direction for the given content.
|
|
618
|
+
|
|
619
|
+
Args:
|
|
620
|
+
texts: text content used for the automatic detection (ignored when the direction is explicit)
|
|
621
|
+
language: optional ISO 639 language code used as a fallback hint
|
|
622
|
+
|
|
623
|
+
Returns:
|
|
624
|
+
the effective reading direction ('ltr', 'rtl', 'ttb-rtl' or 'ttb-ltr')
|
|
625
|
+
"""
|
|
626
|
+
if self.direction != "auto":
|
|
627
|
+
return self.direction
|
|
628
|
+
return detect_text_direction(texts if texts is not None else [], language=language)
|
|
629
|
+
|
|
630
|
+
def extra_repr(self) -> str:
|
|
631
|
+
return f"direction='{self.direction}'"
|
|
632
|
+
|
|
633
|
+
def __call__(
|
|
634
|
+
self,
|
|
635
|
+
geoms: Sequence[Any] | np.ndarray,
|
|
636
|
+
texts: Sequence[str] | None = None,
|
|
637
|
+
labels: Sequence[str | None] | None = None,
|
|
638
|
+
language: str | None = None,
|
|
639
|
+
page_shape: tuple[int, int] | None = None,
|
|
640
|
+
angle_geoms: Sequence[Any] | np.ndarray | None = None,
|
|
641
|
+
) -> list[int]:
|
|
642
|
+
"""Compute the reading order of document elements.
|
|
643
|
+
|
|
644
|
+
Args:
|
|
645
|
+
geoms: sequence of geometries in any docTR format (cf. `sort_reading_order`)
|
|
646
|
+
texts: optional text content of each element (or any text of the page), used for the automatic
|
|
647
|
+
direction detection
|
|
648
|
+
labels: optional layout labels (one per geometry), used to handle page furniture & captions
|
|
649
|
+
language: optional ISO 639 language code used as a fallback hint for the direction detection
|
|
650
|
+
page_shape: the page dimensions (height, width), used to de-skew rotated pages exactly on
|
|
651
|
+
non-square pages
|
|
652
|
+
angle_geoms: optional reading-oriented 4-point polygons (typically the page's word polygons) used
|
|
653
|
+
to estimate the page angle on rotated pages
|
|
654
|
+
|
|
655
|
+
Returns:
|
|
656
|
+
the permutation of the input indices which sorts the elements in reading order
|
|
657
|
+
"""
|
|
658
|
+
return sort_reading_order(
|
|
659
|
+
geoms,
|
|
660
|
+
direction=self.resolve_direction(texts, language=language),
|
|
661
|
+
labels=labels,
|
|
662
|
+
x_overlap_threshold=self.x_overlap_threshold,
|
|
663
|
+
y_overlap_threshold=self.y_overlap_threshold,
|
|
664
|
+
caption_max_distance=self.caption_max_distance,
|
|
665
|
+
page_shape=page_shape,
|
|
666
|
+
angle_geoms=angle_geoms,
|
|
667
|
+
)
|
doctr/models/recognition/core.py
CHANGED