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.
- doctr/cli/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
|
@@ -71,6 +71,165 @@ def _bbox_overlap_query(center_polys: np.ndarray, corner_polys: np.ndarray) -> l
|
|
|
71
71
|
return out
|
|
72
72
|
|
|
73
73
|
|
|
74
|
+
def _deskew_cells(polys: np.ndarray) -> np.ndarray:
|
|
75
|
+
"""Rotate (N, 4, 2) cell quadrilaterals so the rows and columns of the table become horizontal and vertical.
|
|
76
|
+
|
|
77
|
+
The angle is the mean direction of the cell top edges modulo 90 degrees: the corner order of the cells (and a
|
|
78
|
+
rotation of the table by a multiple of 90 degrees) does not matter, the axes are matched in `_logic_from_geometry`.
|
|
79
|
+
"""
|
|
80
|
+
top_edges = polys[:, 1] - polys[:, 0]
|
|
81
|
+
theta = np.arctan2(top_edges[:, 1], top_edges[:, 0])
|
|
82
|
+
angle = float(np.arctan2(np.sin(4 * theta).mean(), np.cos(4 * theta).mean()) / 4)
|
|
83
|
+
cos_a, sin_a = math.cos(-angle), math.sin(-angle)
|
|
84
|
+
pts = polys.reshape(-1, 2) - polys.reshape(-1, 2).mean(axis=0)
|
|
85
|
+
rotated = np.stack([pts[:, 0] * cos_a - pts[:, 1] * sin_a, pts[:, 0] * sin_a + pts[:, 1] * cos_a], axis=1)
|
|
86
|
+
return rotated.reshape(polys.shape)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _cell_edges(polys: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
90
|
+
"""Left, right, top and bottom edges of deskewed (N, 4, 2) cells."""
|
|
91
|
+
return polys[..., 0].min(axis=1), polys[..., 0].max(axis=1), polys[..., 1].min(axis=1), polys[..., 1].max(axis=1)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _suppress_overlapping_cells(polys: np.ndarray, scores: np.ndarray, thresh: float = 0.7) -> np.ndarray:
|
|
95
|
+
"""Indices of the cells to keep (by decreasing score) once the duplicates are removed.
|
|
96
|
+
|
|
97
|
+
The cells of a table do not overlap: a cell covering more than `thresh` of a cell with a higher score, or the
|
|
98
|
+
other way around, is a duplicate detection of the same cell.
|
|
99
|
+
"""
|
|
100
|
+
left, right, top, bottom = _cell_edges(_deskew_cells(polys))
|
|
101
|
+
areas = np.maximum(right - left, 0) * np.maximum(bottom - top, 0)
|
|
102
|
+
keep: list[int] = []
|
|
103
|
+
for i in np.argsort(-scores, kind="stable"):
|
|
104
|
+
if keep:
|
|
105
|
+
k = np.asarray(keep)
|
|
106
|
+
inter_w = np.minimum(right[i], right[k]) - np.maximum(left[i], left[k])
|
|
107
|
+
inter_h = np.minimum(bottom[i], bottom[k]) - np.maximum(top[i], top[k])
|
|
108
|
+
inter = np.maximum(inter_w, 0) * np.maximum(inter_h, 0)
|
|
109
|
+
if np.any(inter > thresh * np.maximum(np.minimum(areas[i], areas[k]), 1e-9)):
|
|
110
|
+
continue
|
|
111
|
+
keep.append(int(i))
|
|
112
|
+
return np.asarray(keep, dtype=np.int64)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _cluster_lines(values: np.ndarray, tol: float) -> np.ndarray:
|
|
116
|
+
"""Group 1D cell-edge positions into the sorted positions of the grid lines.
|
|
117
|
+
|
|
118
|
+
The positions shared by the most edges become lines first, and absorb every edge closer than `tol`: unlike a
|
|
119
|
+
single-linkage grouping, a few stray edges between two lines can not chain them into a single one. An isolated
|
|
120
|
+
edge (shared by no other edge) only makes a line of its own when no line lies within `1.5 * tol`.
|
|
121
|
+
"""
|
|
122
|
+
values = np.sort(values)
|
|
123
|
+
half = tol / 2
|
|
124
|
+
|
|
125
|
+
def window(lo: np.ndarray | float, hi: np.ndarray | float):
|
|
126
|
+
return np.searchsorted(values, lo, "left"), np.searchsorted(values, hi, "right")
|
|
127
|
+
|
|
128
|
+
lo, hi = window(values - half, values + half)
|
|
129
|
+
support = hi - lo # number of edges around each edge (itself included)
|
|
130
|
+
taken = np.zeros(values.size, dtype=bool)
|
|
131
|
+
lines: list[float] = []
|
|
132
|
+
order = np.argsort(-support, kind="stable")
|
|
133
|
+
# 1st pass: the lines shared by several edges, 2nd pass: the isolated edges
|
|
134
|
+
for shared in (True, False):
|
|
135
|
+
for i in order:
|
|
136
|
+
if taken[i] or (shared and support[i] < 2):
|
|
137
|
+
continue
|
|
138
|
+
if not shared and lines and np.min(np.abs(np.asarray(lines) - values[i])) <= 1.5 * tol:
|
|
139
|
+
taken[i] = True # a stray edge of a cell, close to an existing line
|
|
140
|
+
continue
|
|
141
|
+
near = values[lo[i] : hi[i]][~taken[lo[i] : hi[i]]]
|
|
142
|
+
center = float(np.median(near))
|
|
143
|
+
start, end = window(center - tol, center + tol)
|
|
144
|
+
taken[start:end] = True
|
|
145
|
+
taken[i] = True
|
|
146
|
+
lines.append(center)
|
|
147
|
+
return np.sort(np.asarray(lines))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _index_lines(lines: np.ndarray, start: np.ndarray, end: np.ndarray, cell_size: float) -> np.ndarray:
|
|
151
|
+
"""Logical index of each grid line of an axis, from the cells lying between the lines.
|
|
152
|
+
|
|
153
|
+
Every cell spans at least one index, and the lines no cell separates share an index. A gap covered by no cell
|
|
154
|
+
counts as many indices as cells of the typical size fit in it.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
lines: the sorted positions of the grid lines, shape (L,)
|
|
158
|
+
start: index of the line each cell starts on, shape (N,)
|
|
159
|
+
end: index of the line each cell ends on (after its start line), shape (N,)
|
|
160
|
+
cell_size: the typical size of a cell along the axis
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
the (non-decreasing) logical index of each line, shape (L,)
|
|
164
|
+
"""
|
|
165
|
+
values = np.zeros(lines.size, dtype=np.int64)
|
|
166
|
+
for k in range(1, lines.size):
|
|
167
|
+
value = values[k - 1]
|
|
168
|
+
if not np.any((start <= k - 1) & (end >= k)): # no cell covers the gap between the 2 lines
|
|
169
|
+
value += int(round((lines[k] - lines[k - 1]) / max(cell_size, 1e-9)))
|
|
170
|
+
ending = start[end == k]
|
|
171
|
+
values[k] = max(value, int(values[ending].max()) + 1) if ending.size else value
|
|
172
|
+
return values
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _align_table_logic(edges: tuple[np.ndarray, ...], logic: np.ndarray) -> np.ndarray:
|
|
176
|
+
"""Align the (N, 4) logical coordinates of the cells of a table on their deskewed edges."""
|
|
177
|
+
left, right, top, bottom = edges
|
|
178
|
+
logic = logic.copy()
|
|
179
|
+
# The table may be rotated by any multiple of 90 degrees (or the corners ordered by the image axes): match each
|
|
180
|
+
# logical axis (columns, rows) with the geometric axis and direction its model coordinates follow
|
|
181
|
+
geo_axes = [(left, right), (top, bottom)]
|
|
182
|
+
corr = np.zeros((2, 2))
|
|
183
|
+
for g, (lo, hi) in enumerate(geo_axes):
|
|
184
|
+
for a, offset in enumerate((0, 2)):
|
|
185
|
+
pos, idx = lo + hi, logic[:, offset] + logic[:, offset + 1]
|
|
186
|
+
if pos.std() > 0 and idx.std() > 0:
|
|
187
|
+
corr[g, a] = float(np.corrcoef(pos, idx)[0, 1])
|
|
188
|
+
swap = abs(corr[1, 0]) + abs(corr[0, 1]) > abs(corr[0, 0]) + abs(corr[1, 1])
|
|
189
|
+
for a, offset in enumerate((0, 2)):
|
|
190
|
+
g = 1 - a if swap else a
|
|
191
|
+
start_edge, end_edge = geo_axes[g]
|
|
192
|
+
if corr[g, a] < 0: # the logical indices grow against the geometric axis
|
|
193
|
+
start_edge, end_edge = -end_edge, -start_edge
|
|
194
|
+
# Tolerance on the alignment of the edges, from the narrowest cells along this axis: merging the 2 lines of a
|
|
195
|
+
# narrow row / column would lose it, while the lines split from a line that no cell separates share an index
|
|
196
|
+
tol = max(0.4 * float(np.percentile(end_edge - start_edge, 10)), 1e-6)
|
|
197
|
+
lines = _cluster_lines(np.concatenate([start_edge, end_edge]), tol)
|
|
198
|
+
if lines.size < 2: # degenerate (flat) cells: nothing to align
|
|
199
|
+
continue
|
|
200
|
+
# Index of the line each cell starts / ends on (a cell spans at least one row / column)
|
|
201
|
+
start = np.abs(start_edge[:, None] - lines[None]).argmin(axis=1)
|
|
202
|
+
end = np.abs(end_edge[:, None] - lines[None]).argmin(axis=1)
|
|
203
|
+
end = np.clip(end, 1, lines.size - 1)
|
|
204
|
+
start = np.minimum(start, end - 1)
|
|
205
|
+
values = _index_lines(lines, start, end, float(np.median(end_edge - start_edge)))
|
|
206
|
+
# Keep the absolute position the model predicts for most of the cells
|
|
207
|
+
values += max(int(round(float(np.median(logic[:, offset] - values[start])))), 0)
|
|
208
|
+
logic[:, offset] = values[start]
|
|
209
|
+
logic[:, offset + 1] = values[end] - 1
|
|
210
|
+
return logic
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _logic_from_geometry(polys: np.ndarray, model_logic: np.ndarray) -> np.ndarray:
|
|
214
|
+
"""Make the logical coordinates `[start_col, end_col, start_row, end_row]` (0-indexed) of the (N, 4, 2) cells of a
|
|
215
|
+
table consistent with their geometry.
|
|
216
|
+
|
|
217
|
+
The cell edges are grouped into the row and column lines of the grid, indexed from the geometry (cf.
|
|
218
|
+
`_index_lines`). The model coordinates only give the direction of the axes and the absolute position of the table.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
polys: the cells, of shape (N, 4, 2)
|
|
222
|
+
model_logic: the logical coordinates predicted by the model, of shape (N, 4)
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
the logical coordinates, of shape (N, 4)
|
|
226
|
+
"""
|
|
227
|
+
logic = np.asarray(model_logic, dtype=np.int64)
|
|
228
|
+
if logic.shape[0] == 0:
|
|
229
|
+
return logic.copy()
|
|
230
|
+
return _align_table_logic(_cell_edges(_deskew_cells(polys)), logic)
|
|
231
|
+
|
|
232
|
+
|
|
74
233
|
def _lookup_logic(lc_map: np.ndarray, x: float, y: float) -> np.ndarray:
|
|
75
234
|
"""Sample the (2, H, W) logical-coordinate map at a clamped pixel location."""
|
|
76
235
|
h, w = lc_map.shape[1:]
|
|
@@ -92,6 +251,8 @@ class TableCenterNetPostProcessor:
|
|
|
92
251
|
corner_thresh: minimum score for a corner to be used during relocation
|
|
93
252
|
not_relocate: if True, skip the corner-relocation step (faster, less accurate)
|
|
94
253
|
assume_straight_pages: whether the pages are assumed to be straight (i.e., no rotation)
|
|
254
|
+
geometric_logic: if True, remove the duplicate (overlapping) cells. `TablePredictor.predict_regions` then
|
|
255
|
+
indexes the rows and columns from the cell edges instead of the logical coordinates of the model
|
|
95
256
|
"""
|
|
96
257
|
|
|
97
258
|
def __init__(
|
|
@@ -100,11 +261,13 @@ class TableCenterNetPostProcessor:
|
|
|
100
261
|
corner_thresh: float = 0.3,
|
|
101
262
|
not_relocate: bool = False,
|
|
102
263
|
assume_straight_pages: bool = True,
|
|
264
|
+
geometric_logic: bool = True,
|
|
103
265
|
) -> None:
|
|
104
266
|
self.center_thresh = center_thresh
|
|
105
267
|
self.corner_thresh = corner_thresh
|
|
106
268
|
self.not_relocate = not_relocate
|
|
107
269
|
self.assume_straight_pages = assume_straight_pages
|
|
270
|
+
self.geometric_logic = geometric_logic
|
|
108
271
|
# Cell score decay: cells optimised on <= 2 corners get their score scaled.
|
|
109
272
|
self.cell_min_optimize_count = 2
|
|
110
273
|
self.cell_decay_thresh = 0.4
|
|
@@ -190,6 +353,12 @@ class TableCenterNetPostProcessor:
|
|
|
190
353
|
keep = cs >= self.center_thresh
|
|
191
354
|
polys = cp[keep].reshape(-1, 4, 2) / scale # relative coordinates
|
|
192
355
|
polys = np.clip(polys.astype(np.float32), 0, 1)
|
|
356
|
+
scores = cs[keep].astype(np.float32)
|
|
357
|
+
logic = (logic[keep] - 1).astype(np.int32) # start_col, end_col, start_row, end_row (0-indexed)
|
|
358
|
+
if self.geometric_logic and polys.shape[0] > 0:
|
|
359
|
+
# The logical coordinates stay the model's: `TablePredictor._region_table` indexes them from geometry
|
|
360
|
+
kept = _suppress_overlapping_cells(polys, scores)
|
|
361
|
+
polys, scores, logic = polys[kept], scores[kept], logic[kept]
|
|
193
362
|
if self.assume_straight_pages:
|
|
194
363
|
cells = np.concatenate([polys.min(axis=1), polys.max(axis=1)], axis=1).astype(np.float32)
|
|
195
364
|
else:
|
|
@@ -200,8 +369,8 @@ class TableCenterNetPostProcessor:
|
|
|
200
369
|
)
|
|
201
370
|
results.append({
|
|
202
371
|
"polygons": cells, # (N, 4) boxes or (N, 4, 2) quads in relative coordinates
|
|
203
|
-
"scores":
|
|
204
|
-
"logical":
|
|
372
|
+
"scores": scores,
|
|
373
|
+
"logical": logic, # start_col, end_col, start_row, end_row (0-indexed)
|
|
205
374
|
})
|
|
206
375
|
return results
|
|
207
376
|
|
|
@@ -296,8 +465,8 @@ def _build_table_target(
|
|
|
296
465
|
cells: np.ndarray,
|
|
297
466
|
logic: np.ndarray,
|
|
298
467
|
output_size: tuple[int, int],
|
|
299
|
-
max_objects: int =
|
|
300
|
-
max_corners: int =
|
|
468
|
+
max_objects: int = 3000,
|
|
469
|
+
max_corners: int = 12000,
|
|
301
470
|
) -> dict[str, np.ndarray]:
|
|
302
471
|
"""Render the dense TableCenterNet targets (for a single image) consumed by `TableCenterNet.compute_loss`.
|
|
303
472
|
|
|
@@ -313,11 +482,12 @@ def _build_table_target(
|
|
|
313
482
|
"""
|
|
314
483
|
out_h, out_w = output_size
|
|
315
484
|
hm = np.zeros((2, out_h, out_w), np.float32)
|
|
316
|
-
|
|
485
|
+
# Center offsets live in the first `max_objects` slots, corner offsets right after them
|
|
486
|
+
reg = np.zeros((max_objects + max_corners, 2), np.float32)
|
|
317
487
|
ct2cn = np.zeros((max_objects, 8), np.float32)
|
|
318
488
|
cn2ct = np.zeros((max_corners, 8), np.float32)
|
|
319
|
-
reg_ind = np.zeros((max_objects
|
|
320
|
-
reg_mask = np.zeros((max_objects
|
|
489
|
+
reg_ind = np.zeros((max_objects + max_corners,), np.int64)
|
|
490
|
+
reg_mask = np.zeros((max_objects + max_corners,), np.float32)
|
|
321
491
|
ct_ind = np.zeros((max_objects,), np.int64)
|
|
322
492
|
ct_mask = np.zeros((max_objects,), np.float32)
|
|
323
493
|
cn_ind = np.zeros((max_corners,), np.int64)
|
|
@@ -327,9 +497,13 @@ def _build_table_target(
|
|
|
327
497
|
lc_span = np.zeros((max_objects, 2), np.float32)
|
|
328
498
|
|
|
329
499
|
corner_dict: dict[str, int] = {}
|
|
500
|
+
drawn_corners: set[str] = set()
|
|
330
501
|
cells_logic_coords: list = []
|
|
331
502
|
|
|
332
|
-
|
|
503
|
+
# Every cell is drawn on the heat-maps and the logical map, even beyond `max_objects`: otherwise the
|
|
504
|
+
# extra cells are trained as background and the model learns to stop detecting after ~max_objects cells.
|
|
505
|
+
for i in range(len(cells)):
|
|
506
|
+
slotted = i < max_objects # whether this cell also gets regression targets
|
|
333
507
|
corners = cells[i].reshape(8).astype(np.float32).copy()
|
|
334
508
|
corners[0::2] = np.clip(corners[0::2], 0, out_w - 1)
|
|
335
509
|
corners[1::2] = np.clip(corners[1::2], 0, out_h - 1)
|
|
@@ -345,11 +519,12 @@ def _build_table_target(
|
|
|
345
519
|
center = np.array([(max_x + min_x) / 2.0, (max_y + min_y) / 2.0], np.float32)
|
|
346
520
|
ci = center.astype(np.int32)
|
|
347
521
|
flat = ci[1] * out_w + ci[0]
|
|
348
|
-
reg[i] = center - ci
|
|
349
|
-
reg_ind[i], reg_mask[i] = flat, 1
|
|
350
|
-
ct_ind[i], ct_mask[i] = flat, 1
|
|
351
522
|
_draw_umich_gaussian(hm[0], ci, radius)
|
|
352
|
-
|
|
523
|
+
if slotted:
|
|
524
|
+
reg[i] = center - ci
|
|
525
|
+
reg_ind[i], reg_mask[i] = flat, 1
|
|
526
|
+
ct_ind[i], ct_mask[i] = flat, 1
|
|
527
|
+
ct2cn[i] = center[[0, 1, 0, 1, 0, 1, 0, 1]] - corners
|
|
353
528
|
|
|
354
529
|
start_col, end_col, start_row, end_row = (int(v) + 1 for v in logic[i])
|
|
355
530
|
x1, y1, x2, y2, x3, y3, x4, y4 = corners.tolist()
|
|
@@ -360,6 +535,15 @@ def _build_table_target(
|
|
|
360
535
|
(x4, y4, start_col, end_row + 1),
|
|
361
536
|
]
|
|
362
537
|
cells_logic_coords.append(clc)
|
|
538
|
+
if not slotted:
|
|
539
|
+
# Heat-map only for the corners of the cells beyond `max_objects`
|
|
540
|
+
for j in range(4):
|
|
541
|
+
cint = corners[j * 2 : j * 2 + 2].astype(np.int32)
|
|
542
|
+
key = f"{cint[0]}_{cint[1]}"
|
|
543
|
+
if key not in drawn_corners:
|
|
544
|
+
drawn_corners.add(key)
|
|
545
|
+
_draw_umich_gaussian(hm[1], cint, 2)
|
|
546
|
+
continue
|
|
363
547
|
for j, (x, y, _c, _r) in enumerate(clc):
|
|
364
548
|
lc_ind[i, j] = int(y) * out_w + int(x)
|
|
365
549
|
lc_span[i] = (end_col - start_col + 1, end_row - start_row + 1)
|
|
@@ -372,14 +556,20 @@ def _build_table_target(
|
|
|
372
556
|
if key not in corner_dict:
|
|
373
557
|
nc = len(corner_dict)
|
|
374
558
|
if nc >= max_corners:
|
|
375
|
-
|
|
559
|
+
# No regression slot left: still draw the corner so it is not trained as background
|
|
560
|
+
if key not in drawn_corners:
|
|
561
|
+
drawn_corners.add(key)
|
|
562
|
+
_draw_umich_gaussian(hm[1], cint, 2)
|
|
563
|
+
continue
|
|
376
564
|
corner_dict[key] = nc
|
|
377
565
|
reg[max_objects + nc] = np.abs(corner - cint)
|
|
378
566
|
reg_ind[max_objects + nc] = cint[1] * out_w + cint[0]
|
|
379
567
|
reg_mask[max_objects + nc] = 1
|
|
380
568
|
cn_ind[nc] = cint[1] * out_w + cint[0]
|
|
381
569
|
cn_mask[nc] = 1
|
|
382
|
-
|
|
570
|
+
if key not in drawn_corners:
|
|
571
|
+
drawn_corners.add(key)
|
|
572
|
+
_draw_umich_gaussian(hm[1], cint, 2)
|
|
383
573
|
cn2ct[nc][si : si + 2] = corner - center
|
|
384
574
|
ct_cn_ind[4 * i + j] = nc * 4 + j
|
|
385
575
|
else:
|
|
@@ -441,8 +631,8 @@ class _TableCenterNet(BaseModel):
|
|
|
441
631
|
by `compute_loss` are produced here, while `TableCenterNetPostProcessor` decodes the model output.
|
|
442
632
|
"""
|
|
443
633
|
|
|
444
|
-
max_objects: int =
|
|
445
|
-
max_corners: int =
|
|
634
|
+
max_objects: int = 3000
|
|
635
|
+
max_corners: int = 12000
|
|
446
636
|
assume_straight_pages: bool = False
|
|
447
637
|
|
|
448
638
|
def build_target(
|
|
@@ -26,7 +26,7 @@ default_cfgs: dict[str, dict[str, Any]] = {
|
|
|
26
26
|
"input_shape": (3, 1024, 1024),
|
|
27
27
|
"mean": (0.798, 0.785, 0.772),
|
|
28
28
|
"std": (0.264, 0.2749, 0.287),
|
|
29
|
-
"url": "https://github.com/mindee/doctr/releases/download/v1.0
|
|
29
|
+
"url": "https://github.com/mindee/doctr/releases/download/v1.1.0/tablecenternet-b0d6f603.pt",
|
|
30
30
|
},
|
|
31
31
|
}
|
|
32
32
|
|
|
@@ -149,6 +149,7 @@ class TableCenterNet(nn.Module, _TableCenterNet):
|
|
|
149
149
|
center_k: maximum number of cell centers
|
|
150
150
|
corner_k: maximum number of corners
|
|
151
151
|
not_relocate: if True, skip the corner-relocation step
|
|
152
|
+
geometric_logic: if True, remove the duplicate cells (cf. `TableCenterNetPostProcessor`)
|
|
152
153
|
assume_straight_pages: if True, the predictor will fit straight boxes to the cells
|
|
153
154
|
exportable: onnx exportable returns only the raw head maps
|
|
154
155
|
cfg: the configuration dict of the model
|
|
@@ -163,11 +164,12 @@ class TableCenterNet(nn.Module, _TableCenterNet):
|
|
|
163
164
|
last_level: int = 4,
|
|
164
165
|
center_thresh: float = 0.3,
|
|
165
166
|
corner_thresh: float = 0.3,
|
|
166
|
-
center_k: int =
|
|
167
|
-
corner_k: int =
|
|
167
|
+
center_k: int = 10000,
|
|
168
|
+
corner_k: int = 12000,
|
|
168
169
|
not_relocate: bool = False,
|
|
169
|
-
|
|
170
|
-
|
|
170
|
+
geometric_logic: bool = True,
|
|
171
|
+
max_objects: int = 3000,
|
|
172
|
+
max_corners: int = 12000,
|
|
171
173
|
assume_straight_pages: bool = True,
|
|
172
174
|
exportable: bool = False,
|
|
173
175
|
cfg: dict[str, Any] | None = None,
|
|
@@ -213,6 +215,7 @@ class TableCenterNet(nn.Module, _TableCenterNet):
|
|
|
213
215
|
center_thresh=center_thresh,
|
|
214
216
|
corner_thresh=corner_thresh,
|
|
215
217
|
not_relocate=not_relocate,
|
|
218
|
+
geometric_logic=geometric_logic,
|
|
216
219
|
assume_straight_pages=self.assume_straight_pages,
|
|
217
220
|
)
|
|
218
221
|
|
|
@@ -27,6 +27,7 @@ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = False,
|
|
|
27
27
|
raise ValueError(f"unknown architecture: {type(arch)}")
|
|
28
28
|
_model = arch
|
|
29
29
|
_model.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
|
|
30
|
+
_model.postprocessor.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
|
|
30
31
|
|
|
31
32
|
kwargs.pop("pretrained_backbone", None)
|
|
32
33
|
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
@@ -34,9 +35,11 @@ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = False,
|
|
|
34
35
|
kwargs["batch_size"] = kwargs.get("batch_size", 2)
|
|
35
36
|
kwargs.setdefault("preserve_aspect_ratio", True)
|
|
36
37
|
kwargs.setdefault("symmetric_pad", True)
|
|
38
|
+
chunk_size = kwargs.pop("chunk_size", 32)
|
|
37
39
|
predictor = TablePredictor(
|
|
38
40
|
PreProcessor(_model.cfg["input_shape"][1:], **kwargs),
|
|
39
41
|
_model,
|
|
42
|
+
chunk_size=chunk_size,
|
|
40
43
|
)
|
|
41
44
|
return predictor
|
|
42
45
|
|
|
@@ -66,6 +69,8 @@ def table_predictor(
|
|
|
66
69
|
running the model on it
|
|
67
70
|
symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
|
|
68
71
|
batch_size: number of samples the model processes in parallel
|
|
72
|
+
chunk_size: maximum number of table images decoded and processed at once (32 by default): longer inputs and
|
|
73
|
+
lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
|
|
69
74
|
**kwargs: optional keyword arguments passed to the architecture
|
|
70
75
|
|
|
71
76
|
Returns:
|
doctr/models/utils/pytorch.py
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import logging
|
|
7
7
|
from collections.abc import Iterable
|
|
8
|
+
from contextlib import nullcontext
|
|
8
9
|
from typing import Any
|
|
9
10
|
|
|
10
11
|
import torch
|
|
@@ -12,6 +13,7 @@ import validators
|
|
|
12
13
|
from anyascii import anyascii
|
|
13
14
|
from torch import nn
|
|
14
15
|
|
|
16
|
+
from doctr.file_utils import requires_package
|
|
15
17
|
from doctr.utils.data import download_from_url
|
|
16
18
|
|
|
17
19
|
__all__ = [
|
|
@@ -70,7 +72,7 @@ def load_pretrained_params(
|
|
|
70
72
|
)
|
|
71
73
|
|
|
72
74
|
# Read state_dict
|
|
73
|
-
state_dict = torch.load(archive_path, map_location="cpu")
|
|
75
|
+
state_dict = torch.load(archive_path, map_location="cpu", weights_only=True)
|
|
74
76
|
|
|
75
77
|
# Remove weights from the state_dict
|
|
76
78
|
if ignore_keys is not None and len(ignore_keys) > 0:
|
|
@@ -93,7 +95,7 @@ def conv_sequence_pt(
|
|
|
93
95
|
out_channels: int,
|
|
94
96
|
act: bool = False,
|
|
95
97
|
bn: bool = False,
|
|
96
|
-
activation: nn.Module =
|
|
98
|
+
activation: nn.Module | None = None,
|
|
97
99
|
**kwargs: Any,
|
|
98
100
|
) -> list[nn.Module]:
|
|
99
101
|
"""Builds a convolutional-based layer sequence
|
|
@@ -107,7 +109,9 @@ def conv_sequence_pt(
|
|
|
107
109
|
out_channels: number of output channels
|
|
108
110
|
act: should an activation layer be added
|
|
109
111
|
bn: should a batch normalization layer be added
|
|
110
|
-
activation: the activation layer to be added if act is True
|
|
112
|
+
activation: the activation layer to be added if act is True. Defaults to a new ``nn.ReLU(inplace=True)``
|
|
113
|
+
per call. When passing one, use a new instance per call: a module shared between layers is kept only
|
|
114
|
+
once by ``named_children`` (e.g. in ``IntermediateLayerGetter``)
|
|
111
115
|
**kwargs: additional arguments to be passed to the convolutional layer
|
|
112
116
|
|
|
113
117
|
Returns:
|
|
@@ -122,7 +126,9 @@ def conv_sequence_pt(
|
|
|
122
126
|
conv_seq.append(nn.BatchNorm2d(out_channels))
|
|
123
127
|
|
|
124
128
|
if act:
|
|
125
|
-
|
|
129
|
+
# A new module per call: a default ``nn.ReLU`` instance would be shared by every layer, and modules
|
|
130
|
+
# that appear twice in a model are kept once by ``named_children`` (e.g. in ``IntermediateLayerGetter``).
|
|
131
|
+
conv_seq.append(nn.ReLU(inplace=True) if activation is None else activation)
|
|
126
132
|
|
|
127
133
|
return conv_seq
|
|
128
134
|
|
|
@@ -169,6 +175,7 @@ def export_model_to_onnx(
|
|
|
169
175
|
input_names: list[str] | None = None,
|
|
170
176
|
output_names: list[str] | None = None,
|
|
171
177
|
dynamic_axes: dict[str, dict[int, str]] | None = None,
|
|
178
|
+
dynamo: bool = False,
|
|
172
179
|
**kwargs: Any,
|
|
173
180
|
) -> str:
|
|
174
181
|
"""Export model to ONNX format.
|
|
@@ -189,6 +196,11 @@ def export_model_to_onnx(
|
|
|
189
196
|
`["logits", "pred_boxes"]` when `dummy_input` is a tuple). Pass the names of every output when
|
|
190
197
|
the model returns more than one tensor (e.g. a multi-head model).
|
|
191
198
|
dynamic_axes: optional dynamic axes. Defaults to a dynamic batch dimension on every input and output.
|
|
199
|
+
dynamo: whether to export with the `torch.export`-based exporter of PyTorch (requires `onnxscript`) instead of
|
|
200
|
+
the TorchScript-based one (default). Required for `formulanet`: its decoding is then exported as ONNX
|
|
201
|
+
`Loop` nodes, which stop once every formula of the batch is complete, instead of `max_decode_length`
|
|
202
|
+
unrolled steps. `parseq` and `master` are exported with such a loop as well. The model is saved as a
|
|
203
|
+
single file.
|
|
192
204
|
kwargs: additional arguments to be passed to torch.onnx.export
|
|
193
205
|
|
|
194
206
|
Returns:
|
|
@@ -202,22 +214,67 @@ def export_model_to_onnx(
|
|
|
202
214
|
if dynamic_axes is None:
|
|
203
215
|
dynamic_axes = {name: {0: "batch_size"} for name in [*input_names, *output_names]}
|
|
204
216
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
+
if dynamo:
|
|
218
|
+
requires_package("onnxscript", "`dynamo=True` requires onnxscript installed.")
|
|
219
|
+
# A single file, as with the TorchScript-based exporter (the weights are otherwise saved in a separate file)
|
|
220
|
+
kwargs.setdefault("external_data", False)
|
|
221
|
+
# torch.export specializes the dimensions of size 1 (e.g. a reshape would keep a batch size of 1): trace with a
|
|
222
|
+
# batch of 2 so that the batch dimension stays dynamic
|
|
223
|
+
if (dummy_input[0] if is_tuple else dummy_input).shape[0] == 1: # type: ignore[union-attr]
|
|
224
|
+
dummy_input = (
|
|
225
|
+
tuple(torch.cat([t, t]) for t in dummy_input) # type: ignore[assignment]
|
|
226
|
+
if is_tuple
|
|
227
|
+
else torch.cat([dummy_input, dummy_input]) # type: ignore[list-item]
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
# The TorchScript-based exporter otherwise traces with autograd: the same file, with up to twice the memory
|
|
231
|
+
with nullcontext() if dynamo else torch.no_grad():
|
|
232
|
+
torch.onnx.export(
|
|
233
|
+
model,
|
|
234
|
+
dummy_input, # type: ignore[arg-type]
|
|
235
|
+
f"{model_name}.onnx",
|
|
236
|
+
input_names=input_names,
|
|
237
|
+
output_names=output_names,
|
|
238
|
+
dynamic_axes=dynamic_axes,
|
|
239
|
+
export_params=True,
|
|
240
|
+
dynamo=dynamo,
|
|
241
|
+
verbose=False,
|
|
242
|
+
**kwargs,
|
|
243
|
+
)
|
|
244
|
+
if dynamo:
|
|
245
|
+
_strip_onnx_node_metadata(f"{model_name}.onnx")
|
|
217
246
|
logger.info(f"Model exported to {model_name}.onnx")
|
|
218
247
|
return f"{model_name}.onnx"
|
|
219
248
|
|
|
220
249
|
|
|
250
|
+
def _strip_onnx_node_metadata(path: str) -> None:
|
|
251
|
+
"""Remove the metadata the `torch.export`-based exporter attaches to every node (e.g. the Python stack trace that
|
|
252
|
+
created it, with the paths of the local files), which makes up most of the file for models with loops, and the
|
|
253
|
+
initializers no node uses (ONNX Runtime warns about them): neither has any effect on the inference"""
|
|
254
|
+
import onnx
|
|
255
|
+
|
|
256
|
+
used: set[str] = set()
|
|
257
|
+
|
|
258
|
+
def _strip(graph: onnx.GraphProto) -> None:
|
|
259
|
+
for node in graph.node:
|
|
260
|
+
del node.metadata_props[:]
|
|
261
|
+
used.update(node.input)
|
|
262
|
+
for attr in node.attribute:
|
|
263
|
+
if attr.type == onnx.AttributeProto.GRAPH:
|
|
264
|
+
_strip(attr.g)
|
|
265
|
+
elif attr.type == onnx.AttributeProto.GRAPHS:
|
|
266
|
+
for subgraph in attr.graphs:
|
|
267
|
+
_strip(subgraph)
|
|
268
|
+
|
|
269
|
+
model = onnx.load(path)
|
|
270
|
+
_strip(model.graph)
|
|
271
|
+
used.update(output.name for output in model.graph.output)
|
|
272
|
+
unused = [init for init in model.graph.initializer if init.name not in used]
|
|
273
|
+
for init in unused:
|
|
274
|
+
model.graph.initializer.remove(init)
|
|
275
|
+
onnx.save(model, path)
|
|
276
|
+
|
|
277
|
+
|
|
221
278
|
# Location of the final vocabulary-projection layer for each recognition architecture.
|
|
222
279
|
_RECOGNITION_PROJECTIONS: dict[str, str] = {
|
|
223
280
|
"CRNN": "linear",
|