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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -0,0 +1,430 @@
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
+ """Assemble the cells of a table structure model and the words of the table into a consistent grid.
7
+
8
+ Boxes are `(x0, y0, x1, y1)` in the upright table frame, logical coordinates are `(row_start, row_end, col_start,
9
+ col_end)` (0-indexed, inclusive).
10
+ """
11
+
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+
16
+ __all__ = ["fill_table_grid", "assemble_page_table"]
17
+
18
+
19
+ def as_polygons(geometries: Any) -> np.ndarray:
20
+ """Convert straight boxes or (TL, TR, BR, BL) polygons to (N, 4, 2) float32 polygons"""
21
+ flat = np.asarray(geometries, dtype=np.float32)
22
+ flat = flat.reshape(len(flat), -1) if flat.size else np.zeros((0, 4), dtype=np.float32)
23
+ if flat.shape[1] == 4:
24
+ x0, y0, x1, y1 = flat.T
25
+ return np.stack([np.stack(pt, axis=-1) for pt in ((x0, y0), (x1, y0), (x1, y1), (x0, y1))], axis=1)
26
+ return flat.reshape(-1, 4, 2)
27
+
28
+
29
+ def _grid_lines(start: np.ndarray, end: np.ndarray, lo: np.ndarray, hi: np.ndarray, size: int) -> np.ndarray:
30
+ """Positions of the `size + 1` grid lines of an axis: the median of the cell edges on each line, interpolated
31
+ where no edge lies"""
32
+ edges: list[list[float]] = [[] for _ in range(size + 1)]
33
+ for s, e, low, high in zip(start, end, lo, hi):
34
+ edges[int(s)].append(float(low))
35
+ edges[int(e) + 1].append(float(high))
36
+ known = [k for k, values in enumerate(edges) if values]
37
+ return np.maximum.accumulate(np.interp(np.arange(size + 1), known, [float(np.median(edges[k])) for k in known]))
38
+
39
+
40
+ def _group(values: np.ndarray, tol: float) -> np.ndarray:
41
+ """Group index of each 1D position, a group gathering the positions closer than `tol` to its mean"""
42
+ groups = np.zeros(values.size, dtype=np.int64)
43
+ group = 0
44
+ members: list[int] = []
45
+ for j in np.argsort(values, kind="stable"):
46
+ if members and values[j] - np.mean(values[members]) >= tol:
47
+ group, members = group + 1, []
48
+ groups[j] = group
49
+ members.append(j)
50
+ return groups
51
+
52
+
53
+ def _axis_slots(lo: np.ndarray, hi: np.ndarray, lines: np.ndarray, line_tol: float | None) -> np.ndarray:
54
+ """Index of each word along an axis. The words beyond the grid get new indices, grouped by text line (rows,
55
+ `line_tol`) or by overlapping extent (columns, `line_tol=None`)"""
56
+ size, center = lines.size - 1, (lo + hi) / 2
57
+ idx = np.clip(np.searchsorted(lines, center, side="right") - 1, 0, size - 1)
58
+ for before, mask in ((True, center < lines[0]), (False, center > lines[-1])):
59
+ members = np.flatnonzero(mask)
60
+ if members.size == 0:
61
+ continue
62
+ if line_tol is not None:
63
+ groups = _group(center[members], line_tol)
64
+ else: # chain the overlapping extents
65
+ groups, group, reach = np.zeros(members.size, dtype=np.int64), -1, -np.inf
66
+ for j in np.argsort(lo[members], kind="stable"):
67
+ if lo[members[j]] > reach:
68
+ group += 1
69
+ groups[j], reach = group, max(reach, hi[members[j]])
70
+ idx[members] = groups - (groups.max() + 1) if before else size + groups
71
+ return idx
72
+
73
+
74
+ class _Grid:
75
+ """The cells of a table: boxes, logical coordinates, word indices and source cell (-1 if made from words)"""
76
+
77
+ def __init__(self, boxes: np.ndarray, logic: np.ndarray, words: np.ndarray):
78
+ self.boxes = [np.asarray(b, dtype=np.float64) for b in boxes]
79
+ self.logic = [list(map(int, lc)) for lc in logic]
80
+ self.cell_words: list[list[int]] = [[] for _ in self.boxes]
81
+ self.origin = list(range(len(self.boxes)))
82
+ self.words = words
83
+
84
+ def add(self, box: np.ndarray, logic: list[int], words: list[int], origin: int = -1) -> None:
85
+ self.boxes.append(np.asarray(box, dtype=np.float64))
86
+ self.logic.append(logic)
87
+ self.cell_words.append(words)
88
+ self.origin.append(origin)
89
+
90
+ def keep(self, mask: np.ndarray) -> None:
91
+ for name in ("boxes", "logic", "cell_words", "origin"):
92
+ setattr(self, name, [v for v, k in zip(getattr(self, name), mask) if k])
93
+
94
+ def localize(self) -> None:
95
+ """Shift the logical coordinates so that the first row and column are 0"""
96
+ logic = np.asarray(self.logic)
97
+ logic -= [logic[:, 0].min()] * 2 + [logic[:, 2].min()] * 2
98
+ self.logic = logic.tolist()
99
+
100
+ def text_box(self, c_idx: int) -> np.ndarray:
101
+ boxes = self.words[self.cell_words[c_idx]]
102
+ return np.concatenate([boxes[:, :2].min(axis=0), boxes[:, 2:].max(axis=0)])
103
+
104
+ def lines(self, axis: int) -> np.ndarray:
105
+ """The grid lines of the rows (axis 0) or columns (axis 1)"""
106
+ logic, boxes = np.asarray(self.logic), np.asarray(self.boxes)
107
+ lo, hi = (1, 3) if axis == 0 else (0, 2)
108
+ size = int(logic[:, 2 * axis + 1].max()) + 1
109
+ return _grid_lines(logic[:, 2 * axis], logic[:, 2 * axis + 1], boxes[:, lo], boxes[:, hi], size)
110
+
111
+
112
+ def _complete(grid: _Grid, leftover: np.ndarray, line_height: float) -> None:
113
+ """Place the words lying in no cell: in the cell covering their slot, or in a new cell (a missed cell, or a new
114
+ row / column beyond the grid)"""
115
+ words = grid.words[leftover]
116
+ row_lines, col_lines = grid.lines(0), grid.lines(1)
117
+ rows = _axis_slots(words[:, 1], words[:, 3], row_lines, line_height / 2)
118
+ cols = _axis_slots(words[:, 0], words[:, 2], col_lines, None)
119
+ occupied: dict[tuple[int, int], int] = {}
120
+ for c_idx, (rs, re, cs, ce) in enumerate(grid.logic):
121
+ for r in range(rs, re + 1):
122
+ for c in range(cs, ce + 1):
123
+ occupied.setdefault((r, c), c_idx)
124
+
125
+ new_cells: dict[tuple[int, int, int, int], list[int]] = {}
126
+ in_grid = (rows >= 0) & (rows < row_lines.size - 1)
127
+ for j in np.flatnonzero(in_grid):
128
+ slot = (int(rows[j]), int(cols[j]))
129
+ if slot in occupied:
130
+ grid.cell_words[occupied[slot]].append(int(leftover[j]))
131
+ else:
132
+ new_cells.setdefault((slot[0], slot[0], slot[1], slot[1]), []).append(int(j))
133
+ for r in np.unique(rows[~in_grid]):
134
+ # New row: a word starts a new cell in another column, unless it continues a sentence
135
+ members = np.flatnonzero(rows == r)
136
+ groups: list[list[int]] = []
137
+ for j in members[np.argsort(words[members, 0], kind="stable")]:
138
+ prev = groups[-1][-1] if groups else None
139
+ if prev is None or (cols[j] != cols[prev] and words[j, 0] - words[prev, 2] >= line_height / 2):
140
+ groups.append([])
141
+ groups[-1].append(int(j))
142
+ spans: list[tuple[int, int, list[int]]] = []
143
+ for group in groups:
144
+ lo, hi = int(cols[group].min()), int(cols[group].max())
145
+ while spans and lo <= spans[-1][1]: # overlapping words: a column belongs to a single cell
146
+ prev_lo, prev_hi, prev_group = spans.pop()
147
+ lo, hi, group = min(lo, prev_lo), max(hi, prev_hi), prev_group + group
148
+ spans.append((lo, hi, group))
149
+ for lo, hi, group in spans:
150
+ new_cells[(int(r), int(r), lo, hi)] = group
151
+
152
+ def band(lines: np.ndarray, start: int, end: int) -> tuple[float, float]:
153
+ # Unbounded beyond the grid
154
+ size = lines.size - 1
155
+ return (lines[start] if 0 <= start < size else np.inf, lines[end + 1] if 0 <= end < size else -np.inf)
156
+
157
+ for (rs, re, cs, ce), positions in new_cells.items():
158
+ text = words[positions]
159
+ (x0, x1), (y0, y1) = band(col_lines, cs, ce), band(row_lines, rs, re)
160
+ box = [min(x0, text[:, 0].min()), min(y0, text[:, 1].min())]
161
+ box += [max(x1, text[:, 2].max()), max(y1, text[:, 3].max())]
162
+ grid.add(np.array(box), [rs, re, cs, ce], [int(leftover[j]) for j in positions])
163
+ grid.localize()
164
+
165
+
166
+ def _merge_and_prune(grid: _Grid) -> None:
167
+ """Merge the adjacent rows / columns the model split (complementary text on the same text line / column), then
168
+ remove the rows / columns in which no single-span cell holds text"""
169
+ logic = np.asarray(grid.logic)
170
+ filled = np.array([len(w) > 0 for w in grid.cell_words])
171
+ if not filled.any():
172
+ return
173
+ text = np.array([grid.text_box(i) if filled[i] else np.full(4, np.nan) for i in range(len(grid.boxes))])
174
+ boxes = np.asarray(grid.boxes)
175
+ alive = np.ones(len(boxes), dtype=bool)
176
+
177
+ def mergeable(axis: int, k: int) -> bool:
178
+ start, end = logic[:, 2 * axis], logic[:, 2 * axis + 1]
179
+ o_start, o_end = logic[:, 2 - 2 * axis], logic[:, 3 - 2 * axis]
180
+ in_k, in_next = alive & (start <= k) & (end >= k), alive & (start <= k + 1) & (end >= k + 1)
181
+ a, b = np.flatnonzero(in_k & ~in_next & filled), np.flatnonzero(in_next & ~in_k & filled)
182
+ if a.size == 0 or b.size == 0:
183
+ return False
184
+ if np.any((o_start[a, None] <= o_end[None, b]) & (o_start[None, b] <= o_end[a, None])):
185
+ return False # both hold text in a same column / row
186
+ lo, hi = (1, 3) if axis == 0 else (0, 2)
187
+ a_lo, a_hi, b_lo, b_hi = text[a, lo].min(), text[a, hi].max(), text[b, lo].min(), text[b, hi].max()
188
+ return bool(min(a_hi, b_hi) - max(a_lo, b_lo) >= 0.5 * min(a_hi - a_lo, b_hi - b_lo))
189
+
190
+ def shift(axis: int, k: int, merge: bool) -> None:
191
+ # Merge the index k + 1 into k, or remove the index k
192
+ start, end = logic[:, 2 * axis], logic[:, 2 * axis + 1]
193
+ end[alive & ((end > k) if merge else (end >= k))] -= 1
194
+ start[alive & (start > k)] -= 1
195
+
196
+ def absorb_overlaps() -> None:
197
+ # A cell absorbs the empty cells now sharing a slot with it
198
+ for i in np.flatnonzero(alive & filled).tolist() + np.flatnonzero(alive & ~filled).tolist():
199
+ if not alive[i]:
200
+ continue
201
+ others = np.flatnonzero(alive & ~filled)
202
+ others = others[others != i]
203
+ hits = others[
204
+ (logic[others, 0] <= logic[i, 1])
205
+ & (logic[i, 0] <= logic[others, 1])
206
+ & (logic[others, 2] <= logic[i, 3])
207
+ & (logic[i, 2] <= logic[others, 3])
208
+ ]
209
+ if hits.size:
210
+ boxes[i, :2] = np.minimum(boxes[i, :2], boxes[hits, :2].min(axis=0))
211
+ boxes[i, 2:] = np.maximum(boxes[i, 2:], boxes[hits, 2:].max(axis=0))
212
+ logic[i, ::2] = np.minimum(logic[i, ::2], logic[hits, ::2].min(axis=0))
213
+ logic[i, 1::2] = np.maximum(logic[i, 1::2], logic[hits, 1::2].max(axis=0))
214
+ alive[hits] = False
215
+
216
+ changed = True
217
+ while changed:
218
+ changed = False
219
+ for axis in (0, 1):
220
+ for k in range(int(logic[alive, 2 * axis + 1].max())):
221
+ if mergeable(axis, k):
222
+ shift(axis, k, merge=True)
223
+ absorb_overlaps()
224
+ changed = True
225
+ break
226
+ for axis in (0, 1):
227
+ start, end = logic[:, 2 * axis], logic[:, 2 * axis + 1]
228
+ for k in range(int(end[alive].max()), -1, -1):
229
+ if not np.any(alive & filled & (start == k) & (end == k)):
230
+ alive[alive & (start == k) & (end == k)] = False
231
+ shift(axis, k, merge=False)
232
+ grid.boxes, grid.logic = list(boxes), logic.tolist()
233
+ grid.keep(alive)
234
+ grid.localize()
235
+
236
+
237
+ def _split_rows(grid: _Grid, line_height: float) -> None:
238
+ """Split the rows the model merged along their text lines: a row most of whose filled cells hold several lines
239
+ (a single cell wrapping its text does not split its row), and a spanning cell whose text lines each lie level
240
+ with a different row"""
241
+ centers = (grid.words[:, 1] + grid.words[:, 3]) / 2
242
+
243
+ def split(c_idx: int, line_of: np.ndarray, spans: list[tuple[int, int]]) -> None:
244
+ # One cell per text line, cut midway between the lines (the text may lie beyond the box of its cell)
245
+ words, (x0, y0, x1, y1) = np.asarray(grid.cell_words[c_idx]), grid.boxes[c_idx]
246
+ tops = [grid.words[words[line_of == k], 1].min() for k in range(len(spans))]
247
+ bottoms = [grid.words[words[line_of == k], 3].max() for k in range(len(spans))]
248
+ cuts = [min(y0, tops[0]), *[(b + t) / 2 for b, t in zip(bottoms[:-1], tops[1:])], max(y1, bottoms[-1])]
249
+ _, _, cs, ce = grid.logic[c_idx]
250
+ for k, (rs, re) in enumerate(spans):
251
+ box, logic, members = (
252
+ np.array([x0, cuts[k], x1, cuts[k + 1]]),
253
+ [rs, re, cs, ce],
254
+ words[line_of == k].tolist(),
255
+ )
256
+ if k == 0:
257
+ grid.boxes[c_idx], grid.logic[c_idx], grid.cell_words[c_idx] = box, logic, members
258
+ else:
259
+ grid.add(box, logic, members, grid.origin[c_idx])
260
+
261
+ # From the bottom up, so that the rows still to process do not move
262
+ for r in range(max(lc[1] for lc in grid.logic), -1, -1):
263
+ in_row = [i for i, lc in enumerate(grid.logic) if lc[0] == lc[1] == r]
264
+ filled = [i for i in in_row if grid.cell_words[i]]
265
+ words = [w for i in filled for w in grid.cell_words[i]]
266
+ if len(filled) < 2:
267
+ continue
268
+ line_of = dict(zip(words, _group(centers[words], line_height / 2).tolist()))
269
+ n_lines = max(line_of.values()) + 1
270
+ multi = [i for i in filled if len({line_of[w] for w in grid.cell_words[i]}) > 1]
271
+ if len(multi) < 2 or 2 * len(multi) < len(filled):
272
+ continue
273
+ for lc in grid.logic: # the rows below move down, the cells spanning the row grow
274
+ if not lc[0] == lc[1] == r:
275
+ lc[0] += n_lines - 1 if lc[0] > r else 0
276
+ lc[1] += n_lines - 1 if lc[1] >= r else 0
277
+ for i in in_row:
278
+ if not grid.cell_words[i]:
279
+ grid.logic[i][1] = r + n_lines - 1
280
+ continue
281
+ lines = np.array([line_of[w] for w in grid.cell_words[i]])
282
+ present = np.unique(lines)
283
+ split(i, np.searchsorted(present, lines), [(r + k, r + k) for k in present])
284
+
285
+ def level_with_row(c_idx: int, row: int, lo: float, hi: float) -> bool:
286
+ # Whether a text line (lo to hi) is level with the text of another cell of the row
287
+ return any(
288
+ j != c_idx
289
+ and grid.logic[j][0] == row == grid.logic[j][1]
290
+ and any(min(hi, y1) - max(lo, y0) > 0.5 * (hi - lo) for _, y0, _, y1 in grid.words[grid.cell_words[j]])
291
+ for j in range(len(grid.boxes))
292
+ )
293
+
294
+ row_lines = grid.lines(0)
295
+ for i in range(len(grid.boxes)):
296
+ rs, re = grid.logic[i][:2]
297
+ if re == rs or len(grid.cell_words[i]) < 2:
298
+ continue
299
+ idcs = np.asarray(grid.cell_words[i])
300
+ cell_lines = _group(centers[idcs], line_height / 2)
301
+ rows: list[int] = [] # row of each text line
302
+ for k in range(int(cell_lines.max()) + 1):
303
+ lo, hi = grid.words[idcs[cell_lines == k], 1].min(), grid.words[idcs[cell_lines == k], 3].max()
304
+ row = int(np.clip(np.searchsorted(row_lines, (lo + hi) / 2, side="right") - 1, rs, re))
305
+ if row in rows or not level_with_row(i, row, lo, hi):
306
+ rows = []
307
+ break
308
+ rows.append(row)
309
+ if len(rows) > 1:
310
+ # Each text line spans until the row of the next one
311
+ starts, ends = [rs, *rows[1:]], [*(row - 1 for row in rows[1:]), re]
312
+ split(i, cell_lines, list(zip(starts, ends)))
313
+
314
+
315
+ def _reading_order(words: np.ndarray, idcs: list[int], line_height: float) -> list[int]:
316
+ """Order the words of a cell: text lines top to bottom, words left to right"""
317
+ lines = _group((words[idcs, 1] + words[idcs, 3]) / 2, line_height / 2)
318
+ return [idcs[j] for j in np.lexsort((words[idcs, 0], lines))]
319
+
320
+
321
+ def fill_table_grid(
322
+ cells: np.ndarray, logic: np.ndarray, words: np.ndarray
323
+ ) -> tuple[np.ndarray, np.ndarray, list[list[int]], list[int]]:
324
+ """Make the grid of a table consistent with its text, and assign every word of the table to a cell.
325
+
326
+ The words outside of every cell complete the grid, the rows / columns split by the model are merged, the ones
327
+ without text are removed, and the rows merged by the model are split along their text lines.
328
+
329
+ Args:
330
+ cells: the (C, 4) cell boxes predicted by the table model
331
+ logic: the (C, 4) logical coordinates of the cells
332
+ words: the (W, 4) boxes of the words of the table, in the same frame
333
+
334
+ Returns:
335
+ the cell boxes, their local logical coordinates, the indices of their words in reading order, and the index of
336
+ the predicted cell each one comes from (-1 for a cell made from words)
337
+ """
338
+ grid = _Grid(cells, logic, np.asarray(words, dtype=np.float64).reshape(-1, 4))
339
+ if len(grid.boxes) == 0:
340
+ return np.zeros((0, 4)), np.zeros((0, 4), dtype=np.int64), [], []
341
+ grid.localize()
342
+ w = grid.words
343
+ if w.shape[0] > 0:
344
+ centers = (w[:, :2] + w[:, 2:]) / 2
345
+ boxes = np.asarray(grid.boxes)
346
+ inside = (
347
+ (boxes[None, :, 0] <= centers[:, None, 0])
348
+ & (centers[:, None, 0] <= boxes[None, :, 2])
349
+ & (boxes[None, :, 1] <= centers[:, None, 1])
350
+ & (centers[:, None, 1] <= boxes[None, :, 3])
351
+ )
352
+ assigned = inside.any(axis=1)
353
+ for w_idx, c_idx in zip(np.flatnonzero(assigned), inside[assigned].argmax(axis=1)):
354
+ grid.cell_words[c_idx].append(int(w_idx))
355
+ line_height = float(np.median(w[:, 3] - w[:, 1]))
356
+ line_height = line_height if line_height > 0 else 1.0
357
+ if not assigned.all():
358
+ _complete(grid, np.flatnonzero(~assigned), line_height)
359
+ _merge_and_prune(grid)
360
+ _split_rows(grid, line_height)
361
+ grid.localize()
362
+ grid.cell_words = [_reading_order(w, idcs, line_height) if idcs else [] for idcs in grid.cell_words]
363
+ return np.asarray(grid.boxes), np.asarray(grid.logic, dtype=np.int64), grid.cell_words, grid.origin
364
+
365
+
366
+ def _rotate(points: np.ndarray, angle: float, pivot: np.ndarray) -> np.ndarray:
367
+ """Rotate (..., 2) points by `angle` radians around `pivot`"""
368
+ cos_a, sin_a = np.cos(angle), np.sin(angle)
369
+ x, y = points[..., 0] - pivot[0], points[..., 1] - pivot[1]
370
+ return np.stack([pivot[0] + x * cos_a - y * sin_a, pivot[1] + x * sin_a + y * cos_a], axis=-1)
371
+
372
+
373
+ def assemble_page_table(
374
+ cells: list[dict[str, Any]], word_boxes: np.ndarray, page_shape: tuple[int, int], taken: np.ndarray
375
+ ) -> tuple[list[dict[str, Any]], int, int]:
376
+ """Assemble a table given in page coordinates with the words of the page.
377
+
378
+ The cells listing their words (`"words"`) keep them, otherwise the free words inside the outline of the cells are
379
+ assigned with `fill_table_grid`.
380
+
381
+ Args:
382
+ cells: the cells `{"geometry", "score", "row_start", "row_end", "col_start", "col_end"}` of the table, with
383
+ page-relative geometries (straight boxes or polygons)
384
+ word_boxes: the (N, 4) or (N, 4, 2) page-relative word boxes
385
+ page_shape: the (height, width) of the page
386
+ taken: the (N,) mask of the words already assigned to a table, updated in place
387
+
388
+ Returns:
389
+ the cells (local logical coordinates, (4, 2) page-relative polygon, `"words"` in reading order), the number of
390
+ rows and the number of columns
391
+ """
392
+ scale = np.array([page_shape[1], page_shape[0]], dtype=np.float64)
393
+ polys = as_polygons([cell["geometry"] for cell in cells]) * scale
394
+ logic = np.array([[c["row_start"], c["row_end"], c["col_start"], c["col_end"]] for c in cells], dtype=np.int64)
395
+ if all("words" in cell for cell in cells):
396
+ cell_words = [[int(i) for i in cell["words"] if not taken[i]] for cell in cells]
397
+ origin = list(range(len(cells)))
398
+ logic -= [logic[:, 0].min()] * 2 + [logic[:, 2].min()] * 2
399
+ else:
400
+ # Upright frame of the table rows
401
+ top_edges = polys[:, 1] - polys[:, 0]
402
+ angle, pivot = float(np.median(np.arctan2(top_edges[:, 1], top_edges[:, 0]))), polys.reshape(-1, 2).mean(0)
403
+ upright = _rotate(polys, -angle, pivot)
404
+ boxes = np.concatenate([upright.min(axis=1), upright.max(axis=1)], axis=1)
405
+ free, word_coords = np.flatnonzero(~taken), np.zeros((0, 4))
406
+ if free.size:
407
+ words = _rotate(as_polygons(word_boxes[free]) * scale, -angle, pivot)
408
+ centers = words.mean(axis=1)
409
+ inside = np.all((centers >= boxes[:, :2].min(axis=0)) & (centers <= boxes[:, 2:].max(axis=0)), axis=1)
410
+ free, words = free[inside], words[inside]
411
+ word_coords = np.concatenate([words.min(axis=1), words.max(axis=1)], axis=1)
412
+ boxes, logic, local_words, origin = fill_table_grid(boxes, logic, word_coords)
413
+ cell_words = [[int(free[j]) for j in idcs] for idcs in local_words]
414
+ corners = boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]]
415
+ polys = _rotate(corners, angle, pivot)
416
+ for idcs in cell_words:
417
+ taken[idcs] = True
418
+ out = []
419
+ for poly, (rs, re, cs, ce), idcs, source in zip(polys / scale, logic, cell_words, origin):
420
+ score = None if source < 0 else cells[source]["score"]
421
+ out.append({
422
+ "geometry": poly,
423
+ "score": None if score is None else float(score),
424
+ "row_start": int(rs),
425
+ "row_end": int(re),
426
+ "col_start": int(cs),
427
+ "col_end": int(ce),
428
+ "words": idcs,
429
+ })
430
+ return out, int(logic[:, 1].max()) + 1, int(logic[:, 3].max()) + 1
@@ -3,38 +3,89 @@
3
3
  # This program is licensed under the Apache License 2.0.
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
+ from collections.abc import Iterable, Sequence
6
7
  from typing import Any
7
8
 
9
+ import cv2
8
10
  import numpy as np
9
11
  import torch
10
12
  from torch import nn
11
13
 
14
+ from doctr.models._utils import predict_by_chunks
12
15
  from doctr.models.detection._utils import _remove_padding
13
16
  from doctr.models.preprocessor import PreProcessor
14
17
  from doctr.models.utils import set_device_and_dtype
15
18
 
19
+ from ..grid import as_polygons, fill_table_grid
20
+ from ..tablecenternet.base import _logic_from_geometry
21
+
16
22
  __all__ = ["TablePredictor"]
17
23
 
18
24
 
25
+ def _crop_region(page: np.ndarray, region: Any) -> tuple[np.ndarray, np.ndarray, int] | None:
26
+ """Rectify a page-relative table region to an upright crop with a margin of page context
27
+
28
+ Returns:
29
+ the crop, the page-to-crop perspective transform and the margin in pixels, or None for a degenerate region
30
+ """
31
+ h, w = page.shape[:2]
32
+ src = as_polygons([region])[0] * np.array([w, h], dtype=np.float32)
33
+ crop_w = int(round(max(np.linalg.norm(src[1] - src[0]), np.linalg.norm(src[2] - src[3]))))
34
+ crop_h = int(round(max(np.linalg.norm(src[3] - src[0]), np.linalg.norm(src[2] - src[1]))))
35
+ if crop_w < 2 or crop_h < 2:
36
+ return None
37
+ pad = max(20, round(0.01 * max(crop_w, crop_h)))
38
+ dst = np.array([[pad, pad], [pad + crop_w, pad], [pad + crop_w, pad + crop_h], [pad, pad + crop_h]], np.float32)
39
+ transform = cv2.getPerspectiveTransform(src, dst)
40
+ crop = cv2.warpPerspective(page, transform, (crop_w + 2 * pad, crop_h + 2 * pad), borderMode=cv2.BORDER_REPLICATE)
41
+ return crop, transform, pad
42
+
43
+
19
44
  class TablePredictor(nn.Module):
