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
doctr/models/_utils.py CHANGED
@@ -3,17 +3,107 @@
3
3
  # This program is licensed under the Apache License 2.0.
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
- from math import floor
6
+ import heapq
7
+ from collections.abc import Callable, Iterable, Sequence
8
+ from math import ceil, floor, isnan
7
9
  from statistics import median_low
8
- from typing import Any
10
+ from typing import Any, Literal, TypeAlias, TypeVar
9
11
 
10
12
  import cv2
11
13
  import numpy as np
12
14
  from langdetect import LangDetectException, detect_langs
13
15
 
14
16
  from doctr.utils.geometry import rotate_image
17
+ from doctr.utils.multithreading import prefetch_chunks
18
+
19
+ __all__ = [
20
+ "ConfidenceAggregation",
21
+ "aggregate_confidence",
22
+ "estimate_orientation",
23
+ "get_language",
24
+ "invert_data_structure",
25
+ "mask_boxes",
26
+ "rectify_crops",
27
+ "rectify_loc_preds",
28
+ ]
29
+
30
+ ConfidenceAggregation: TypeAlias = (
31
+ Literal["mean", "min", "max", "median", "geometric_mean", "harmonic_mean"] | Callable[[np.ndarray], float]
32
+ )
33
+
34
+
35
+ def _geometric_mean(scores: np.ndarray) -> float:
36
+ # numerically stable form of prod(scores) ** (1 / N), a zero score yields 0
37
+ with np.errstate(divide="ignore"):
38
+ return float(np.exp(np.mean(np.log(scores, dtype=np.float64))))
39
+
40
+
41
+ def _harmonic_mean(scores: np.ndarray) -> float:
42
+ # a zero score yields 0
43
+ with np.errstate(divide="ignore"):
44
+ return float(scores.size / np.sum(1.0 / scores.astype(np.float64)))
45
+
46
+
47
+ _CONFIDENCE_AGGREGATIONS: dict[str, Callable[[np.ndarray], Any]] = {
48
+ "mean": np.mean,
49
+ "min": np.min,
50
+ "max": np.max,
51
+ "median": np.median,
52
+ "geometric_mean": _geometric_mean,
53
+ "harmonic_mean": _harmonic_mean,
54
+ }
55
+
56
+
57
+ def _resolve_confidence_aggregation(method: ConfidenceAggregation) -> Callable[[np.ndarray], Any]:
58
+ """Return the function of a confidence aggregation method, raise a `ValueError` if it is unknown"""
59
+ if callable(method):
60
+ return method
61
+ # the type check comes first: an unhashable value (e.g. a list) can not be looked up
62
+ if not isinstance(method, str) or method not in _CONFIDENCE_AGGREGATIONS:
63
+ raise ValueError(
64
+ f"Unknown confidence aggregation {method!r}, expected a callable or one of {list(_CONFIDENCE_AGGREGATIONS)}"
65
+ )
66
+ return _CONFIDENCE_AGGREGATIONS[method]
67
+
68
+
69
+ def _confidence_aggregation_repr(method: ConfidenceAggregation) -> str:
70
+ """Return the name of a confidence aggregation method to display it in a `repr`"""
71
+ return repr(method) if isinstance(method, str) else getattr(method, "__name__", type(method).__name__)
72
+
73
+
74
+ def aggregate_confidence(
75
+ scores: np.ndarray | Sequence[float],
76
+ method: ConfidenceAggregation = "mean",
77
+ ) -> float:
78
+ """Aggregate several scores (e.g. the character probabilities of a word) into a single confidence score
79
+
80
+ >>> from doctr.models._utils import aggregate_confidence
81
+ >>> aggregate_confidence([0.99, 0.98, 0.12, 0.99], "min")
82
+ 0.12
83
+
84
+ Available methods:
85
+ - "mean": arithmetic mean, a single low score can be hidden by many high ones
86
+ - "min": the lowest score, a single low score is enough to lower the confidence
87
+ - "max": the highest score
88
+ - "median": the median score, robust to outliers
89
+ - "geometric_mean": `exp(mean(log(scores)))`, i.e. the exponential of the average log-probability
90
+ - "harmonic_mean": strongly penalizes low scores
91
+ - a Python callable taking the 1D array of scores and returning a float
92
+
93
+ Args:
94
+ scores: the scores to aggregate, expected in [0, 1]
95
+ method: the aggregation method
15
96
 
16
- __all__ = ["estimate_orientation", "get_language", "invert_data_structure"]
97
+ Returns:
98
+ the aggregated confidence clipped to [0, 1], 0 if there is no score or if the aggregation is NaN (e.g. a
99
+ callable averaging an empty selection)
100
+ """
101
+ aggregate = _resolve_confidence_aggregation(method)
102
+ scores = np.asarray(scores).ravel()
103
+ if scores.size == 0:
104
+ return 0.0
105
+ value = float(np.asarray(aggregate(scores)).squeeze())
106
+ return 0.0 if isnan(value) else min(max(value, 0.0), 1.0)
17
107
 
