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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -0
  3. doctr/contrib/artefacts.py +1 -1
  4. doctr/contrib/base.py +1 -1
  5. doctr/datasets/__init__.py +2 -0
  6. doctr/datasets/coco_text.py +5 -3
  7. doctr/datasets/cord.py +3 -2
  8. doctr/datasets/datasets/base.py +13 -25
  9. doctr/datasets/datasets/pytorch.py +15 -5
  10. doctr/datasets/detection.py +3 -2
  11. doctr/datasets/doc_artefacts.py +3 -2
  12. doctr/datasets/funsd.py +3 -2
  13. doctr/datasets/generator/base.py +6 -5
  14. doctr/datasets/generator/pytorch.py +5 -6
  15. doctr/datasets/ic03.py +4 -3
  16. doctr/datasets/ic13.py +5 -3
  17. doctr/datasets/iiit5k.py +3 -2
  18. doctr/datasets/iiithws.py +5 -3
  19. doctr/datasets/imgur5k.py +5 -3
  20. doctr/datasets/layout.py +123 -0
  21. doctr/datasets/mjsynth.py +5 -3
  22. doctr/datasets/ocr.py +3 -2
  23. doctr/datasets/orientation.py +3 -2
  24. doctr/datasets/recognition.py +3 -2
  25. doctr/datasets/sroie.py +3 -2
  26. doctr/datasets/svhn.py +3 -2
  27. doctr/datasets/svt.py +4 -3
  28. doctr/datasets/synthtext.py +3 -2
  29. doctr/datasets/table_structure.py +97 -0
  30. doctr/datasets/utils.py +15 -6
  31. doctr/datasets/vocabs.py +3 -1
  32. doctr/datasets/wildreceipt.py +5 -3
  33. doctr/file_utils.py +4 -2
  34. doctr/io/__init__.py +1 -0
  35. doctr/io/elements.py +253 -261
  36. doctr/io/exporters.py +1275 -0
  37. doctr/io/html.py +1 -1
  38. doctr/io/image/base.py +4 -3
  39. doctr/io/image/pytorch.py +6 -4
  40. doctr/io/pdf.py +1 -1
  41. doctr/io/reader.py +1 -1
  42. doctr/models/__init__.py +2 -0
  43. doctr/models/_utils.py +111 -25
  44. doctr/models/builder.py +533 -62
  45. doctr/models/classification/__init__.py +2 -0
  46. doctr/models/classification/magc_resnet/pytorch.py +2 -2
  47. doctr/models/classification/mobilenet/pytorch.py +7 -7
  48. doctr/models/classification/predictor/pytorch.py +7 -3
  49. doctr/models/classification/resnet/pytorch.py +6 -6
  50. doctr/models/classification/starnet/__init__.py +1 -0
  51. doctr/models/classification/starnet/pytorch.py +202 -0
  52. doctr/models/classification/textnet/pytorch.py +7 -6
  53. doctr/models/classification/vgg/pytorch.py +4 -3
  54. doctr/models/classification/vip/layers/pytorch.py +5 -5
  55. doctr/models/classification/vip/pytorch.py +5 -5
  56. doctr/models/classification/vit/pytorch.py +4 -4
  57. doctr/models/classification/vit_det/__init__.py +1 -0
  58. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  60. doctr/models/classification/vit_det/pytorch.py +346 -0
  61. doctr/models/classification/zoo.py +4 -1
  62. doctr/models/core.py +1 -1
  63. doctr/models/detection/_utils/base.py +24 -8
  64. doctr/models/detection/_utils/pytorch.py +1 -1
  65. doctr/models/detection/core.py +34 -19
  66. doctr/models/detection/differentiable_binarization/base.py +7 -5
  67. doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
  68. doctr/models/detection/fast/base.py +6 -2
  69. doctr/models/detection/fast/pytorch.py +4 -4
  70. doctr/models/detection/linknet/base.py +6 -2
  71. doctr/models/detection/linknet/pytorch.py +4 -4
  72. doctr/models/detection/predictor/pytorch.py +4 -3
  73. doctr/models/detection/zoo.py +3 -3
  74. doctr/models/factory/hub.py +72 -52
  75. doctr/models/kie_predictor/base.py +17 -2
  76. doctr/models/kie_predictor/pytorch.py +42 -11
  77. doctr/models/layout/__init__.py +2 -0
  78. doctr/models/layout/lw_detr/__init__.py +1 -0
  79. doctr/models/layout/lw_detr/base.py +309 -0
  80. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  81. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  82. doctr/models/layout/lw_detr/pytorch.py +838 -0
  83. doctr/models/layout/predictor/__init__.py +1 -0
  84. doctr/models/layout/predictor/pytorch.py +82 -0
  85. doctr/models/layout/zoo.py +90 -0
  86. doctr/models/modules/layers/pytorch.py +140 -4
  87. doctr/models/modules/transformer/pytorch.py +1 -1
  88. doctr/models/modules/vision_transformer/pytorch.py +1 -1
  89. doctr/models/predictor/base.py +138 -16
  90. doctr/models/predictor/pytorch.py +151 -9
  91. doctr/models/preprocessor/pytorch.py +78 -23
  92. doctr/models/reading_order/__init__.py +1 -0
  93. doctr/models/reading_order/base.py +667 -0
  94. doctr/models/recognition/core.py +1 -1
  95. doctr/models/recognition/crnn/pytorch.py +6 -8
  96. doctr/models/recognition/master/base.py +1 -1
  97. doctr/models/recognition/master/pytorch.py +7 -8
  98. doctr/models/recognition/parseq/base.py +1 -1
  99. doctr/models/recognition/parseq/pytorch.py +5 -5
  100. doctr/models/recognition/predictor/_utils.py +1 -1
  101. doctr/models/recognition/predictor/pytorch.py +2 -2
  102. doctr/models/recognition/sar/pytorch.py +2 -2
  103. doctr/models/recognition/utils.py +9 -11
  104. doctr/models/recognition/viptr/pytorch.py +4 -6
  105. doctr/models/recognition/vitstr/base.py +1 -1
  106. doctr/models/recognition/vitstr/pytorch.py +6 -6
  107. doctr/models/recognition/zoo.py +6 -7
  108. doctr/models/table_structure/__init__.py +2 -0
  109. doctr/models/table_structure/predictor/__init__.py +1 -0
  110. doctr/models/table_structure/predictor/pytorch.py +80 -0
  111. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  112. doctr/models/table_structure/tablecenternet/base.py +485 -0
  113. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  114. doctr/models/table_structure/zoo.py +82 -0
  115. doctr/models/utils/pytorch.py +316 -16
  116. doctr/models/zoo.py +91 -3
  117. doctr/transforms/functional/base.py +3 -2
  118. doctr/transforms/functional/pytorch.py +1 -1
  119. doctr/transforms/modules/base.py +248 -83
  120. doctr/transforms/modules/pytorch.py +213 -74
  121. doctr/utils/common_types.py +22 -2
  122. doctr/utils/data.py +5 -4
  123. doctr/utils/fonts.py +56 -17
  124. doctr/utils/geometry.py +136 -19
  125. doctr/utils/metrics.py +351 -19
  126. doctr/utils/multithreading.py +6 -3
  127. doctr/utils/reconstitution.py +697 -133
  128. doctr/utils/repr.py +1 -1
  129. doctr/utils/visualization.py +63 -4
  130. doctr/version.py +1 -1
  131. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
  132. python_doctr-1.1.0.dist-info/RECORD +179 -0
  133. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  134. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  135. python_doctr-1.0.0.dist-info/RECORD +0 -149
  136. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  137. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  138. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