20
45
  """Implements an object able to recognize the cell structure of tables in a document.
21
46
 
22
47
  Args:
23
48
  pre_processor: transform inputs for easier batched model inference
24
49
  model: core table-structure-recognition architecture
50
+ chunk_size: the maximum number of table images decoded and processed at once (32 by default). Longer
51
+ inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
52
+ chunk by chunk, with a memory footprint that does not grow with the number of table images. It is rounded
53
+ up to a multiple of the batch size, so that the predictions are the same as in a single pass.
25
54
  """
26
55
 
27
56
  def __init__(
28
57
  self,
29
58
  pre_processor: PreProcessor,
30
59
  model: nn.Module,
60
+ chunk_size: int = 32,
31
61
  ) -> None:
32
62
  super().__init__()
33
63
  self.pre_processor = pre_processor
34
64
  self.model = model.eval()
65
+ if chunk_size < 1:
66
+ raise ValueError("`chunk_size` must be a positive integer")
67
+ self.chunk_size = chunk_size
35
68
 
36
69
  @torch.inference_mode()
37
- def forward(self, pages: list[np.ndarray], **kwargs: Any) -> list[dict[str, Any]]:
70
+ def forward(self, pages: Sequence[np.ndarray] | Iterable[np.ndarray], **kwargs: Any) -> list[dict[str, Any]]:
71
+ """Recognize the cell structure of table images
72
+
73
+ Args:
74
+ pages: a list of table images (numpy arrays of shape H x W x C), a lazy page source
75
+ (cf. `DocumentFile.from_images(..., lazy=True)`) or any iterable of images
76
+ **kwargs: keyword arguments forwarded to the model
77
+
78
+ Returns:
79
+ the structure of each table: `{"cells", "num_rows", "num_cols"}`
80
+ """
81
+ return predict_by_chunks(
82
+ lambda chunk: self._predict(chunk, **kwargs), pages, self.chunk_size, self.pre_processor.batch_size
83
+ )
84
+
85
+ @torch.inference_mode()
86
+ def _predict(self, pages: list[np.ndarray], **kwargs: Any) -> list[dict[str, Any]]:
87
+ if len(pages) == 0:
88
+ return []
38
89
  # Extract parameters from the preprocessor