18
108
 
19
109
  def get_max_width_length_ratio(contour: np.ndarray) -> float:
@@ -43,7 +133,7 @@ def estimate_orientation(
43
133
  lines of the document and the assumption that they should be horizontal.
44
134
 
45
135
  Args:
46
- img: the img or bitmap to analyze (H, W, C)
136
+ img: the img (in np.uint8, or as floats in [0, 1]) or bitmap to analyze (H, W, C)
47
137
  general_page_orientation: the general orientation of the page (angle [0, 90, 180, 270 (-90)], confidence)
48
138
  estimated by a model
49
139
  n_ct: the number of contours used for the orientation estimation
@@ -58,7 +148,10 @@ def estimate_orientation(
58
148
 
59
149
  # Convert image to grayscale if necessary
60
150
  if img.shape[-1] == 3:
61
- gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
151
+ if np.issubdtype(img.dtype, np.floating):
152
+ # Otsu thresholding needs 8-bit values: a float image holds values in [0, 1]
153
+ img = (img * 255).round().clip(0, 255).astype(np.uint8)
154
+ gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
62
155
  gray_img = cv2.medianBlur(gray_img, 5)
63
156
  thresh = cv2.threshold(gray_img, thresh=0, maxval=255, type=cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
64
157
  else:
@@ -83,15 +176,15 @@ def estimate_orientation(
83
176
  # extract contours
84
177
  contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
85
178
 
86
- # Filter & Sort contours
87
- contours = sorted(
88
- [contour for contour in contours if cv2.contourArea(contour) > lower_area],
179
+ # Filter contours & keep the n_ct most elongated ones
180
+ contours = heapq.nlargest(
181
+ n_ct,
182
+ (contour for contour in contours if cv2.contourArea(contour) > lower_area),
89
183
  key=get_max_width_length_ratio,
90
- reverse=True,
91
184
  )
92
185
 
93
186
  angles = []
94
- for contour in contours[:n_ct]:
187
+ for contour in contours:
95
188
  _, (w, h), angle = cv2.minAreaRect(contour)
96
189
 
97
190
  # OpenCV version-proof normalization: force 'w' to be the long side
@@ -210,6 +303,46 @@ def get_language(text: str) -> tuple[str, float]:
210
303
  return lang.lang, lang.prob
211
304
 
212
305
 
306
+ def mask_boxes(img: np.ndarray, boxes: np.ndarray, fill_value: int = 255) -> np.ndarray:
307
+ """Blank out regions of an image by filling the given boxes with a constant value.
308
+
309
+ Handles both box formats produced by the models: straight boxes of shape `(N, 4)` in
310
+ `(x_min, y_min, x_max, y_max)` form and rotated 4-point polygons of shape `(N, 4, 2)`, with
311
+ coordinates relative to the image size.
312
+
313
+ Args:
314
+ img: the image to mask, shape `(H, W)` or `(H, W, C)`
315
+ boxes: relative coordinates of the regions to fill, shape `(N, 4)` or `(N, 4, 2)`
316
+ fill_value: pixel value used to fill the masked regions
317
+
318
+ Returns:
319
+ a copy of the image with the boxes filled (the input is left untouched)
320
+ """
321
+ boxes = np.asarray(boxes, dtype=np.float32)
322
+ if boxes.size == 0:
323
+ return img
324
+
325
+ h, w = img.shape[:2]
326
+ if boxes.ndim == 2: # straight boxes (N, 4) -> (N, 4, 2) corner polygons
327
+ polys = np.empty((boxes.shape[0], 4, 2), dtype=np.float32)
328
+ polys[:, 0] = boxes[:, [0, 1]] # (x_min, y_min)
329
+ polys[:, 1] = boxes[:, [2, 1]] # (x_max, y_min)
330
+ polys[:, 2] = boxes[:, [2, 3]] # (x_max, y_max)
331
+ polys[:, 3] = boxes[:, [0, 3]] # (x_min, y_max)
332
+ else: # rotated polygons (N, 4, 2)
333
+ polys = boxes.copy()
334
+
335
+ # relative -> absolute pixel corners, clipped to the image
336
+ polys[..., 0] = np.clip(polys[..., 0] * w, 0, w)
337
+ polys[..., 1] = np.clip(polys[..., 1] * h, 0, h)
338
+ polys = polys.round().astype(np.int32)
339
+
340
+ img = img.copy()
341
+ color = (int(fill_value),) * (img.shape[2] if img.ndim == 3 else 1)
342
+ cv2.fillPoly(img, list(polys), color=color)
343
+ return img
344
+
345
+
213
346
  def invert_data_structure(
214
347
  x: list[dict[str, Any]] | dict[str, list[Any]],
215
348
  ) -> list[dict[str, Any]] | dict[str, list[Any]]:
@@ -222,9 +355,69 @@ def invert_data_structure(
222
355
  dictionary of list when x is a list of dictionaries or a list of dictionaries when x is dictionary of lists
223
356
  """
224
357
  if isinstance(x, dict):
225
- assert len({len(v) for v in x.values()}) == 1, "All the lists in the dictionary should have the same length."
358
+ assert len({len(v) for v in x.values()}) <= 1, "All the lists in the dictionary should have the same length."
226
359
  return [dict(zip(x, t)) for t in zip(*x.values())]
227
360
  elif isinstance(x, list):
228
- return {k: [dic[k] for dic in x] for k in x[0]}
361
+ return {k: [dic[k] for dic in x] for k in x[0]} if x else {}
229
362
  else:
230
- raise TypeError(f"Expected input to be either a dict or a list, got {type(input)} instead.")
363
+ raise TypeError(f"Expected input to be either a dict or a list, got {type(x)} instead.")
364
+
365
+
366
+ _Output = TypeVar("_Output")
367
+
368
+
369
+ def merge_items(outputs: list[list[Any]]) -> list[Any]:
370
+ """Concatenate the outputs of several chunks, for predictors returning one item per input"""
371
+ return [item for output in outputs for item in output]
372
+
373
+
374
+ def merge_columns(outputs: list[Any]) -> Any:
375
+ """Concatenate the outputs of several chunks column by column, for predictors returning several aligned lists
376
+ (e.g. `[class_idxs, classes, probs]`, or `(preds, seg_maps)`): the container type is kept"""
377
+ columns = [merge_items([output[col] for output in outputs]) for col in range(len(outputs[0]))]
378
+ return tuple(columns) if isinstance(outputs[0], tuple) else columns
379
+
380
+
381
+ def predict_by_chunks(
382
+ predict: Callable[[list[np.ndarray]], _Output],
383
+ inputs: Sequence[np.ndarray] | Iterable[np.ndarray],
384
+ chunk_size: int,
385
+ batch_size: int = 1,
386
+ merge: Callable[[list[_Output]], _Output] = merge_items, # type: ignore[assignment]
387
+ ) -> _Output:
388
+ """Run a predictor on inputs of any length: a lazy page source (cf. `DocumentFile.from_pdf(..., lazy=True)`), a
389
+ list, a tuple or any iterable of images
390
+
391
+ Lists and tuples of at most `chunk_size` images, as well as arrays (a batch already in memory), are processed at
392
+ once, exactly as before. Anything else is processed chunk by chunk, the next chunk of a lazy source being decoded
393
+ in a background thread, so that the memory footprint does not grow with the number of inputs.
394
+
395
+ The chunk size is rounded up to a multiple of `batch_size`: the model then processes the same batches as in a
396
+ single pass, so that chunking does not change the predictions (a predictor transforming its inputs before batching,
397
+ e.g. the recognition predictor splitting wide crops, does so within each chunk).
398
+
399
+ Args:
400
+ predict: the prediction function, taking a list of images
401
+ inputs: the images
402
+ chunk_size: the maximum number of images decoded and processed at once
403
+ batch_size: the batch size of the model
404
+ merge: the function concatenating the outputs of the chunks
405
+
406
+ Returns:
407
+ the output of `predict` on the whole input
408
+ """
409
+ if isinstance(inputs, np.ndarray):
410
+ return predict(inputs) # type: ignore[arg-type]
411
+ if isinstance(inputs, (list, tuple)) and len(inputs) <= chunk_size:
412
+ return predict(list(inputs))
413
+ size = ceil(chunk_size / batch_size) * batch_size
414
+ outputs = []
415
+ chunks = prefetch_chunks(inputs, size)
416
+ try:
417
+ for chunk in chunks:
418
+ outputs.append(predict(chunk))
419
+ finally:
420
+ # Stop decoding ahead on error
421
+ chunks.close()
422
+ # An empty input yields no chunk: let the predictor return its empty output
423
+ return merge(outputs) if outputs else predict([])