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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/models/zoo.py CHANGED
@@ -5,7 +5,9 @@
5
5
 
6
6
  from typing import Any
7
7
 
8
+ from ._utils import ConfidenceAggregation, _resolve_confidence_aggregation
8
9
  from .detection.zoo import detection_predictor
10
+ from .formula.zoo import formula_predictor
9
11
  from .kie_predictor import KIEPredictor
10
12
  from .layout.zoo import layout_predictor
11
13
  from .predictor import OCRPredictor
@@ -32,8 +34,14 @@ def _predictor(
32
34
  layout_arch: Any = "lw_detr_s",
33
35
  ignore_regions: list[str] | None = None,
34
36
  detect_tables: bool = False,
37
+ detect_formulas: bool = False,
38
+ confidence_aggregation: ConfidenceAggregation | None = None,
35
39
  **kwargs,
36
40
  ) -> OCRPredictor:
41
+ if confidence_aggregation is not None:
42
+ # Fail before building the models
43
+ _resolve_confidence_aggregation(confidence_aggregation)
44
+
37
45
  # Detection
38
46
  det_predictor = detection_predictor(
39
47
  det_arch,
@@ -51,9 +59,10 @@ def _predictor(
51
59
  pretrained=pretrained,
52
60
  pretrained_backbone=pretrained_backbone,
53
61
  batch_size=reco_bs,
62
+ confidence_aggregation=confidence_aggregation,
54
63
  )
55
64
 
56
- # Layout - required for table detection, so build it whenever layout or tables are requested
65
+ # Layout - required for table and formula recognition, so build it whenever one of them is requested
57
66
  layout_pred = (
58
67
  layout_predictor(
59
68
  layout_arch,
@@ -63,7 +72,7 @@ def _predictor(
63
72
  symmetric_pad=symmetric_pad,
64
73
  batch_size=det_bs,
65
74
  )
66
- if (detect_layout or detect_tables)
75
+ if (detect_layout or detect_tables or detect_formulas)
67
76
  else None
68
77
  )
69
78
 
@@ -81,6 +90,17 @@ def _predictor(
81
90
  else None
82
91
  )
83
92
 
93
+ # Formula recognition - optional, applied on the cropped formula regions found by the layout model
94
+ formula_pred = (
95
+ formula_predictor(
96
+ "formulanet",
97
+ pretrained=pretrained,
98
+ pretrained_backbone=pretrained_backbone,
99
+ )
100
+ if detect_formulas
101
+ else None
102
+ )
103
+
84
104
  return OCRPredictor(
85
105
  det_predictor,
86
106
  reco_predictor,
@@ -92,6 +112,7 @@ def _predictor(
92
112
  detect_language=detect_language,
93
113
  layout_predictor=layout_pred,
94
114
  table_predictor=table_pred,
115
+ formula_predictor=formula_pred,
95
116
  ignore_regions=ignore_regions,
96
117
  **kwargs,
97
118
  )
@@ -113,6 +134,8 @@ def ocr_predictor(
113
134
  layout_arch: Any = "lw_detr_s",
114
135
  ignore_regions: list[str] | None = None,
115
136
  detect_tables: bool = False,
137
+ detect_formulas: bool = False,
138
+ confidence_aggregation: ConfidenceAggregation | None = None,
116
139
  **kwargs: Any,
117
140
  ) -> OCRPredictor:
118
141
  """End-to-end OCR architecture using one model for localization, and another for text recognition.
@@ -156,7 +179,17 @@ def ocr_predictor(
156
179
  structure model. Words falling inside a detected table are regrouped into a structured table
157
180
  (accessible via `page.tables`) and removed from the regular text output. This enables the layout
158
181
  model and slightly deteriorates the overall latency.
159
- kwargs: keyword args of `OCRPredictor`
182
+ detect_formulas: if True, formula regions found by the layout model are masked out of the text detection,
183
+ cropped and read as LaTeX by a formula recognition model (accessible via `page.formulas`, and exported as
184
+ display math, e.g. `$$...$$` in Markdown). This enables the layout model and deteriorates the overall
185
+ latency.
186
+ confidence_aggregation: aggregation method of the character probabilities of the recognition model into the
187
+ word confidence: "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a Python callable
188
+ taking the 1D array of probabilities and returning a float. If None (default), the method of the
189
+ recognition model is kept ("min" for CRNN, VIPTR, SAR and MASTER, "mean" for ViTSTR and PARSeq).
190
+ A recognition model instance passed as `reco_arch` is modified.
191
+ kwargs: keyword args of `OCRPredictor` (e.g. `page_chunk_size`, the maximum number of pages of a lazy
192
+ page source processed at once)
160
193
 
161
194
  Returns:
162
195
  OCR predictor
@@ -176,7 +209,9 @@ def ocr_predictor(
176
209
  detect_layout=detect_layout,
177
210
  layout_arch=layout_arch,
178
211
  detect_tables=detect_tables,
212
+ detect_formulas=detect_formulas,
179
213
  ignore_regions=ignore_regions,
214
+ confidence_aggregation=confidence_aggregation,
180
215
  **kwargs,
181
216
  )
182
217
 
@@ -197,8 +232,13 @@ def _kie_predictor(
197
232
  detect_layout: bool = False,
198
233
  layout_arch: Any = "lw_detr_s",
199
234
  ignore_regions: list[str] | None = None,
235
+ confidence_aggregation: ConfidenceAggregation | None = None,
200
236
  **kwargs,
201
237
  ) -> KIEPredictor:
238
+ if confidence_aggregation is not None:
239
+ # Fail before building the models
240
+ _resolve_confidence_aggregation(confidence_aggregation)
241
+
202
242
  # Detection
203
243
  det_predictor = detection_predictor(
204
244
  det_arch,
@@ -216,6 +256,7 @@ def _kie_predictor(
216
256
  pretrained=pretrained,
217
257
  pretrained_backbone=pretrained_backbone,
218
258
  batch_size=reco_bs,
259
+ confidence_aggregation=confidence_aggregation,
219
260
  )
220
261
 
221
262
  # Layout - optional
@@ -262,6 +303,7 @@ def kie_predictor(
262
303
  detect_layout: bool = False,
263
304
  layout_arch: Any = "lw_detr_s",
264
305
  ignore_regions: list[str] | None = None,
306
+ confidence_aggregation: ConfidenceAggregation | None = None,
265
307
  **kwargs: Any,
266
308
  ) -> KIEPredictor:
267
309
  """End-to-end KIE architecture using one model for localization, and another for text recognition.
@@ -301,7 +343,13 @@ def kie_predictor(
301
343
  ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
302
344
  layout model will be used to locate the regions of the specified classes, and these regions will
303
345
  be masked out (filled with black) before passing the pages to the detection/recognition modules.
304
- kwargs: keyword args of `OCRPredictor`
346
+ confidence_aggregation: aggregation method of the character probabilities of the recognition model into the
347
+ word confidence: "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a Python callable
348
+ taking the 1D array of probabilities and returning a float. If None (default), the method of the
349
+ recognition model is kept ("min" for CRNN, VIPTR, SAR and MASTER, "mean" for ViTSTR and PARSeq).
350
+ A recognition model instance passed as `reco_arch` is modified.
351
+ kwargs: keyword args of `OCRPredictor` (e.g. `page_chunk_size`, the maximum number of pages of a lazy
352
+ page source processed at once)
305
353
 
306
354
  Returns:
307
355
  KIE predictor
@@ -321,5 +369,6 @@ def kie_predictor(
321
369
  detect_layout=detect_layout,
322
370
  layout_arch=layout_arch,
323
371
  ignore_regions=ignore_regions,
372
+ confidence_aggregation=confidence_aggregation,
324
373
  **kwargs,
325
374
  )
@@ -25,6 +25,9 @@ def crop_boxes(
25
25
  Returns:
26
26
  the cropped boxes
27
27
  """
28
+ boxes = boxes.copy()
29
+ if boxes.shape[0] == 0: # nothing to crop (e.g. an image without any text)
30
+ return boxes
28
31
  is_box_rel = boxes.max() <= 1
29
32
  is_crop_rel = max(crop_box) <= 1
30
33
 
@@ -61,6 +64,9 @@ def expand_line(line: np.ndarray, target_shape: tuple[int, int]) -> tuple[float,
61
64
  return line[0]
62
65
  # Get the line equation
63
66
  _tmp = line[1] - line[0]
67
+ if not np.any(_tmp):
68
+ # Both points coincide (e.g. once rounded to pixels): there is no direction to extend the line in
69
+ return line[0, 0], line[0, 1]
64
70
  _direction = _tmp > 0
65
71
  _flat = _tmp == 0
66
72
  # vertical case
@@ -5,6 +5,7 @@
5
5
 
6
6
  from copy import deepcopy
7
7
 
8
+ import cv2
8
9
  import numpy as np
9
10
  import torch
10
11
  from scipy.ndimage import gaussian_filter
@@ -14,7 +15,15 @@ from doctr.utils.geometry import rotate_abs_geoms
14
15
 
15
16
  from .base import create_shadow_mask, crop_boxes
16
17
 
17
- __all__ = ["invert_colors", "rotate_sample", "crop_detection", "random_shadow"]
18
+ __all__ = [
19
+ "invert_colors",
20
+ "rotate_sample",
21
+ "crop_detection",
22
+ "random_shadow",
23
+ "random_glare",
24
+ "random_lighting",
25
+ "perspective_sample",
26
+ ]
18
27
 
19
28
 
20
29
  def invert_colors(img: torch.Tensor, min_val: float = 0.6) -> torch.Tensor:
@@ -62,12 +71,14 @@ def rotate_sample(
62
71
  rotated_img = rotated_img[:3] # when expand=True, it expands to RGBA channels
63
72
  # Get absolute coords
64
73
  _geoms = deepcopy(geoms)
74
+ # Relative coordinates are scaled to the image size (an empty array has no coordinates to scale)
75
+ is_relative = _geoms.size == 0 or np.max(_geoms) <= 1
65
76
  if _geoms.shape[1:] == (4,):
66
- if np.max(_geoms) <= 1:
77
+ if is_relative:
67
78
  _geoms[:, [0, 2]] *= img.shape[-1]
68
79
  _geoms[:, [1, 3]] *= img.shape[-2]
69
80
  elif _geoms.shape[1:] == (4, 2):
70
- if np.max(_geoms) <= 1:
81
+ if is_relative:
71
82
  _geoms[..., 0] *= img.shape[-1]
72
83
  _geoms[..., 1] *= img.shape[-2]
73
84
  else:
@@ -104,11 +115,11 @@ def crop_detection(
104
115
  if any(val < 0 or val > 1 for val in crop_box):
105
116
  raise AssertionError("coordinates of arg `crop_box` should be relative")
106
117
  h, w = img.shape[-2:]
107
- xmin, ymin = int(round(crop_box[0] * (w - 1))), int(round(crop_box[1] * (h - 1)))
108
- xmax, ymax = int(round(crop_box[2] * (w - 1))), int(round(crop_box[3] * (h - 1)))
118
+ xmin, ymin = int(round(crop_box[0] * w)), int(round(crop_box[1] * h))
119
+ xmax, ymax = int(round(crop_box[2] * w)), int(round(crop_box[3] * h))
109
120
  cropped_img = F.crop(img, ymin, xmin, ymax - ymin, xmax - xmin)
110
121
  # Crop the box
111
- boxes = crop_boxes(boxes, crop_box if boxes.max() <= 1 else (xmin, ymin, xmax, ymax))
122
+ boxes = crop_boxes(boxes, crop_box if boxes.size == 0 or boxes.max() <= 1 else (xmin, ymin, xmax, ymax))
112
123
 
113
124
  return cropped_img, boxes
114
125
 
@@ -135,3 +146,120 @@ def random_shadow(img: torch.Tensor, opacity_range: tuple[float, float], **kwarg
135
146
  shadow_tensor = shadow_tensor.to(img.device).unsqueeze(0) # Add channel dimension
136
147
 
137
148
  return opacity * shadow_tensor * img + (1 - opacity) * img
149
+
150
+
151
+ def random_glare(
152
+ img: torch.Tensor, opacity_range: tuple[float, float], num_spots: tuple[int, int] = (1, 3)
153
+ ) -> torch.Tensor:
154
+ """Add soft bright spots, like the specular reflections of a light source on a photographed screen or a glossy
155
+ sheet.
156
+
157
+ Args:
158
+ img: image to modify (C, H, W), float in [0, 1]
159
+ opacity_range: minimum and maximum strength of the reflections
160
+ num_spots: minimum and maximum number of reflections
161
+
162
+ Returns:
163
+ the image with the reflections blended towards white (same shape as input)
164
+ """
165
+ _, h, w = img.shape
166
+ ys, xs = np.mgrid[0:h, 0:w].astype(np.float32)
167
+ mask = np.zeros((h, w), dtype=np.float32)
168
+ for _ in range(np.random.randint(num_spots[0], num_spots[1] + 1)):
169
+ cx, cy = np.random.uniform(0, w), np.random.uniform(0, h)
170
+ rx, ry = np.random.uniform(0.08, 0.35) * w, np.random.uniform(0.08, 0.35) * h
171
+ theta = np.random.uniform(0, np.pi)
172
+ dx, dy = xs - cx, ys - cy
173
+ u = dx * np.cos(theta) + dy * np.sin(theta)
174
+ v = -dx * np.sin(theta) + dy * np.cos(theta)
175
+ mask = np.maximum(mask, np.exp(-((u / rx) ** 2 + (v / ry) ** 2)))
176
+ opacity = float(np.random.uniform(*opacity_range))
177
+ glare = torch.from_numpy(mask).to(device=img.device, dtype=img.dtype).unsqueeze(0) * opacity
178
+ return img + glare * (1 - img)
179
+
180
+
181
+ def random_lighting(
182
+ img: torch.Tensor, strength_range: tuple[float, float], grid: tuple[int, int] = (2, 4)
183
+ ) -> torch.Tensor:
184
+ """Multiply the image by a smooth, low-frequency brightness field: uneven lighting, the shading of a crumpled
185
+ or curved sheet, vignetting.
186
+
187
+ Args:
188
+ img: image to modify (C, H, W), float in [0, 1]
189
+ strength_range: minimum and maximum amplitude of the field (0.3 = brightness between 0.7 and 1.3)
190
+ grid: minimum and maximum size of the random grid that is upsampled into the field
191
+
192
+ Returns:
193
+ the modulated image (same shape as input)
194
+ """
195
+ _, h, w = img.shape
196
+ n = np.random.randint(grid[0], grid[1] + 1)
197
+ strength = np.random.uniform(*strength_range)
198
+ coarse = np.random.uniform(-1, 1, size=(n, n)).astype(np.float32)
199
+ field = cv2.resize(coarse, (w, h), interpolation=cv2.INTER_CUBIC)
200
+ field = (1 + strength * np.clip(field, -1, 1)).astype(np.float32)
201
+ return (img * torch.from_numpy(field).to(device=img.device, dtype=img.dtype).unsqueeze(0)).clamp(0, 1)
202
+
203
+
204
+ def perspective_sample(
205
+ img: torch.Tensor,
206
+ geoms: np.ndarray,
207
+ distortion: float,
208
+ mask: torch.Tensor | None = None,
209
+ ) -> tuple[torch.Tensor, np.ndarray, torch.Tensor | None]:
210
+ """Warp an image (and its boxes / polygons) with a random perspective, as if it were photographed at an angle.
211
+
212
+ The four corners of the image are moved inwards by up to `distortion` times the image size, and the image is
213
+ warped so that the original corners land on the moved ones (the content shrinks, the borders are filled with
214
+ zeros like a background around a photographed page).
215
+
216
+ Args:
217
+ img: image to warp (C, H, W)
218
+ geoms: relative boxes (N, 4) or polygons (N, 4, 2) in [0, 1]
219
+ distortion: maximum relative displacement of every corner
220
+ mask: optional (H, W) boolean validity mask warped alongside
221
+
222
+ Returns:
223
+ the warped image, the warped geometries (same format, clipped to [0, 1]) and the warped mask
224
+ """
225
+ _, h, w = img.shape
226
+ start = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]], dtype=np.float32)
227
+ dx, dy = distortion * w, distortion * h
228
+ end = start + np.array(
229
+ [
230
+ [np.random.uniform(0, dx), np.random.uniform(0, dy)],
231
+ [-np.random.uniform(0, dx), np.random.uniform(0, dy)],
232
+ [-np.random.uniform(0, dx), -np.random.uniform(0, dy)],
233
+ [np.random.uniform(0, dx), -np.random.uniform(0, dy)],
234
+ ],
235
+ dtype=np.float32,
236
+ )
237
+ warped = F.perspective(img, start.tolist(), end.tolist(), interpolation=F.InterpolationMode.BILINEAR, fill=0)
238
+ warped_mask = None
239
+ if mask is not None:
240
+ warped_mask = (
241
+ F
242
+ .perspective(
243
+ mask.unsqueeze(0).to(torch.uint8), start.tolist(), end.tolist(), F.InterpolationMode.NEAREST, fill=0
244
+ )
245
+ .squeeze(0)
246
+ .to(torch.bool)
247
+ )
248
+ if geoms.shape[0] == 0:
249
+ return warped, geoms.copy(), warped_mask
250
+
251
+ matrix = cv2.getPerspectiveTransform(start, end)
252
+ is_polygon = geoms.ndim == 3
253
+ if is_polygon:
254
+ pts = geoms.astype(np.float32).reshape(-1, 4, 2)
255
+ else:
256
+ x1, y1, x2, y2 = (geoms[:, i].astype(np.float32) for i in range(4))
257
+ pts = np.stack([np.stack([x1, y1], 1), np.stack([x2, y1], 1), np.stack([x2, y2], 1), np.stack([x1, y2], 1)], 1)
258
+ abs_pts = pts * np.array([w, h], dtype=np.float32)
259
+ out = cv2.perspectiveTransform(abs_pts.reshape(-1, 1, 2), matrix).reshape(-1, 4, 2)
260
+ rel = out / np.array([w, h], dtype=np.float32)
261
+ rel = np.clip(rel, 0, 1)
262
+ if is_polygon:
263
+ return warped, rel.astype(geoms.dtype), warped_mask
264
+ boxes = np.concatenate([rel.min(axis=1), rel.max(axis=1)], axis=1).astype(geoms.dtype)
265
+ return warped, boxes, warped_mask
@@ -197,6 +197,11 @@ class RandomRotate(NestedObject):
197
197
  def extra_repr(self) -> str:
198
198
  return f"max_angle={self.max_angle}, expand={self.expand}"
199
199
 
200
+ def _rotate_image_only(self, img: Any, angle: float) -> Any:
201
+ dummy_box = np.array([[0, 0, 1, 1]], dtype=np.float32)
202
+ r_img, _ = F.rotate_sample(img, dummy_box, angle, self.expand)
203
+ return r_img
204
+
200
205
  def _rotate_array(self, img: Any, target: np.ndarray, angle: float):
201
206
  is_polygon = target.shape[1:] == (4, 2)
202
207
 
@@ -225,10 +230,11 @@ class RandomRotate(NestedObject):
225
230
  r_mask, _ = F.rotate_sample(
226
231
  mask.unsqueeze(0), np.array([[0, 0, 1, 1]], dtype=np.float32), angle, self.expand
227
232
  )
233
+ # Remove the axis added for the rotation, so the mask keeps its shape like in the other transforms
234
+ r_mask = r_mask.squeeze(0)
228
235
 
229
236
  if target is None:
230
- r_img, _ = F.rotate_sample(img, np.array([[0, 0, 1, 1]], dtype=np.float32), angle, self.expand)
231
- return sample.replace(image=r_img, mask=r_mask)
237
+ return sample.replace(image=self._rotate_image_only(img, angle), mask=r_mask)
232
238
 
233
239
  if isinstance(target, dict):
234
240
  rotated_targets = {}
@@ -244,9 +250,13 @@ class RandomRotate(NestedObject):
244
250
  rotated_img = r_img
245
251
  rotated_targets[cls_name] = r_arr
246
252
 
247
- final_img = rotated_img if rotated_img is not None else img
253
+ # Every class may be empty: the image (and its mask) still have to be rotated
254
+ final_img = rotated_img if rotated_img is not None else self._rotate_image_only(img, angle)
248
255
  return sample.replace(image=final_img, mask=r_mask, target=rotated_targets)
249
256
 
257
+ if len(target) == 0:
258
+ return sample.replace(image=self._rotate_image_only(img, angle), mask=r_mask, target=target.copy())
259
+
250
260
  r_img, r_target = self._rotate_array(img, target, angle)
251
261
  return sample.replace(image=r_img, mask=r_mask, target=r_target)
252
262
 
@@ -382,6 +392,10 @@ class RandomCrop(NestedObject):
382
392
  r_mask = self._crop_image_only(mask, crop_box) if mask is not None else None
383
393
  return sample.replace(image=cropped_img, mask=r_mask, target=cropped_targets)
384
394
 
395
+ if len(target) == 0:
396
+ # Same as a dict target without any box: keep the sample as is
397
+ return sample.replace(image=img, mask=mask, target=target.copy())
398
+
385
399
  c_img, c_target = self._crop_array(img, target, crop_box)
386
400
  if c_img is img:
387
401
  r_mask = mask
@@ -15,7 +15,7 @@ from torchvision.transforms import transforms as T
15
15
 
16
16
  from doctr.utils import Sample
17
17
 
18
- from ..functional import random_shadow
18
+ from ..functional import perspective_sample, random_glare, random_lighting, random_shadow
19
19
 
20
20
  __all__ = [
21
21
  "Resize",
@@ -24,7 +24,11 @@ __all__ = [
24
24
  "RandomHorizontalFlip",
25
25
  "RandomShadow",
26
26
  "RandomResize",
27
+ "RandomPad",
27
28
  "GaussianBlur",
29
+ "RandomGlare",
30
+ "RandomLighting",
31
+ "RandomPerspective",
28
32
  ]
29
33
 
30
34
 
@@ -278,11 +282,11 @@ class GaussianBlur(torch.nn.Module):
278
282
  # Sample a random sigma value within the specified range
279
283
  sigma = torch.empty(1).uniform_(*self.sigma_range).item()
280
284
 
281
- # Apply Gaussian blur along spatial dimensions only
285
+ # Apply Gaussian blur along spatial dimensions only (a zero sigma leaves the leading channel axis untouched)
282
286
  blurred = torch.tensor(
283
287
  gaussian_filter(
284
288
  sample.image.numpy(),
285
- sigma=sigma,
289
+ sigma=(0.0,) * (sample.image.ndim - 2) + (sigma, sigma),
286
290
  mode="reflect",
287
291
  truncate=4.0,
288
292
  ),
@@ -430,7 +434,11 @@ class RandomResize(torch.nn.Module):
430
434
  if torch.rand(1) < self.p:
431
435
  scale_h = np.random.uniform(*self.scale_range)
432
436
  scale_w = np.random.uniform(*self.scale_range)
433
- new_size = (int(sample.image.shape[-2] * scale_h), int(sample.image.shape[-1] * scale_w))
437
+ # A side scaled below one pixel is kept at one pixel, as an image can not be resized to zero pixels
438
+ new_size = (
439
+ max(1, int(sample.image.shape[-2] * scale_h)),
440
+ max(1, int(sample.image.shape[-1] * scale_w)),
441
+ )
434
442
 
435
443
  res = self._resize(
436
444
  new_size,
@@ -446,3 +454,176 @@ class RandomResize(torch.nn.Module):
446
454
 
447
455
  def extra_repr(self) -> str:
448
456
  return f"scale_range={self.scale_range}, preserve_aspect_ratio={self.preserve_aspect_ratio}, symmetric_pad={self.symmetric_pad}, p={self.p}" # noqa: E501
457
+
458
+
459
+ class RandomPad(torch.nn.Module):
460
+ """Randomly pad the input image with its background color and align the corresponding targets
461
+
462
+ Each side gets an independent padding, filled with the background color of the image (the median color of its
463
+ border pixels: white for a rendered document, the paper color for a photo). Used for instance to teach a model to
464
+ read the crops of layout regions with their margins.
465
+
466
+ >>> import torch
467
+ >>> from doctr.transforms import RandomPad
468
+ >>> from doctr.utils import Sample
469
+ >>> transfo = RandomPad(max_ratio=0.5, p=0.5)
470
+ >>> out = transfo(Sample(image=torch.rand((3, 64, 256))))
471
+
472
+ Args:
473
+ max_ratio: maximum padding of each side, relative to the image height
474
+ p: probability to apply the transformation
475
+ """
476
+
477
+ def __init__(self, max_ratio: float = 0.5, p: float = 0.5) -> None:
478
+ super().__init__()
479
+ if max_ratio < 0:
480
+ raise ValueError("`max_ratio` must be non-negative")
481
+ self.max_ratio = max_ratio
482
+ self.p = p
483
+
484
+ @staticmethod
485
+ def _pad_target(target: np.ndarray, offset: tuple[int, int], size: tuple[int, int], new_size: tuple[int, int]):
486
+ """Map relative boxes (N, 4) or polygons (N, 4, 2) of the image to the padded image"""
487
+ if not ((target.ndim == 2 and target.shape[1] == 4) or (target.ndim == 3 and target.shape[1:] == (4, 2))):
488
+ raise ValueError(f"expected relative boxes (N, 4) or polygons (N, 4, 2), got shape {target.shape}")
489
+ (left, top), (h, w), (new_h, new_w) = offset, size, new_size
490
+ out = target.astype(np.float32, copy=True)
491
+ xs, ys = (out[..., [0, 2]], out[..., [1, 3]]) if out.ndim == 2 else (out[..., 0], out[..., 1])
492
+ new_xs, new_ys = (left + xs * w) / new_w, (top + ys * h) / new_h
493
+ if out.ndim == 2:
494
+ out[..., [0, 2]], out[..., [1, 3]] = new_xs, new_ys
495
+ else:
496
+ out[..., 0], out[..., 1] = new_xs, new_ys
497
+ return out
498
+
499
+ def forward(self, sample: Sample) -> Sample:
500
+ if torch.rand(1) >= self.p:
501
+ return sample
502
+ img = sample.image # (C, H, W)
503
+ _, h, w = img.shape
504
+ top, bottom, left, right = (torch.rand(4) * self.max_ratio * h).long().tolist()
505
+ new_h, new_w = top + h + bottom, left + w + right
506
+ # Background color: the median color of the border pixels
507
+ border = torch.cat([img[:, 0], img[:, -1], img[:, :, 0], img[:, :, -1]], dim=1)
508
+ background = border.median(dim=1).values
509
+ out = background[:, None, None].repeat(1, new_h, new_w)
510
+ out[:, top : top + h, left : left + w] = img
511
+
512
+ target = sample.target
513
+ if isinstance(target, np.ndarray):
514
+ target = self._pad_target(target, (left, top), (h, w), (new_h, new_w))
515
+ elif isinstance(target, dict):
516
+ target = {
517
+ key: self._pad_target(value, (left, top), (h, w), (new_h, new_w))
518
+ if isinstance(value, np.ndarray)
519
+ else value
520
+ for key, value in target.items()
521
+ }
522
+ # The padded areas are not valid image content
523
+ mask = None if sample.mask is None else pad(sample.mask, (left, right, top, bottom), value=False)
524
+ return sample.replace(image=out, target=target, mask=mask)
525
+
526
+ def extra_repr(self) -> str:
527
+ return f"max_ratio={self.max_ratio}, p={self.p}"
528
+
529
+
530
+ def _apply_float_photometric(sample: Sample, fn) -> Sample:
531
+ """Run a photometric function expecting a float image in [0, 1] on a float or uint8 sample."""
532
+ if sample.image.dtype == torch.uint8:
533
+ out = (255 * fn(sample.image.to(dtype=torch.float32) / 255)).round().clip(0, 255).to(dtype=torch.uint8)
534
+ else:
535
+ out = fn(sample.image).clip(0, 1)
536
+ return sample.replace(image=out)
537
+
538
+
539
+ class RandomGlare(torch.nn.Module):
540
+ """Adds soft bright reflections to the image, like a light source mirrored on a photographed screen or a
541
+ glossy sheet
542
+
543
+ >>> import torch
544
+ >>> from doctr.transforms import RandomGlare
545
+ >>> from doctr.utils import Sample
546
+ >>> transfo = RandomGlare((0.2, 0.7))
547
+ >>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
548
+
549
+ Args:
550
+ opacity_range: minimum and maximum strength of the reflections
551
+ num_spots: minimum and maximum number of reflections
552
+ """
553
+
554
+ def __init__(self, opacity_range: tuple[float, float] | None = None, num_spots: tuple[int, int] = (1, 3)) -> None:
555
+ super().__init__()
556
+ self.opacity_range = opacity_range if isinstance(opacity_range, tuple) else (0.2, 0.7)
557
+ self.num_spots = num_spots
558
+
559
+ def __call__(self, sample: Sample) -> Sample:
560
+ return _apply_float_photometric(sample, lambda img: random_glare(img, self.opacity_range, self.num_spots))
561
+
562
+ def extra_repr(self) -> str:
563
+ return f"opacity_range={self.opacity_range}, num_spots={self.num_spots}"
564
+
565
+
566
+ class RandomLighting(torch.nn.Module):
567
+ """Multiplies the image by a smooth low-frequency brightness field: uneven lighting, the shading of a crumpled
568
+ or curved sheet, vignetting
569
+
570
+ >>> import torch
571
+ >>> from doctr.transforms import RandomLighting
572
+ >>> from doctr.utils import Sample
573
+ >>> transfo = RandomLighting((0.1, 0.4))
574
+ >>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
575
+
576
+ Args:
577
+ strength_range: minimum and maximum amplitude of the field (0.3 = brightness between 0.7 and 1.3)
578
+ """
579
+
580
+ def __init__(self, strength_range: tuple[float, float] | None = None) -> None:
581
+ super().__init__()
582
+ self.strength_range = strength_range if isinstance(strength_range, tuple) else (0.1, 0.4)
583
+
584
+ def __call__(self, sample: Sample) -> Sample:
585
+ return _apply_float_photometric(sample, lambda img: random_lighting(img, self.strength_range))
586
+
587
+ def extra_repr(self) -> str:
588
+ return f"strength_range={self.strength_range}"
589
+
590
+
591
+ class RandomPerspective(torch.nn.Module):
592
+ """Warps the image and its boxes with a random perspective, as if the page were photographed at an angle
593
+
594
+ >>> import numpy as np
595
+ >>> import torch
596
+ >>> from doctr.transforms import RandomPerspective
597
+ >>> from doctr.utils import Sample
598
+ >>> transfo = RandomPerspective(distortion=0.2)
599
+ >>> out = transfo(Sample(image=torch.rand((3, 64, 64)), target=np.array([[0.1, 0.1, 0.5, 0.5]])))
600
+
601
+ Args:
602
+ distortion: maximum relative displacement of every image corner (0.2 = up to 20% of the width / height)
603
+ """
604
+
605
+ def __init__(self, distortion: float = 0.2) -> None:
606
+ super().__init__()
607
+ self.distortion = distortion
608
+
609
+ def __call__(self, sample: Sample) -> Sample:
610
+ img, target, mask = sample.image, sample.target, sample.mask
611
+ if target is None:
612
+ w_img, _, w_mask = perspective_sample(img, np.zeros((0, 4), dtype=np.float32), self.distortion, mask)
613
+ return sample.replace(image=w_img, mask=w_mask)
614
+ if isinstance(target, dict):
615
+ # Same random warp for every class: the corners are drawn from numpy's RNG, so restoring its state
616
+ # before every class reproduces the same transformation for the image and each geometry array
617
+ state = np.random.get_state()
618
+ out_target: dict[str, np.ndarray] = {}
619
+ w_img, w_mask = img, mask
620
+ for cls_name, arr in target.items():
621
+ np.random.set_state(state)
622
+ w_img, w_arr, w_mask = perspective_sample(img, arr, self.distortion, mask)
623
+ out_target[cls_name] = w_arr
624
+ return sample.replace(image=w_img, mask=w_mask, target=out_target)
625
+ w_img, w_target, w_mask = perspective_sample(img, target, self.distortion, mask)
626
+ return sample.replace(image=w_img, mask=w_mask, target=w_target)
627
+
628
+ def extra_repr(self) -> str:
629
+ return f"distortion={self.distortion}"
doctr/utils/data.py CHANGED
@@ -11,6 +11,7 @@ import os
11
11
  import re
12
12
  import urllib.error
13
13
  import urllib.request
14
+ import uuid
14
15
  from pathlib import Path
15
16
 
16
17
  from tqdm.auto import tqdm
@@ -21,19 +22,29 @@ logger = logging.getLogger(__name__)
21
22
 
22
23
 
23
24
  # matches bfd8deac from resnet18-bfd8deac.ckpt
24
- HASH_REGEX = re.compile(r"-([a-f0-9]*)\.")
25
+ # Hash prefix at the end of a file name (e.g. "db_resnet50-79bd7d70.pt"), shorter runs like "-10." are not hashes
26
+ HASH_REGEX = re.compile(r"-([a-f0-9]{8,})\.")
25
27
  USER_AGENT = "mindee/doctr"
26
28
 
27
29
 
28
30
  def _urlretrieve(url: str, filename: Path | str, chunk_size: int = 1024) -> None:
29
- with open(filename, "wb") as fh:
30
- with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": USER_AGENT})) as response:
31
- with tqdm(total=response.length) as pbar:
32
- for chunk in iter(lambda: response.read(chunk_size), ""):
33
- if not chunk:
34
- break
35
- pbar.update(chunk_size)
36
- fh.write(chunk)
31
+ # Download to a temporary file first: an interrupted download must not leave a truncated file
32
+ # behind, which would then be reused as is by the next call when there is no hash to check.
33
+ # The name is unique to each call, so that concurrent downloads of the same file do not share it
34
+ tmp_path = Path(f"{filename}.{uuid.uuid4().hex}.part")
35
+ try:
36
+ with open(tmp_path, "wb") as fh:
37
+ with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": USER_AGENT})) as response:
38
+ with tqdm(total=response.length) as pbar:
39
+ for chunk in iter(lambda: response.read(chunk_size), ""):
40
+ if not chunk:
41
+ break
42
+ pbar.update(chunk_size)
43
+ fh.write(chunk)
44
+ os.replace(tmp_path, filename)
45
+ except BaseException:
46
+ tmp_path.unlink(missing_ok=True)
47
+ raise
37
48
 
38
49
 
39
50
  def _check_integrity(file_path: str | Path, hash_prefix: str) -> bool: