python-doctr 1.0.1__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +669 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +14 -3
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +121 -37
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +9 -7
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +129 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +5 -4
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +10 -8
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +104 -21
- doctr/datasets/vocabs.py +320 -148
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +3 -0
- doctr/io/elements.py +381 -271
- doctr/io/exporters.py +1915 -0
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -7
- doctr/io/image/pytorch.py +13 -5
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +3 -0
- doctr/models/_utils.py +206 -13
- doctr/models/builder.py +590 -137
- doctr/models/classification/__init__.py +3 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +34 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- 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 +14 -2
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +32 -18
- doctr/models/detection/differentiable_binarization/base.py +23 -9
- doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
- doctr/models/detection/fast/base.py +22 -6
- doctr/models/detection/fast/pytorch.py +24 -11
- doctr/models/detection/linknet/base.py +22 -6
- doctr/models/detection/linknet/pytorch.py +10 -3
- doctr/models/detection/predictor/pytorch.py +43 -2
- doctr/models/detection/zoo.py +6 -2
- doctr/models/factory/hub.py +59 -41
- 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 +23 -1
- doctr/models/kie_predictor/pytorch.py +87 -15
- 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 +895 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +114 -0
- doctr/models/layout/zoo.py +94 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +415 -17
- doctr/models/predictor/pytorch.py +109 -12
- doctr/models/preprocessor/pytorch.py +82 -25
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +1127 -0
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +40 -16
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +84 -22
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +126 -25
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +68 -12
- doctr/models/recognition/sar/pytorch.py +21 -7
- doctr/models/recognition/utils.py +80 -50
- doctr/models/recognition/viptr/pytorch.py +38 -14
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +11 -7
- doctr/models/recognition/zoo.py +36 -9
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +231 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +675 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
- doctr/models/table_structure/zoo.py +87 -0
- doctr/models/utils/pytorch.py +381 -25
- doctr/models/zoo.py +141 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +261 -82
- doctr/transforms/modules/pytorch.py +396 -76
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +24 -11
- doctr/utils/fonts.py +64 -17
- doctr/utils/geometry.py +167 -28
- doctr/utils/metrics.py +481 -19
- doctr/utils/multithreading.py +127 -4
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +73 -10
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
- python_doctr-1.2.0.dist-info/RECORD +191 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
|
@@ -0,0 +1,675 @@
|
|
|
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
|
+
# Credits: decode logic ported from https://github.com/dreamy-xay/TableCenterNet
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from scipy.interpolate import griddata
|
|
12
|
+
from shapely import contains_xy, prepare
|
|
13
|
+
from shapely.geometry import Polygon
|
|
14
|
+
|
|
15
|
+
from doctr.models.core import BaseModel
|
|
16
|
+
from doctr.utils import order_points
|
|
17
|
+
|
|
18
|
+
__all__ = ["_TableCenterNet", "TableCenterNetPostProcessor"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _get_logic_coords(lc_logic: np.ndarray, col_span: int, row_span: int) -> tuple[int, int, int, int]:
|
|
22
|
+
"""Resolve a cell's logical coordinates (start/end column and row) from the per-corner logical
|
|
23
|
+
predictions (`lc_logic` is a (4, 2) array of [col, row] for corners TL, TR, BR, BL) and the cell span.
|
|
24
|
+
Pure numpy port of the reference `get_logic_coords`."""
|
|
25
|
+
col_span = max(1, col_span)
|
|
26
|
+
row_span = max(1, row_span)
|
|
27
|
+
col_lc = [max(1, int(round(float(p)))) for p in lc_logic[:, 0]]
|
|
28
|
+
row_lc = [max(1, int(round(float(p)))) for p in lc_logic[:, 1]]
|
|
29
|
+
cols, rows = lc_logic[:, 0], lc_logic[:, 1]
|
|
30
|
+
|
|
31
|
+
if col_lc[0] == col_lc[3]:
|
|
32
|
+
start_col = col_lc[0]
|
|
33
|
+
end_col = start_col + col_span - 1
|
|
34
|
+
elif col_lc[1] == col_lc[2]:
|
|
35
|
+
end_col = max(col_span + 1, col_lc[1]) - 1
|
|
36
|
+
start_col = end_col + 1 - col_span
|
|
37
|
+
elif abs(cols[0] - cols[3]) <= abs(cols[1] - cols[2]):
|
|
38
|
+
start_col = max(1, int(round((cols[0] + cols[3]) / 2.0)))
|
|
39
|
+
end_col = start_col + col_span - 1
|
|
40
|
+
else:
|
|
41
|
+
end_col = max(col_span + 1, int(round((cols[1] + cols[2]) / 2.0))) - 1
|
|
42
|
+
start_col = end_col + 1 - col_span
|
|
43
|
+
|
|
44
|
+
if row_lc[0] == row_lc[1]:
|
|
45
|
+
start_row = row_lc[0]
|
|
46
|
+
end_row = start_row + row_span - 1
|
|
47
|
+
elif row_lc[2] == row_lc[3]:
|
|
48
|
+
end_row = max(row_span + 1, row_lc[2]) - 1
|
|
49
|
+
start_row = end_row + 1 - row_span
|
|
50
|
+
elif abs(rows[0] - rows[1]) <= abs(rows[2] - rows[3]):
|
|
51
|
+
start_row = max(1, int(round((rows[0] + rows[1]) / 2.0)))
|
|
52
|
+
end_row = start_row + row_span - 1
|
|
53
|
+
else:
|
|
54
|
+
end_row = max(row_span + 1, int(round((rows[2] + rows[3]) / 2.0))) - 1
|
|
55
|
+
start_row = end_row + 1 - row_span
|
|
56
|
+
|
|
57
|
+
return start_col, end_col, start_row, end_row
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _bbox_overlap_query(center_polys: np.ndarray, corner_polys: np.ndarray) -> list[np.ndarray]:
|
|
61
|
+
"""For each center polygon, the indices of corner polygons whose axis-aligned bounding boxes overlap."""
|
|
62
|
+
c_xmin, c_xmax = center_polys[:, 0::2].min(1), center_polys[:, 0::2].max(1)
|
|
63
|
+
c_ymin, c_ymax = center_polys[:, 1::2].min(1), center_polys[:, 1::2].max(1)
|
|
64
|
+
k_xmin, k_xmax = corner_polys[:, 0::2].min(1), corner_polys[:, 0::2].max(1)
|
|
65
|
+
k_ymin, k_ymax = corner_polys[:, 1::2].min(1), corner_polys[:, 1::2].max(1)
|
|
66
|
+
out = []
|
|
67
|
+
for i in range(center_polys.shape[0]):
|
|
68
|
+
x_ok = (k_xmin <= c_xmax[i]) & (k_xmax >= c_xmin[i])
|
|
69
|
+
y_ok = (k_ymin <= c_ymax[i]) & (k_ymax >= c_ymin[i])
|
|
70
|
+
out.append(np.nonzero(x_ok & y_ok)[0])
|
|
71
|
+
return out
|
|
72
|
+
|
|
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
|
+
|
|
233
|
+
def _lookup_logic(lc_map: np.ndarray, x: float, y: float) -> np.ndarray:
|
|
234
|
+
"""Sample the (2, H, W) logical-coordinate map at a clamped pixel location."""
|
|
235
|
+
h, w = lc_map.shape[1:]
|
|
236
|
+
xi = 0 if x < 0 else (w - 1 if x >= w else int(x))
|
|
237
|
+
yi = 0 if y < 0 else (h - 1 if y >= h else int(y))
|
|
238
|
+
return lc_map[:, yi, xi]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class TableCenterNetPostProcessor:
|
|
242
|
+
"""TableCenterNet post-processor turning the model's *decoded* key-points into table cells.
|
|
243
|
+
|
|
244
|
+
The cell geometry is returned in **relative** coordinates ([0, 1] w.r.t. the model input), so the
|
|
245
|
+
predictor can undo the pre-processor's padding/resize like the other docTR predictors. When
|
|
246
|
+
`assume_straight_pages=True`, geometries are axis-aligned boxes of shape `(N, 4)`; otherwise they
|
|
247
|
+
are quadrilaterals of shape `(N, 4, 2)`.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
center_thresh: minimum score for a cell center to be kept
|
|
251
|
+
corner_thresh: minimum score for a corner to be used during relocation
|
|
252
|
+
not_relocate: if True, skip the corner-relocation step (faster, less accurate)
|
|
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
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
def __init__(
|
|
259
|
+
self,
|
|
260
|
+
center_thresh: float = 0.3,
|
|
261
|
+
corner_thresh: float = 0.3,
|
|
262
|
+
not_relocate: bool = False,
|
|
263
|
+
assume_straight_pages: bool = True,
|
|
264
|
+
geometric_logic: bool = True,
|
|
265
|
+
) -> None:
|
|
266
|
+
self.center_thresh = center_thresh
|
|
267
|
+
self.corner_thresh = corner_thresh
|
|
268
|
+
self.not_relocate = not_relocate
|
|
269
|
+
self.assume_straight_pages = assume_straight_pages
|
|
270
|
+
self.geometric_logic = geometric_logic
|
|
271
|
+
# Cell score decay: cells optimised on <= 2 corners get their score scaled.
|
|
272
|
+
self.cell_min_optimize_count = 2
|
|
273
|
+
self.cell_decay_thresh = 0.4
|
|
274
|
+
|
|
275
|
+
def _relocate(self, decoded: dict[str, np.ndarray], b: int):
|
|
276
|
+
cp = decoded["center_polygons"][b].copy() # (Kc, 8)
|
|
277
|
+
cs = decoded["center_scores"][b].copy() # (Kc,)
|
|
278
|
+
spans = decoded["center_spans"][b] # (Kc, 2)
|
|
279
|
+
corner_polys = decoded["corner_polygons"][b] # (Kn, 8)
|
|
280
|
+
corner_scores = decoded["corner_scores"][b] # (Kn,)
|
|
281
|
+
corner_pts = decoded["corner_points"][b] # (Kn, 2)
|
|
282
|
+
corner_logics = decoded["corner_logics"][b] # (Kn, 2)
|
|
283
|
+
lc_map = decoded["lc"][b] # (2, H, W)
|
|
284
|
+
|
|
285
|
+
valid_c = np.nonzero(cs >= self.center_thresh)[0]
|
|
286
|
+
valid_k = np.nonzero(corner_scores >= self.corner_thresh)[0]
|
|
287
|
+
queries = (
|
|
288
|
+
_bbox_overlap_query(cp[valid_c], corner_polys[valid_k])
|
|
289
|
+
if valid_k.size
|
|
290
|
+
else [np.array([], int)] * valid_c.size
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
logic = np.zeros((cp.shape[0], 4), dtype=np.int32)
|
|
294
|
+
corner_count = np.zeros(cp.shape[0], dtype=np.int32)
|
|
295
|
+
for qi, i in enumerate(valid_c):
|
|
296
|
+
center_poly = Polygon(cp[i].reshape(4, 2))
|
|
297
|
+
prepare(center_poly)
|
|
298
|
+
cell = cp[i].reshape(4, 2)
|
|
299
|
+
origin = decoded["center_polygons"][b][i].reshape(4, 2)
|
|
300
|
+
lc_logic: list[np.ndarray | None] = [None, None, None, None]
|
|
301
|
+
n_used = n_repeat = 0
|
|
302
|
+
for j in valid_k[queries[qi]]:
|
|
303
|
+
cx, cy = corner_pts[j]
|
|
304
|
+
candidate_pts = corner_polys[j].reshape(4, 2)
|
|
305
|
+
if not contains_xy(center_poly, candidate_pts[:, 0], candidate_pts[:, 1]).any():
|
|
306
|
+
continue
|
|
307
|
+
# nearest corner index is computed on the ORIGINAL polygon
|
|
308
|
+
idx = int(np.argmin(((origin - [cx, cy]) ** 2).sum(1)))
|
|
309
|
+
ox, oy = origin[idx]
|
|
310
|
+
px, py = cell[idx]
|
|
311
|
+
if px == ox and py == oy:
|
|
312
|
+
n_used += 1
|
|
313
|
+
cell[idx] = [cx, cy]
|
|
314
|
+
lc_logic[idx] = corner_logics[j]
|
|
315
|
+
elif (ox - px) ** 2 + (oy - py) ** 2 >= (ox - cx) ** 2 + (oy - cy) ** 2:
|
|
316
|
+
n_repeat += 1
|
|
317
|
+
cell[idx] = [cx, cy]
|
|
318
|
+
lc_logic[idx] = corner_logics[j]
|
|
319
|
+
corner_count[i] = n_used + n_repeat
|
|
320
|
+
for k in range(4):
|
|
321
|
+
if lc_logic[k] is None:
|
|
322
|
+
lc_logic[k] = _lookup_logic(lc_map, cell[k][0], cell[k][1])
|
|
323
|
+
col_span, row_span = int(round(float(spans[i][0]))), int(round(float(spans[i][1])))
|
|
324
|
+
logic[i] = _get_logic_coords(np.stack(lc_logic), col_span, row_span) # type: ignore[arg-type]
|
|
325
|
+
cp[i] = cell.reshape(8)
|
|
326
|
+
|
|
327
|
+
# Score decay for under-optimised cells, then re-sort
|
|
328
|
+
keep_high = cs >= self.center_thresh
|
|
329
|
+
decay = keep_high & (corner_count <= self.cell_min_optimize_count)
|
|
330
|
+
cs[decay] *= self.cell_decay_thresh
|
|
331
|
+
order = np.argsort(-cs)
|
|
332
|
+
return cp[order], cs[order], logic[order]
|
|
333
|
+
|
|
334
|
+
def _simple(self, decoded: dict[str, np.ndarray], b: int):
|
|
335
|
+
cp = decoded["center_polygons"][b]
|
|
336
|
+
cs = decoded["center_scores"][b]
|
|
337
|
+
spans = decoded["center_spans"][b]
|
|
338
|
+
lc_map = decoded["lc"][b]
|
|
339
|
+
logic = np.zeros((cp.shape[0], 4), dtype=np.int32)
|
|
340
|
+
for i in np.nonzero(cs >= self.center_thresh)[0]:
|
|
341
|
+
cell = cp[i].reshape(4, 2)
|
|
342
|
+
lc_logic = np.stack([_lookup_logic(lc_map, cell[k][0], cell[k][1]) for k in range(4)])
|
|
343
|
+
col_span, row_span = int(round(float(spans[i][0]))), int(round(float(spans[i][1])))
|
|
344
|
+
logic[i] = _get_logic_coords(lc_logic, col_span, row_span)
|
|
345
|
+
return cp, cs, logic
|
|
346
|
+
|
|
347
|
+
def __call__(self, decoded: dict[str, np.ndarray]) -> list[dict[str, np.ndarray]]:
|
|
348
|
+
feat_h, feat_w = decoded["feat_size"]
|
|
349
|
+
scale = np.array([feat_w, feat_h], dtype=np.float32)
|
|
350
|
+
results: list[dict[str, np.ndarray]] = []
|
|
351
|
+
for b in range(decoded["center_polygons"].shape[0]):
|
|
352
|
+
cp, cs, logic = self._simple(decoded, b) if self.not_relocate else self._relocate(decoded, b)
|
|
353
|
+
keep = cs >= self.center_thresh
|
|
354
|
+
polys = cp[keep].reshape(-1, 4, 2) / scale # relative coordinates
|
|
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]
|
|
362
|
+
if self.assume_straight_pages:
|
|
363
|
+
cells = np.concatenate([polys.min(axis=1), polys.max(axis=1)], axis=1).astype(np.float32)
|
|
364
|
+
else:
|
|
365
|
+
cells = (
|
|
366
|
+
np.stack([order_points(poly) for poly in polys]).astype(np.float32)
|
|
367
|
+
if polys.shape[0]
|
|
368
|
+
else polys.reshape(0, 4, 2).astype(np.float32)
|
|
369
|
+
)
|
|
370
|
+
results.append({
|
|
371
|
+
"polygons": cells, # (N, 4) boxes or (N, 4, 2) quads in relative coordinates
|
|
372
|
+
"scores": scores,
|
|
373
|
+
"logical": logic, # start_col, end_col, start_row, end_row (0-indexed)
|
|
374
|
+
})
|
|
375
|
+
return results
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _gaussian_radius(det_size: tuple[float, float], min_overlap: float = 0.7) -> float:
|
|
379
|
+
height, width = det_size
|
|
380
|
+
a1, b1, c1 = 1, height + width, width * height * (1 - min_overlap) / (1 + min_overlap)
|
|
381
|
+
r1 = (b1 + math.sqrt(max(b1**2 - 4 * a1 * c1, 0))) / 2
|
|
382
|
+
a2, b2, c2 = 4, 2 * (height + width), (1 - min_overlap) * width * height
|
|
383
|
+
r2 = (b2 + math.sqrt(max(b2**2 - 4 * a2 * c2, 0))) / 2
|
|
384
|
+
a3, b3, c3 = 4 * min_overlap, -2 * min_overlap * (height + width), (min_overlap - 1) * width * height
|
|
385
|
+
r3 = (b3 + math.sqrt(max(b3**2 - 4 * a3 * c3, 0))) / 2
|
|
386
|
+
return min(r1, r2, r3)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _gaussian_2d(shape: tuple[int, int], sigma: float = 1.0) -> np.ndarray:
|
|
390
|
+
m, n = ((s - 1) / 2 for s in shape)
|
|
391
|
+
y, x = np.ogrid[-m : m + 1, -n : n + 1]
|
|
392
|
+
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
|
|
393
|
+
h[h < np.finfo(h.dtype).eps * h.max()] = 0
|
|
394
|
+
return h
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _draw_umich_gaussian(heatmap: np.ndarray, center: np.ndarray, radius: int, k: float = 1.0) -> None:
|
|
398
|
+
diameter = 2 * radius + 1
|
|
399
|
+
gaussian = _gaussian_2d((diameter, diameter), sigma=diameter / 6)
|
|
400
|
+
x, y = int(center[0]), int(center[1])
|
|
401
|
+
height, width = heatmap.shape[:2]
|
|
402
|
+
left, right = min(x, radius), min(width - x, radius + 1)
|
|
403
|
+
top, bottom = min(y, radius), min(height - y, radius + 1)
|
|
404
|
+
masked_heatmap = heatmap[y - top : y + bottom, x - left : x + right]
|
|
405
|
+
masked_gaussian = gaussian[radius - top : radius + bottom, radius - left : radius + right]
|
|
406
|
+
if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0:
|
|
407
|
+
np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _polygon_area(points: list[tuple[float, float]]) -> float:
|
|
411
|
+
n = len(points)
|
|
412
|
+
area = 0.0
|
|
413
|
+
for i in range(n):
|
|
414
|
+
x1, y1 = points[i]
|
|
415
|
+
x2, y2 = points[(i + 1) % n]
|
|
416
|
+
area += x1 * y2 - x2 * y1
|
|
417
|
+
return abs(area) / 2.0
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _interpolate_polygons(polygons: list[list[tuple]], img_size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]:
|
|
421
|
+
"""Fill each polygon's interior with the linear interpolation of its per-corner value."""
|
|
422
|
+
final_image = np.zeros(img_size, dtype=np.float32)
|
|
423
|
+
mask = np.zeros(img_size, dtype=bool)
|
|
424
|
+
areas = [_polygon_area([(x, y) for x, y, _ in poly]) for poly in polygons]
|
|
425
|
+
for _, poly in sorted(zip(areas, polygons), key=lambda t: t[0]):
|
|
426
|
+
xs = [p[0] for p in poly]
|
|
427
|
+
ys = [p[1] for p in poly]
|
|
428
|
+
x_min, y_min = math.floor(min(xs)), math.floor(min(ys))
|
|
429
|
+
x_max, y_max = math.ceil(max(xs)), math.ceil(max(ys))
|
|
430
|
+
bw, bh = x_max - x_min + 1, y_max - y_min + 1
|
|
431
|
+
if bw <= 0 or bh <= 0:
|
|
432
|
+
continue
|
|
433
|
+
points = np.array([(x - x_min, y - y_min) for x, y, _ in poly], dtype=np.float32)
|
|
434
|
+
values = np.array([v for _, _, v in poly], dtype=np.float32)
|
|
435
|
+
gx, gy = np.meshgrid(np.arange(bw), np.arange(bh))
|
|
436
|
+
grid_points = np.vstack((gx.ravel(), gy.ravel())).T
|
|
437
|
+
try:
|
|
438
|
+
interp = griddata(points, values, grid_points, method="linear", fill_value=-1)
|
|
439
|
+
except Exception:
|
|
440
|
+
continue
|
|
441
|
+
cols = grid_points[:, 0] + x_min
|
|
442
|
+
rows = grid_points[:, 1] + y_min
|
|
443
|
+
valid = (interp >= 0) & (rows >= 0) & (rows < img_size[0]) & (cols >= 0) & (cols < img_size[1])
|
|
444
|
+
rows, cols, vals = rows[valid], cols[valid], interp[valid]
|
|
445
|
+
free = ~mask[rows, cols]
|
|
446
|
+
final_image[rows[free], cols[free]] = vals[free]
|
|
447
|
+
mask[rows[free], cols[free]] = True
|
|
448
|
+
return final_image, mask
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _interpolate_logical_map(cells_logic_coords: list, output_size: tuple[int, int]):
|
|
452
|
+
"""Build the dense (2, H, W) logical-coordinate map (column map, row map) and its mask."""
|
|
453
|
+
if not cells_logic_coords:
|
|
454
|
+
return np.zeros((2, *output_size), np.float32), np.zeros((2, *output_size), np.float32)
|
|
455
|
+
cols = [[(x, y, col) for (x, y, col, _row) in cell] for cell in cells_logic_coords]
|
|
456
|
+
rows = [[(x, y, row) for (x, y, _col, row) in cell] for cell in cells_logic_coords]
|
|
457
|
+
col_img, col_mask = _interpolate_polygons(cols, output_size)
|
|
458
|
+
row_img, row_mask = _interpolate_polygons(rows, output_size)
|
|
459
|
+
lc = np.stack([col_img, row_img], axis=0)
|
|
460
|
+
lc_mask = np.stack([col_mask, row_mask], axis=0).astype(np.float32)
|
|
461
|
+
return lc, lc_mask
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _build_table_target(
|
|
465
|
+
cells: np.ndarray,
|
|
466
|
+
logic: np.ndarray,
|
|
467
|
+
output_size: tuple[int, int],
|
|
468
|
+
max_objects: int = 3000,
|
|
469
|
+
max_corners: int = 12000,
|
|
470
|
+
) -> dict[str, np.ndarray]:
|
|
471
|
+
"""Render the dense TableCenterNet targets (for a single image) consumed by `TableCenterNet.compute_loss`.
|
|
472
|
+
|
|
473
|
+
Args:
|
|
474
|
+
cells: (N, 4, 2) cell quadrilaterals (corner order TL, TR, BR, BL) in **output-grid** coordinates
|
|
475
|
+
logic: (N, 4) integer logical coordinates `[start_col, end_col, start_row, end_row]` (0-indexed)
|
|
476
|
+
output_size: (H, W) of the model output grid (input size // down_ratio)
|
|
477
|
+
max_objects: maximum number of cells
|
|
478
|
+
max_corners: maximum number of distinct corners
|
|
479
|
+
|
|
480
|
+
Returns:
|
|
481
|
+
the dense target dictionary (numpy arrays) matching the reference schema
|
|
482
|
+
"""
|
|
483
|
+
out_h, out_w = output_size
|
|
484
|
+
hm = np.zeros((2, out_h, out_w), np.float32)
|
|
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)
|
|
487
|
+
ct2cn = np.zeros((max_objects, 8), np.float32)
|
|
488
|
+
cn2ct = np.zeros((max_corners, 8), np.float32)
|
|
489
|
+
reg_ind = np.zeros((max_objects + max_corners,), np.int64)
|
|
490
|
+
reg_mask = np.zeros((max_objects + max_corners,), np.float32)
|
|
491
|
+
ct_ind = np.zeros((max_objects,), np.int64)
|
|
492
|
+
ct_mask = np.zeros((max_objects,), np.float32)
|
|
493
|
+
cn_ind = np.zeros((max_corners,), np.int64)
|
|
494
|
+
cn_mask = np.zeros((max_corners,), np.float32)
|
|
495
|
+
ct_cn_ind = np.zeros((max_objects * 4,), np.int64)
|
|
496
|
+
lc_ind = np.zeros((max_objects, 4), np.int64)
|
|
497
|
+
lc_span = np.zeros((max_objects, 2), np.float32)
|
|
498
|
+
|
|
499
|
+
corner_dict: dict[str, int] = {}
|
|
500
|
+
drawn_corners: set[str] = set()
|
|
501
|
+
cells_logic_coords: list = []
|
|
502
|
+
|
|
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
|
|
507
|
+
corners = cells[i].reshape(8).astype(np.float32).copy()
|
|
508
|
+
corners[0::2] = np.clip(corners[0::2], 0, out_w - 1)
|
|
509
|
+
corners[1::2] = np.clip(corners[1::2], 0, out_h - 1)
|
|
510
|
+
if len(set(corners[0::2].tolist())) < 2 or len(set(corners[1::2].tolist())) < 2:
|
|
511
|
+
continue # not an effective quad
|
|
512
|
+
xs, ys = corners[0::2], corners[1::2]
|
|
513
|
+
max_x, min_x, max_y, min_y = xs.max(), xs.min(), ys.max(), ys.min()
|
|
514
|
+
bbox_h, bbox_w = max_y - min_y, max_x - min_x
|
|
515
|
+
if bbox_h <= 0 or bbox_w <= 0:
|
|
516
|
+
continue
|
|
517
|
+
|
|
518
|
+
radius = max(0, int(_gaussian_radius((math.ceil(bbox_h), math.ceil(bbox_w)))))
|
|
519
|
+
center = np.array([(max_x + min_x) / 2.0, (max_y + min_y) / 2.0], np.float32)
|
|
520
|
+
ci = center.astype(np.int32)
|
|
521
|
+
flat = ci[1] * out_w + ci[0]
|
|
522
|
+
_draw_umich_gaussian(hm[0], ci, radius)
|
|
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
|
|
528
|
+
|
|
529
|
+
start_col, end_col, start_row, end_row = (int(v) + 1 for v in logic[i])
|
|
530
|
+
x1, y1, x2, y2, x3, y3, x4, y4 = corners.tolist()
|
|
531
|
+
clc = [
|
|
532
|
+
(x1, y1, start_col, start_row),
|
|
533
|
+
(x2, y2, end_col + 1, start_row),
|
|
534
|
+
(x3, y3, end_col + 1, end_row + 1),
|
|
535
|
+
(x4, y4, start_col, end_row + 1),
|
|
536
|
+
]
|
|
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
|
|
547
|
+
for j, (x, y, _c, _r) in enumerate(clc):
|
|
548
|
+
lc_ind[i, j] = int(y) * out_w + int(x)
|
|
549
|
+
lc_span[i] = (end_col - start_col + 1, end_row - start_row + 1)
|
|
550
|
+
|
|
551
|
+
for j in range(4):
|
|
552
|
+
si = j * 2
|
|
553
|
+
corner = corners[si : si + 2]
|
|
554
|
+
cint = corner.astype(np.int32)
|
|
555
|
+
key = f"{cint[0]}_{cint[1]}"
|
|
556
|
+
if key not in corner_dict:
|
|
557
|
+
nc = len(corner_dict)
|
|
558
|
+
if nc >= max_corners:
|
|
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
|
|
564
|
+
corner_dict[key] = nc
|
|
565
|
+
reg[max_objects + nc] = np.abs(corner - cint)
|
|
566
|
+
reg_ind[max_objects + nc] = cint[1] * out_w + cint[0]
|
|
567
|
+
reg_mask[max_objects + nc] = 1
|
|
568
|
+
cn_ind[nc] = cint[1] * out_w + cint[0]
|
|
569
|
+
cn_mask[nc] = 1
|
|
570
|
+
if key not in drawn_corners:
|
|
571
|
+
drawn_corners.add(key)
|
|
572
|
+
_draw_umich_gaussian(hm[1], cint, 2)
|
|
573
|
+
cn2ct[nc][si : si + 2] = corner - center
|
|
574
|
+
ct_cn_ind[4 * i + j] = nc * 4 + j
|
|
575
|
+
else:
|
|
576
|
+
idx = corner_dict[key]
|
|
577
|
+
cn2ct[idx][si : si + 2] = corner - center
|
|
578
|
+
ct_cn_ind[4 * i + j] = idx * 4 + j
|
|
579
|
+
|
|
580
|
+
lc, lc_mask = _interpolate_logical_map(cells_logic_coords, (out_h, out_w))
|
|
581
|
+
return {
|
|
582
|
+
"hm": hm,
|
|
583
|
+
"reg": reg,
|
|
584
|
+
"reg_ind": reg_ind,
|
|
585
|
+
"reg_mask": reg_mask,
|
|
586
|
+
"ct_ind": ct_ind,
|
|
587
|
+
"ct_mask": ct_mask,
|
|
588
|
+
"cn_ind": cn_ind,
|
|
589
|
+
"cn_mask": cn_mask,
|
|
590
|
+
"ct2cn": ct2cn,
|
|
591
|
+
"cn2ct": cn2ct,
|
|
592
|
+
"ct_cn_ind": ct_cn_ind,
|
|
593
|
+
"lc": lc,
|
|
594
|
+
"lc_mask": lc_mask,
|
|
595
|
+
"lc_ind": lc_ind,
|
|
596
|
+
"lc_span": lc_span,
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _cells_to_polygons(cells: np.ndarray) -> np.ndarray:
|
|
601
|
+
"""Convert table cells to quadrilaterals.
|
|
602
|
+
|
|
603
|
+
Args:
|
|
604
|
+
cells: relative axis-aligned boxes of shape `(N, 4)` in `(xmin, ymin, xmax, ymax)` format,
|
|
605
|
+
or quadrilaterals of shape `(N, 4, 2)`.
|
|
606
|
+
|
|
607
|
+
Returns:
|
|
608
|
+
Relative quadrilaterals of shape `(N, 4, 2)` in TL, TR, BR, BL order.
|
|
609
|
+
"""
|
|
610
|
+
if cells.ndim == 3 and cells.shape[1:] == (4, 2):
|
|
611
|
+
return cells
|
|
612
|
+
if cells.ndim == 2 and cells.shape[1:] == (4,):
|
|
613
|
+
xmin, ymin, xmax, ymax = cells.T
|
|
614
|
+
return np.stack(
|
|
615
|
+
[
|
|
616
|
+
np.stack([xmin, ymin], axis=-1),
|
|
617
|
+
np.stack([xmax, ymin], axis=-1),
|
|
618
|
+
np.stack([xmax, ymax], axis=-1),
|
|
619
|
+
np.stack([xmin, ymax], axis=-1),
|
|
620
|
+
],
|
|
621
|
+
axis=1,
|
|
622
|
+
).astype(np.float32, copy=False)
|
|
623
|
+
raise ValueError(f"cells are expected to have shape (N, 4) or (N, 4, 2), got {cells.shape}")
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
class _TableCenterNet(BaseModel):
|
|
627
|
+
"""TableCenterNet for table-structure recognition, as described in the official implementation
|
|
628
|
+
`<https://github.com/dreamy-xay/TableCenterNet>`_.
|
|
629
|
+
|
|
630
|
+
This base class holds the framework-agnostic target rendering (`build_target`): the dense maps consumed
|
|
631
|
+
by `compute_loss` are produced here, while `TableCenterNetPostProcessor` decodes the model output.
|
|
632
|
+
"""
|
|
633
|
+
|
|
634
|
+
max_objects: int = 3000
|
|
635
|
+
max_corners: int = 12000
|
|
636
|
+
assume_straight_pages: bool = False
|
|
637
|
+
|
|
638
|
+
def build_target(
|
|
639
|
+
self,
|
|
640
|
+
target: list[dict[str, np.ndarray]],
|
|
641
|
+
output_shape: tuple[int, int],
|
|
642
|
+
) -> dict[str, np.ndarray]:
|
|
643
|
+
"""Render the dense training targets for a batch from per-image cell annotations.
|
|
644
|
+
|
|
645
|
+
Args:
|
|
646
|
+
target: one `{"cells": (N, 4) relative boxes or (N, 4, 2) relative polygons,
|
|
647
|
+
"logic": (N, 4)}` dict per image
|
|
648
|
+
output_shape: (H, W) of the model output grid (input size // down_ratio)
|
|
649
|
+
|
|
650
|
+
Returns:
|
|
651
|
+
the batched dense target dictionary (numpy arrays) matching the reference schema
|
|
652
|
+
"""
|
|
653
|
+
cells_per_image: list[np.ndarray] = []
|
|
654
|
+
for t in target:
|
|
655
|
+
cells = np.asarray(t["cells"])
|
|
656
|
+
if cells.dtype != np.float32:
|
|
657
|
+
raise AssertionError("the expected dtype of target 'cells' entry is 'np.float32'.")
|
|
658
|
+
cells = _cells_to_polygons(cells)
|
|
659
|
+
if np.any((cells > 1) | (cells < 0)):
|
|
660
|
+
raise ValueError("the 'cells' entry of the target is expected to take values between 0 & 1.")
|
|
661
|
+
cells_per_image.append(cells)
|
|
662
|
+
|
|
663
|
+
out_h, out_w = output_shape
|
|
664
|
+
scale = np.array([out_w, out_h], dtype=np.float32)
|
|
665
|
+
per_image = [
|
|
666
|
+
_build_table_target(
|
|
667
|
+
cells * scale,
|
|
668
|
+
np.asarray(t["logic"], dtype=np.int64).reshape(-1, 4),
|
|
669
|
+
(out_h, out_w),
|
|
670
|
+
self.max_objects,
|
|
671
|
+
self.max_corners,
|
|
672
|
+
)
|
|
673
|
+
for t, cells in zip(target, cells_per_image)
|
|
674
|
+
]
|
|
675
|
+
return {k: np.stack([img[k] for img in per_image], axis=0) for k in per_image[0]}
|