39
90
  preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
40
91
  symmetric_pad = self.pre_processor.resize.symmetric_pad
@@ -78,3 +129,103 @@ class TablePredictor(nn.Module):
78
129
  # logical coordinates are 0-indexed, so the table size is the largest index + 1 (0 if no cells)
79
130
  results.append({"cells": cells, "num_rows": max_row + 1, "num_cols": max_col + 1})
80
131
  return results
132
+
133
+ @torch.inference_mode()
134
+ def predict_regions(
135
+ self,
136
+ pages: list[np.ndarray],
137
+ regions: list[dict[str, Any] | None],
138
+ word_boxes: list[np.ndarray] | None = None,
139
+ class_name: str = "Table",
140
+ **kwargs: Any,
141
+ ) -> list[list[dict[str, Any]]]:
142
+ """Recognize the tables a layout model located on pages, and assign the words of the pages to their cells
143
+
144
+ Each table region (straight box or polygon) is rectified to an upright crop, and the words lying in it are
145
+ assigned to the cells and complete the grid (cf. :func:`~doctr.models.table_structure.grid.fill_table_grid`).
146
+
147
+ Args:
148
+ pages: the page images
149
+ regions: the per-page layout predictions `{"class_names", "boxes", "scores"}` (None for none)
150
+ word_boxes: the per-page word boxes, of shape (N, 4) or (N, 4, 2) in relative coordinates
151
+ class_name: the layout class of the table regions
152
+ **kwargs: keyword arguments forwarded to the model
153
+
154
+ Returns:
155
+ a per-page list of tables `{"cells": [...], "num_rows": int, "num_cols": int}` in page-relative
156
+ coordinates, each cell listing the page indices of its words in reading order (`"words"`)
157
+ """
158
+ crops, meta = [], []
159
+ for p_idx, (page, region) in enumerate(zip(pages, regions)):
160
+ region = region or {}
161
+ for cls_name, box in zip(region.get("class_names", []), region.get("boxes", [])):
162
+ cropped = _crop_region(page, box) if cls_name == class_name else None
163
+ if cropped is not None:
164
+ crops.append(cropped[0])
165
+ meta.append((p_idx, cropped[1], cropped[2]))
166
+ tables: list[list[dict[str, Any]]] = [[] for _ in pages]
167
+ for (p_idx, transform, pad), crop, grid in zip(meta, crops, self(crops, **kwargs) if crops else []):
168
+ words = None if word_boxes is None else word_boxes[p_idx]
169
+ table = self._region_table(grid, crop.shape[:2], pages[p_idx].shape[:2], transform, pad, words)
170
+ if table is not None:
171
+ tables[p_idx].append(table)
172
+ return tables
173
+
174
+ def _region_table(
175
+ self,
176
+ grid: dict[str, Any],
177
+ crop_shape: tuple[int, int],
178
+ page_shape: tuple[int, int],
179
+ transform: np.ndarray,
180
+ pad: int,
181
+ word_boxes: np.ndarray | None,
182
+ ) -> dict[str, Any] | None:
183
+ """Assemble the table of a region crop with the words of the page, in page-relative coordinates"""
184
+ (crop_h, crop_w), (h, w) = crop_shape, page_shape
185
+ if len(grid["cells"]) == 0:
186
+ return None
187
+
188
+ def in_region(points: np.ndarray) -> np.ndarray:
189
+ return np.flatnonzero(np.all((points >= pad) & (points <= [crop_w - pad, crop_h - pad]), axis=1))
190
+
191
+ # Cells in crop pixels; the ones centered in the context margin belong to the neighbouring content
192
+ polys = as_polygons([cell["geometry"] for cell in grid["cells"]]) * [crop_w, crop_h]
193
+ keep = in_region(polys.mean(axis=1))
194
+ if keep.size == 0:
195
+ return None
196
+ polys, cells = polys[keep], [grid["cells"][idx] for idx in keep]
197
+ logic = np.array([[c["row_start"], c["row_end"], c["col_start"], c["col_end"]] for c in cells])
198
+ geometric_logic = getattr(getattr(self.model, "postprocessor", None), "geometric_logic", False)
199
+ if geometric_logic:
200
+ # Index the rows / columns from the cell edges (TableCenterNet logic is ordered columns first)
201
+ by_col = _logic_from_geometry(polys, logic[:, [2, 3, 0, 1]])
202
+ logic = by_col[:, [2, 3, 0, 1]]
203
+ # Words of the region, in crop pixels
204
+ word_idcs, words = np.zeros(0, dtype=np.int64), np.zeros((0, 4))
205
+ if word_boxes is not None and len(word_boxes) > 0:
206
+ pts = as_polygons(word_boxes) * np.array([w, h], dtype=np.float32)
207
+ pts = cv2.perspectiveTransform(pts.reshape(1, -1, 2), transform).reshape(-1, 4, 2)
208
+ word_idcs = in_region(pts.mean(axis=1))
209
+ words = np.concatenate([pts[word_idcs].min(axis=1), pts[word_idcs].max(axis=1)], axis=1)
210
+ boxes, cell_logic, cell_words, origin = fill_table_grid(
211
+ np.concatenate([polys.min(axis=1), polys.max(axis=1)], axis=1), logic, words
212
+ )
213
+ # Crop pixels -> page-relative coordinates
214
+ corners = boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]].reshape(1, -1, 2).astype(np.float32)
215
+ page_polys = cv2.perspectiveTransform(corners, np.linalg.inv(transform)).reshape(-1, 4, 2) / [w, h]
216
+ return {
217
+ "cells": [
218
+ {
219
+ "geometry": poly.tolist(),
220
+ "score": None if source < 0 else float(cells[source]["score"]), # None for a cell made from words
221
+ "row_start": int(rs),
222
+ "row_end": int(re),
223
+ "col_start": int(cs),
224
+ "col_end": int(ce),
225
+ "words": [int(word_idcs[idx]) for idx in w_idcs],
226
+ }
227
+ for poly, (rs, re, cs, ce), w_idcs, source in zip(page_polys, cell_logic, cell_words, origin)
228
+ ],
229
+ "num_rows": int(cell_logic[:, 1].max()) + 1,
230
+ "num_cols": int(cell_logic[:, 3].max()) + 1,
231
+ }