@@ -0,0 +1,485 @@
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 _lookup_logic(lc_map: np.ndarray, x: float, y: float) -> np.ndarray:
75
+ """Sample the (2, H, W) logical-coordinate map at a clamped pixel location."""
76
+ h, w = lc_map.shape[1:]
77
+ xi = 0 if x < 0 else (w - 1 if x >= w else int(x))
78
+ yi = 0 if y < 0 else (h - 1 if y >= h else int(y))
79
+ return lc_map[:, yi, xi]
80
+
81
+
82
+ class TableCenterNetPostProcessor:
83
+ """TableCenterNet post-processor turning the model's *decoded* key-points into table cells.
84
+
85
+ The cell geometry is returned in **relative** coordinates ([0, 1] w.r.t. the model input), so the
86
+ predictor can undo the pre-processor's padding/resize like the other docTR predictors. When
87
+ `assume_straight_pages=True`, geometries are axis-aligned boxes of shape `(N, 4)`; otherwise they
88
+ are quadrilaterals of shape `(N, 4, 2)`.
89
+
90
+ Args:
91
+ center_thresh: minimum score for a cell center to be kept
92
+ corner_thresh: minimum score for a corner to be used during relocation
93
+ not_relocate: if True, skip the corner-relocation step (faster, less accurate)
94
+ assume_straight_pages: whether the pages are assumed to be straight (i.e., no rotation)
95
+ """
96
+
97
+ def __init__(
98
+ self,
99
+ center_thresh: float = 0.3,
100
+ corner_thresh: float = 0.3,
101
+ not_relocate: bool = False,
102
+ assume_straight_pages: bool = True,
103
+ ) -> None:
104
+ self.center_thresh = center_thresh
105
+ self.corner_thresh = corner_thresh
106
+ self.not_relocate = not_relocate
107
+ self.assume_straight_pages = assume_straight_pages
108
+ # Cell score decay: cells optimised on <= 2 corners get their score scaled.
109
+ self.cell_min_optimize_count = 2
110
+ self.cell_decay_thresh = 0.4
111
+
112
+ def _relocate(self, decoded: dict[str, np.ndarray], b: int):
113
+ cp = decoded["center_polygons"][b].copy() # (Kc, 8)
114
+ cs = decoded["center_scores"][b].copy() # (Kc,)
115
+ spans = decoded["center_spans"][b] # (Kc, 2)
116
+ corner_polys = decoded["corner_polygons"][b] # (Kn, 8)
117
+ corner_scores = decoded["corner_scores"][b] # (Kn,)
118
+ corner_pts = decoded["corner_points"][b] # (Kn, 2)
119
+ corner_logics = decoded["corner_logics"][b] # (Kn, 2)
120
+ lc_map = decoded["lc"][b] # (2, H, W)
121
+
122
+ valid_c = np.nonzero(cs >= self.center_thresh)[0]
123
+ valid_k = np.nonzero(corner_scores >= self.corner_thresh)[0]
124
+ queries = (
125
+ _bbox_overlap_query(cp[valid_c], corner_polys[valid_k])
126
+ if valid_k.size
127
+ else [np.array([], int)] * valid_c.size
128
+ )
129
+
130
+ logic = np.zeros((cp.shape[0], 4), dtype=np.int32)
131
+ corner_count = np.zeros(cp.shape[0], dtype=np.int32)
132
+ for qi, i in enumerate(valid_c):
133
+ center_poly = Polygon(cp[i].reshape(4, 2))
134
+ prepare(center_poly)
135
+ cell = cp[i].reshape(4, 2)
136
+ origin = decoded["center_polygons"][b][i].reshape(4, 2)
137
+ lc_logic: list[np.ndarray | None] = [None, None, None, None]
138
+ n_used = n_repeat = 0
139
+ for j in valid_k[queries[qi]]:
140
+ cx, cy = corner_pts[j]
141
+ candidate_pts = corner_polys[j].reshape(4, 2)
142
+ if not contains_xy(center_poly, candidate_pts[:, 0], candidate_pts[:, 1]).any():
143
+ continue
144
+ # nearest corner index is computed on the ORIGINAL polygon
145
+ idx = int(np.argmin(((origin - [cx, cy]) ** 2).sum(1)))
146
+ ox, oy = origin[idx]
147
+ px, py = cell[idx]
148
+ if px == ox and py == oy:
149
+ n_used += 1
150
+ cell[idx] = [cx, cy]
151
+ lc_logic[idx] = corner_logics[j]
152
+ elif (ox - px) ** 2 + (oy - py) ** 2 >= (ox - cx) ** 2 + (oy - cy) ** 2:
153
+ n_repeat += 1
154
+ cell[idx] = [cx, cy]
155
+ lc_logic[idx] = corner_logics[j]
156
+ corner_count[i] = n_used + n_repeat
157
+ for k in range(4):
158
+ if lc_logic[k] is None:
159
+ lc_logic[k] = _lookup_logic(lc_map, cell[k][0], cell[k][1])
160
+ col_span, row_span = int(round(float(spans[i][0]))), int(round(float(spans[i][1])))
161
+ logic[i] = _get_logic_coords(np.stack(lc_logic), col_span, row_span) # type: ignore[arg-type]
162
+ cp[i] = cell.reshape(8)
163
+
164
+ # Score decay for under-optimised cells, then re-sort
165
+ keep_high = cs >= self.center_thresh
166
+ decay = keep_high & (corner_count <= self.cell_min_optimize_count)
167
+ cs[decay] *= self.cell_decay_thresh
168
+ order = np.argsort(-cs)
169
+ return cp[order], cs[order], logic[order]
170
+
171
+ def _simple(self, decoded: dict[str, np.ndarray], b: int):
172
+ cp = decoded["center_polygons"][b]
173
+ cs = decoded["center_scores"][b]
174
+ spans = decoded["center_spans"][b]
175
+ lc_map = decoded["lc"][b]
176
+ logic = np.zeros((cp.shape[0], 4), dtype=np.int32)
177
+ for i in np.nonzero(cs >= self.center_thresh)[0]:
178
+ cell = cp[i].reshape(4, 2)
179
+ lc_logic = np.stack([_lookup_logic(lc_map, cell[k][0], cell[k][1]) for k in range(4)])
180
+ col_span, row_span = int(round(float(spans[i][0]))), int(round(float(spans[i][1])))
181
+ logic[i] = _get_logic_coords(lc_logic, col_span, row_span)
182
+ return cp, cs, logic
183
+
184
+ def __call__(self, decoded: dict[str, np.ndarray]) -> list[dict[str, np.ndarray]]:
185
+ feat_h, feat_w = decoded["feat_size"]
186
+ scale = np.array([feat_w, feat_h], dtype=np.float32)
187
+ results: list[dict[str, np.ndarray]] = []
188
+ for b in range(decoded["center_polygons"].shape[0]):
189
+ cp, cs, logic = self._simple(decoded, b) if self.not_relocate else self._relocate(decoded, b)
190
+ keep = cs >= self.center_thresh
191
+ polys = cp[keep].reshape(-1, 4, 2) / scale # relative coordinates
192
+ polys = np.clip(polys.astype(np.float32), 0, 1)
193
+ if self.assume_straight_pages:
194
+ cells = np.concatenate([polys.min(axis=1), polys.max(axis=1)], axis=1).astype(np.float32)
195
+ else:
196
+ cells = (
197
+ np.stack([order_points(poly) for poly in polys]).astype(np.float32)
198
+ if polys.shape[0]
199
+ else polys.reshape(0, 4, 2).astype(np.float32)
200
+ )
201
+ results.append({
202
+ "polygons": cells, # (N, 4) boxes or (N, 4, 2) quads in relative coordinates
203
+ "scores": cs[keep].astype(np.float32),
204
+ "logical": (logic[keep] - 1).astype(np.int32), # start_col, end_col, start_row, end_row (0-indexed)
205
+ })
206
+ return results
207
+
208
+
209
+ def _gaussian_radius(det_size: tuple[float, float], min_overlap: float = 0.7) -> float:
210
+ height, width = det_size
211
+ a1, b1, c1 = 1, height + width, width * height * (1 - min_overlap) / (1 + min_overlap)
212
+ r1 = (b1 + math.sqrt(max(b1**2 - 4 * a1 * c1, 0))) / 2
213
+ a2, b2, c2 = 4, 2 * (height + width), (1 - min_overlap) * width * height
214
+ r2 = (b2 + math.sqrt(max(b2**2 - 4 * a2 * c2, 0))) / 2
215
+ a3, b3, c3 = 4 * min_overlap, -2 * min_overlap * (height + width), (min_overlap - 1) * width * height
216
+ r3 = (b3 + math.sqrt(max(b3**2 - 4 * a3 * c3, 0))) / 2
217
+ return min(r1, r2, r3)
218
+
219
+
220
+ def _gaussian_2d(shape: tuple[int, int], sigma: float = 1.0) -> np.ndarray:
221
+ m, n = ((s - 1) / 2 for s in shape)
222
+ y, x = np.ogrid[-m : m + 1, -n : n + 1]
223
+ h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
224
+ h[h < np.finfo(h.dtype).eps * h.max()] = 0
225
+ return h
226
+
227
+
228
+ def _draw_umich_gaussian(heatmap: np.ndarray, center: np.ndarray, radius: int, k: float = 1.0) -> None:
229
+ diameter = 2 * radius + 1
230
+ gaussian = _gaussian_2d((diameter, diameter), sigma=diameter / 6)
231
+ x, y = int(center[0]), int(center[1])
232
+ height, width = heatmap.shape[:2]
233
+ left, right = min(x, radius), min(width - x, radius + 1)
234
+ top, bottom = min(y, radius), min(height - y, radius + 1)
235
+ masked_heatmap = heatmap[y - top : y + bottom, x - left : x + right]
236
+ masked_gaussian = gaussian[radius - top : radius + bottom, radius - left : radius + right]
237
+ if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0:
238
+ np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap)
239
+
240
+
241
+ def _polygon_area(points: list[tuple[float, float]]) -> float:
242
+ n = len(points)
243
+ area = 0.0
244
+ for i in range(n):
245
+ x1, y1 = points[i]
246
+ x2, y2 = points[(i + 1) % n]
247
+ area += x1 * y2 - x2 * y1
248
+ return abs(area) / 2.0
249
+
250
+
251
+ def _interpolate_polygons(polygons: list[list[tuple]], img_size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]:
252
+ """Fill each polygon's interior with the linear interpolation of its per-corner value."""
253
+ final_image = np.zeros(img_size, dtype=np.float32)
254
+ mask = np.zeros(img_size, dtype=bool)
255
+ areas = [_polygon_area([(x, y) for x, y, _ in poly]) for poly in polygons]
256
+ for _, poly in sorted(zip(areas, polygons), key=lambda t: t[0]):
257
+ xs = [p[0] for p in poly]
258
+ ys = [p[1] for p in poly]
259
+ x_min, y_min = math.floor(min(xs)), math.floor(min(ys))
260
+ x_max, y_max = math.ceil(max(xs)), math.ceil(max(ys))
261
+ bw, bh = x_max - x_min + 1, y_max - y_min + 1
262
+ if bw <= 0 or bh <= 0:
263
+ continue
264
+ points = np.array([(x - x_min, y - y_min) for x, y, _ in poly], dtype=np.float32)
265
+ values = np.array([v for _, _, v in poly], dtype=np.float32)
266
+ gx, gy = np.meshgrid(np.arange(bw), np.arange(bh))
267
+ grid_points = np.vstack((gx.ravel(), gy.ravel())).T
268
+ try:
269
+ interp = griddata(points, values, grid_points, method="linear", fill_value=-1)
270
+ except Exception:
271
+ continue
272
+ cols = grid_points[:, 0] + x_min
273
+ rows = grid_points[:, 1] + y_min
274
+ valid = (interp >= 0) & (rows >= 0) & (rows < img_size[0]) & (cols >= 0) & (cols < img_size[1])
275
+ rows, cols, vals = rows[valid], cols[valid], interp[valid]
276
+ free = ~mask[rows, cols]
277
+ final_image[rows[free], cols[free]] = vals[free]
278
+ mask[rows[free], cols[free]] = True
279
+ return final_image, mask
280
+
281
+
282
+ def _interpolate_logical_map(cells_logic_coords: list, output_size: tuple[int, int]):
283
+ """Build the dense (2, H, W) logical-coordinate map (column map, row map) and its mask."""
284
+ if not cells_logic_coords:
285
+ return np.zeros((2, *output_size), np.float32), np.zeros((2, *output_size), np.float32)
286
+ cols = [[(x, y, col) for (x, y, col, _row) in cell] for cell in cells_logic_coords]
287
+ rows = [[(x, y, row) for (x, y, _col, row) in cell] for cell in cells_logic_coords]
288
+ col_img, col_mask = _interpolate_polygons(cols, output_size)
289
+ row_img, row_mask = _interpolate_polygons(rows, output_size)
290
+ lc = np.stack([col_img, row_img], axis=0)
291
+ lc_mask = np.stack([col_mask, row_mask], axis=0).astype(np.float32)
292
+ return lc, lc_mask
293
+
294
+
295
+ def _build_table_target(
296
+ cells: np.ndarray,
297
+ logic: np.ndarray,
298
+ output_size: tuple[int, int],
299
+ max_objects: int = 300,
300
+ max_corners: int = 1200,
301
+ ) -> dict[str, np.ndarray]:
302
+ """Render the dense TableCenterNet targets (for a single image) consumed by `TableCenterNet.compute_loss`.
303
+
304
+ Args:
305
+ cells: (N, 4, 2) cell quadrilaterals (corner order TL, TR, BR, BL) in **output-grid** coordinates
306
+ logic: (N, 4) integer logical coordinates `[start_col, end_col, start_row, end_row]` (0-indexed)
307
+ output_size: (H, W) of the model output grid (input size // down_ratio)
308
+ max_objects: maximum number of cells
309
+ max_corners: maximum number of distinct corners
310
+
311
+ Returns:
312
+ the dense target dictionary (numpy arrays) matching the reference schema
313
+ """
314
+ out_h, out_w = output_size
315
+ hm = np.zeros((2, out_h, out_w), np.float32)
316
+ reg = np.zeros((max_objects * 5, 2), np.float32)
317
+ ct2cn = np.zeros((max_objects, 8), np.float32)
318
+ cn2ct = np.zeros((max_corners, 8), np.float32)
319
+ reg_ind = np.zeros((max_objects * 5,), np.int64)
320
+ reg_mask = np.zeros((max_objects * 5,), np.float32)
321
+ ct_ind = np.zeros((max_objects,), np.int64)
322
+ ct_mask = np.zeros((max_objects,), np.float32)
323
+ cn_ind = np.zeros((max_corners,), np.int64)
324
+ cn_mask = np.zeros((max_corners,), np.float32)
325
+ ct_cn_ind = np.zeros((max_objects * 4,), np.int64)
326
+ lc_ind = np.zeros((max_objects, 4), np.int64)
327
+ lc_span = np.zeros((max_objects, 2), np.float32)
328
+
329
+ corner_dict: dict[str, int] = {}
330
+ cells_logic_coords: list = []
331
+
332
+ for i in range(min(len(cells), max_objects)):
333
+ corners = cells[i].reshape(8).astype(np.float32).copy()
334
+ corners[0::2] = np.clip(corners[0::2], 0, out_w - 1)
335
+ corners[1::2] = np.clip(corners[1::2], 0, out_h - 1)
336
+ if len(set(corners[0::2].tolist())) < 2 or len(set(corners[1::2].tolist())) < 2:
337
+ continue # not an effective quad
338
+ xs, ys = corners[0::2], corners[1::2]
339
+ max_x, min_x, max_y, min_y = xs.max(), xs.min(), ys.max(), ys.min()
340
+ bbox_h, bbox_w = max_y - min_y, max_x - min_x
341
+ if bbox_h <= 0 or bbox_w <= 0:
342
+ continue
343
+
344
+ radius = max(0, int(_gaussian_radius((math.ceil(bbox_h), math.ceil(bbox_w)))))
345
+ center = np.array([(max_x + min_x) / 2.0, (max_y + min_y) / 2.0], np.float32)
346
+ ci = center.astype(np.int32)
347
+ 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
+ _draw_umich_gaussian(hm[0], ci, radius)
352
+ ct2cn[i] = center[[0, 1, 0, 1, 0, 1, 0, 1]] - corners
353
+
354
+ start_col, end_col, start_row, end_row = (int(v) + 1 for v in logic[i])
355
+ x1, y1, x2, y2, x3, y3, x4, y4 = corners.tolist()
356
+ clc = [
357
+ (x1, y1, start_col, start_row),
358
+ (x2, y2, end_col + 1, start_row),
359
+ (x3, y3, end_col + 1, end_row + 1),
360
+ (x4, y4, start_col, end_row + 1),
361
+ ]
362
+ cells_logic_coords.append(clc)
363
+ for j, (x, y, _c, _r) in enumerate(clc):
364
+ lc_ind[i, j] = int(y) * out_w + int(x)
365
+ lc_span[i] = (end_col - start_col + 1, end_row - start_row + 1)
366
+
367
+ for j in range(4):
368
+ si = j * 2
369
+ corner = corners[si : si + 2]
370
+ cint = corner.astype(np.int32)
371
+ key = f"{cint[0]}_{cint[1]}"
372
+ if key not in corner_dict:
373
+ nc = len(corner_dict)
374
+ if nc >= max_corners:
375
+ break
376
+ corner_dict[key] = nc
377
+ reg[max_objects + nc] = np.abs(corner - cint)
378
+ reg_ind[max_objects + nc] = cint[1] * out_w + cint[0]
379
+ reg_mask[max_objects + nc] = 1
380
+ cn_ind[nc] = cint[1] * out_w + cint[0]
381
+ cn_mask[nc] = 1
382
+ _draw_umich_gaussian(hm[1], cint, 2)
383
+ cn2ct[nc][si : si + 2] = corner - center
384
+ ct_cn_ind[4 * i + j] = nc * 4 + j
385
+ else:
386
+ idx = corner_dict[key]
387
+ cn2ct[idx][si : si + 2] = corner - center
388
+ ct_cn_ind[4 * i + j] = idx * 4 + j
389
+
390
+ lc, lc_mask = _interpolate_logical_map(cells_logic_coords, (out_h, out_w))
391
+ return {
392
+ "hm": hm,
393
+ "reg": reg,
394
+ "reg_ind": reg_ind,
395
+ "reg_mask": reg_mask,
396
+ "ct_ind": ct_ind,
397
+ "ct_mask": ct_mask,
398
+ "cn_ind": cn_ind,
399
+ "cn_mask": cn_mask,
400
+ "ct2cn": ct2cn,
401
+ "cn2ct": cn2ct,
402
+ "ct_cn_ind": ct_cn_ind,
403
+ "lc": lc,
404
+ "lc_mask": lc_mask,
405
+ "lc_ind": lc_ind,
406
+ "lc_span": lc_span,
407
+ }
408
+
409
+
410
+ def _cells_to_polygons(cells: np.ndarray) -> np.ndarray:
411
+ """Convert table cells to quadrilaterals.
412
+
413
+ Args:
414
+ cells: relative axis-aligned boxes of shape `(N, 4)` in `(xmin, ymin, xmax, ymax)` format,
415
+ or quadrilaterals of shape `(N, 4, 2)`.
416
+
417
+ Returns:
418
+ Relative quadrilaterals of shape `(N, 4, 2)` in TL, TR, BR, BL order.
419
+ """
420
+ if cells.ndim == 3 and cells.shape[1:] == (4, 2):
421
+ return cells
422
+ if cells.ndim == 2 and cells.shape[1:] == (4,):
423
+ xmin, ymin, xmax, ymax = cells.T
424
+ return np.stack(
425
+ [
426
+ np.stack([xmin, ymin], axis=-1),
427
+ np.stack([xmax, ymin], axis=-1),
428
+ np.stack([xmax, ymax], axis=-1),
429
+ np.stack([xmin, ymax], axis=-1),
430
+ ],
431
+ axis=1,
432
+ ).astype(np.float32, copy=False)
433
+ raise ValueError(f"cells are expected to have shape (N, 4) or (N, 4, 2), got {cells.shape}")
434
+
435
+
436
+ class _TableCenterNet(BaseModel):
437
+ """TableCenterNet for table-structure recognition, as described in the official implementation
438
+ `<https://github.com/dreamy-xay/TableCenterNet>`_.
439
+
440
+ This base class holds the framework-agnostic target rendering (`build_target`): the dense maps consumed
441
+ by `compute_loss` are produced here, while `TableCenterNetPostProcessor` decodes the model output.
442
+ """
443
+
444
+ max_objects: int = 300
445
+ max_corners: int = 1200
446
+ assume_straight_pages: bool = False
447
+
448
+ def build_target(
449
+ self,
450
+ target: list[dict[str, np.ndarray]],
451
+ output_shape: tuple[int, int],
452
+ ) -> dict[str, np.ndarray]:
453
+ """Render the dense training targets for a batch from per-image cell annotations.
454
+
455
+ Args:
456
+ target: one `{"cells": (N, 4) relative boxes or (N, 4, 2) relative polygons,
457
+ "logic": (N, 4)}` dict per image
458
+ output_shape: (H, W) of the model output grid (input size // down_ratio)
459
+
460
+ Returns:
461
+ the batched dense target dictionary (numpy arrays) matching the reference schema
462
+ """
463
+ cells_per_image: list[np.ndarray] = []
464
+ for t in target:
465
+ cells = np.asarray(t["cells"])
466
+ if cells.dtype != np.float32:
467
+ raise AssertionError("the expected dtype of target 'cells' entry is 'np.float32'.")
468
+ cells = _cells_to_polygons(cells)
469
+ if np.any((cells > 1) | (cells < 0)):
470
+ raise ValueError("the 'cells' entry of the target is expected to take values between 0 & 1.")
471
+ cells_per_image.append(cells)
472
+
473
+ out_h, out_w = output_shape
474
+ scale = np.array([out_w, out_h], dtype=np.float32)
475
+ per_image = [
476
+ _build_table_target(
477
+ cells * scale,
478
+ np.asarray(t["logic"], dtype=np.int64).reshape(-1, 4),
479
+ (out_h, out_w),
480
+ self.max_objects,
481
+ self.max_corners,
482
+ )
483
+ for t, cells in zip(target, cells_per_image)
484
+ ]
485
+ return {k: np.stack([img[k] for img in per_image], axis=0) for k in per_image[0]}