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.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -0,0 +1,309 @@
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
+ from typing import Any
7
+
8
+ import cv2
9
+ import numpy as np
10
+
11
+ from doctr.models.core import BaseModel
12
+ from doctr.utils import order_points
13
+
14
+ __all__ = ["_LWDETR", "LWDETRPostProcessor"]
15
+
16
+
17
+ class LWDETRPostProcessor:
18
+ """Implements a post processor for LW-DETR model
19
+
20
+ Args:
21
+ num_classes: number of classes
22
+ score_thresh: confidence threshold for filtering predictions
23
+ iou_thresh: IoU threshold for NMS
24
+ topk: number of top predictions to keep before NMS
25
+ assume_straight_pages: whether the pages are assumed to be straight (i.e., no rotation)
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ num_classes: int,
31
+ score_thresh: float = 0.5,
32
+ iou_thresh: float = 0.5,
33
+ topk: int = 300,
34
+ assume_straight_pages: bool = True,
35
+ ):
36
+ self.num_classes = num_classes
37
+ self.score_thresh = score_thresh
38
+ self.iou_thresh = iou_thresh
39
+ self.topk = topk
40
+ self.assume_straight_pages = assume_straight_pages
41
+
42
+ def _decode_boxes(self, boxes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
43
+ """Decode the predicted boxes from OBB format to polygon format
44
+
45
+ Args:
46
+ boxes: array of predicted boxes in OBB format (N, 6) (cx, cy, w, h, sin(theta), cos(theta))
47
+
48
+ Returns:
49
+ tuple of (polys, angles) where polys is an array of decoded polygons (N, 4, 2)
50
+ and angles is an array of angles in radians (N,)
51
+ """
52
+ cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
53
+ sin, cos = boxes[:, 4], boxes[:, 5]
54
+
55
+ angles = np.arctan2(sin, cos)
56
+
57
+ polys = []
58
+ for i in range(len(boxes)):
59
+ rect = ((float(cx[i]), float(cy[i])), (float(w[i]), float(h[i])), float(np.degrees(angles[i])))
60
+
61
+ poly = order_points(cv2.boxPoints(rect))
62
+ polys.append(poly)
63
+
64
+ return np.asarray(polys, dtype=np.float32), angles
65
+
66
+ def _iou(self, poly1: np.ndarray, poly2: np.ndarray) -> float:
67
+ """Compute the IoU between two polygons
68
+
69
+ Args:
70
+ poly1: first polygon (4, 2)
71
+ poly2: second polygon (4, 2)
72
+
73
+ Returns:
74
+ IoU between the two polygons
75
+ """
76
+ inter = cv2.intersectConvexConvex(
77
+ poly1.astype(np.float32),
78
+ poly2.astype(np.float32),
79
+ )[0]
80
+
81
+ if inter <= 0:
82
+ return 0.0
83
+
84
+ area1 = cv2.contourArea(poly1)
85
+ area2 = cv2.contourArea(poly2)
86
+
87
+ return inter / (area1 + area2 - inter + 1e-6)
88
+
89
+ def _nms(self, polys: np.ndarray, scores: np.ndarray, labels: np.ndarray) -> list[int]:
90
+ """
91
+ Class-wise greedy NMS for rotated polygons.
92
+
93
+ Args:
94
+ polys: (N, 4, 2)
95
+ scores: (N,)
96
+ labels: (N,)
97
+
98
+ Returns:
99
+ indices kept after NMS (global indices)
100
+ """
101
+ if len(polys) == 0:
102
+ return []
103
+
104
+ keep: list[int] = []
105
+
106
+ # Process each class independently
107
+ for cls in np.unique(labels):
108
+ cls_idxs = np.where(labels == cls)[0]
109
+ if len(cls_idxs) == 0:
110
+ continue
111
+
112
+ cls_scores = scores[cls_idxs]
113
+ cls_polys = polys[cls_idxs]
114
+
115
+ # sort by confidence
116
+ order = np.argsort(cls_scores)[::-1]
117
+ cls_idxs = cls_idxs[order]
118
+ cls_polys = cls_polys[order]
119
+ cls_scores = cls_scores[order]
120
+
121
+ suppressed = np.zeros(len(cls_idxs), dtype=bool)
122
+
123
+ for i in range(len(cls_idxs)):
124
+ if suppressed[i]:
125
+ continue
126
+
127
+ keep.append(cls_idxs[i])
128
+
129
+ # compare current box with the rest
130
+ for j in range(i + 1, len(cls_idxs)):
131
+ if suppressed[j]:
132
+ continue
133
+
134
+ iou = self._iou(cls_polys[i], cls_polys[j])
135
+ if iou >= self.iou_thresh:
136
+ suppressed[j] = True
137
+ return keep
138
+
139
+ def __call__(self, logits: np.ndarray, boxes: np.ndarray) -> list[tuple[list[int], np.ndarray, list[float]]]:
140
+ logits = np.asarray(logits)
141
+ boxes = np.asarray(boxes)
142
+
143
+ results: list[tuple[list[int], np.ndarray, list[float]]] = []
144
+
145
+ for b in range(boxes.shape[0]):
146
+ # Sigmoid scores (the model is trained with a sigmoid-based (IA-BCE) loss without
147
+ # a background class)
148
+ prob = 1.0 / (1.0 + np.exp(-logits[b])) # (num_queries, num_classes)
149
+ num_classes = prob.shape[-1]
150
+
151
+ # Keep only the topk (query, class) pairs before NMS
152
+ flat_prob = prob.reshape(-1)
153
+ topk = min(self.topk, flat_prob.size) if self.topk is not None else flat_prob.size
154
+ topk_idxs = np.argsort(flat_prob)[::-1][:topk]
155
+
156
+ scores_b = flat_prob[topk_idxs]
157
+ labels_b = topk_idxs % num_classes
158
+ query_idxs = topk_idxs // num_classes
159
+ bboxes = boxes[b][query_idxs]
160
+
161
+ mask = scores_b > self.score_thresh
162
+
163
+ bboxes = bboxes[mask]
164
+ scores_b = scores_b[mask]
165
+ labels_b = labels_b[mask]
166
+
167
+ polys, _ = (
168
+ self._decode_boxes(bboxes)
169
+ if len(bboxes) > 0
170
+ else (
171
+ np.zeros((0, 4, 2), dtype=np.float32),
172
+ np.zeros((0,), dtype=np.float32),
173
+ )
174
+ )
175
+
176
+ keep = self._nms(polys, scores_b, labels_b) if len(polys) > 0 else []
177
+
178
+ final_labels = []
179
+ final_boxes = []
180
+ final_scores = []
181
+
182
+ for idx in keep:
183
+ poly = polys[idx].reshape(-1).tolist()
184
+ if self.assume_straight_pages:
185
+ x_coords = poly[0::2]
186
+ y_coords = poly[1::2]
187
+ xmin, xmax = min(x_coords), max(x_coords)
188
+ ymin, ymax = min(y_coords), max(y_coords)
189
+ final_boxes.append([xmin, ymin, xmax, ymax])
190
+ else:
191
+ final_boxes.append(poly)
192
+
193
+ final_labels.append(int(labels_b[idx]))
194
+ final_scores.append(float(scores_b[idx]))
195
+
196
+ final_boxes_arr = (
197
+ np.asarray(final_boxes, dtype=np.float32).reshape(-1, 4, 2)
198
+ if not self.assume_straight_pages
199
+ else np.asarray(final_boxes, dtype=np.float32).reshape(-1, 4)
200
+ ).clip(0, 1)
201
+
202
+ results.append((
203
+ final_labels,
204
+ final_boxes_arr,
205
+ final_scores,
206
+ ))
207
+
208
+ return results
209
+
210
+
211
+ class _LWDETR(BaseModel):
212
+ """LW-DETR as described in `"LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection"
213
+ <https://arxiv.org/pdf/2406.03459v1>`_.
214
+ """
215
+
216
+ def build_target(
217
+ self,
218
+ target: list[dict[str, np.ndarray]],
219
+ class_names: list[str],
220
+ ) -> list[dict[str, Any]]:
221
+ """Build the target for LW-DETR training
222
+
223
+ Args:
224
+ target: list of dictionaries where each dictionary corresponds to a sample and has keys corresponding
225
+ to class names and values corresponding to lists of boxes in either polygon format (4, 2)
226
+ or bounding box format (4,) (xmin, ymin, xmax, ymax)
227
+ class_names: list of class names
228
+
229
+ Returns:
230
+ list of dictionaries with keys "boxes" and "labels" where "boxes" is an array of shape (num_boxes, 6)
231
+ containing the box parameters in OBB format (cx, cy, w, h, sin(theta), cos(theta))
232
+ and "labels" is an array of shape (num_boxes,) containing the class labels
233
+ """
234
+ targets = []
235
+ class_to_id = {name: i for i, name in enumerate(class_names)}
236
+
237
+ def _quad_to_obb(poly: np.ndarray):
238
+ poly = np.asarray(poly, dtype=np.float32)
239
+
240
+ # Center point is simply the average of the relative vertices
241
+ cx, cy = np.mean(poly, axis=0)
242
+
243
+ edges = np.stack([
244
+ poly[1] - poly[0],
245
+ poly[2] - poly[1],
246
+ poly[3] - poly[2],
247
+ poly[0] - poly[3],
248
+ ])
249
+
250
+ lengths = np.linalg.norm(edges, axis=1)
251
+ i = np.argmax(lengths)
252
+ dx, dy = edges[i]
253
+
254
+ theta = np.arctan2(dy, dx)
255
+
256
+ # Width and height remain cleanly in relative coordinate space [0, 1]
257
+ w = np.mean([lengths[i], lengths[(i + 2) % 4]])
258
+ h = np.mean([lengths[(i + 1) % 4], lengths[(i + 3) % 4]])
259
+
260
+ # Enforce strict unit-length normal vectors for rotation
261
+ sin_t = np.sin(theta)
262
+ cos_t = np.cos(theta)
263
+ norm = np.sqrt(sin_t**2 + cos_t**2) + 1e-8
264
+
265
+ return np.array(
266
+ [cx, cy, w, h, sin_t / norm, cos_t / norm],
267
+ dtype=np.float32,
268
+ )
269
+
270
+ def to_quad(box: np.ndarray):
271
+ box = np.asarray(box, dtype=np.float32)
272
+ if box.shape == (4,):
273
+ x1, y1, x2, y2 = box
274
+ return np.array([[x1, y1], [x2, y1], [x2, y2], [x1, y2]], dtype=np.float32)
275
+ if box.shape == (4, 2):
276
+ return box.astype(np.float32)
277
+ raise ValueError(f"Unsupported box shape: {box.shape}") # pragma: no cover
278
+
279
+ for sample in target:
280
+ boxes_all = []
281
+ labels_all = []
282
+
283
+ for class_name, boxes in sample.items():
284
+ if class_name not in class_to_id:
285
+ raise ValueError(f"Unknown class name: {class_name}") # pragma: no cover
286
+
287
+ cls_id = class_to_id[class_name]
288
+ boxes = np.asarray(boxes)
289
+
290
+ if boxes.ndim == 1:
291
+ boxes = boxes[None, :]
292
+
293
+ for box in boxes:
294
+ poly = to_quad(box)
295
+ obb = _quad_to_obb(poly)
296
+
297
+ # filter out degenerate boxes
298
+ if obb[2] <= 1e-5 or obb[3] <= 1e-5:
299
+ continue
300
+
301
+ boxes_all.append(obb)
302
+ labels_all.append(cls_id)
303
+
304
+ targets.append({
305
+ "boxes": np.asarray(boxes_all, dtype=np.float32) if boxes_all else np.zeros((0, 6), dtype=np.float32),
306
+ "labels": np.asarray(labels_all, dtype=np.int64),
307
+ })
308
+
309
+ return targets
@@ -0,0 +1 @@
1
+ from .pytorch import *