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,132 @@
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 collections.abc import Iterable, Sequence
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torch import nn
12
+
13
+ from doctr.models._utils import predict_by_chunks
14
+ from doctr.models.preprocessor import PreProcessor
15
+ from doctr.models.utils import set_device_and_dtype
16
+ from doctr.utils.geometry import extract_crops, extract_rcrops
17
+
18
+ __all__ = ["FormulaPredictor"]
19
+
20
+
21
+ def _crop_region(page: np.ndarray, region: np.ndarray) -> np.ndarray | None:
22
+ """Crop a page-relative region, a straight box (4,) or a polygon (4, 2), None for a degenerate region"""
23
+ region = np.asarray(region, dtype=np.float32)
24
+ if region.ndim == 1:
25
+ crop = extract_crops(page, np.clip(region, 0, 1)[None])[0]
26
+ else:
27
+ crop = extract_rcrops(page, np.clip(region, 0, 1)[None], assume_horizontal=False)[0]
28
+ return crop if crop.shape[0] >= 2 and crop.shape[1] >= 2 else None
29
+
30
+
31
+ class FormulaPredictor(nn.Module):
32
+ """Implements an object able to recognize mathematical formulas as LaTeX strings
33
+
34
+ Each formula image is resized (keeping its aspect ratio), padded and normalized. The margins around a formula
35
+ (e.g. of a layout region) are kept: the model is trained to read formulas with margins.
36
+
37
+ Args:
38
+ pre_processor: transform inputs for easier batched model inference
39
+ model: core formula recognition architecture
40
+ chunk_size: the maximum number of formula images decoded and processed at once (128 by default). Longer
41
+ inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
42
+ chunk by chunk, with a memory footprint that does not grow with the number of images. It is rounded
43
+ up to a multiple of the batch size, so that the predictions are the same as in a single pass.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ pre_processor: PreProcessor,
49
+ model: nn.Module,
50
+ chunk_size: int = 128,
51
+ ) -> None:
52
+ super().__init__()
53
+ self.pre_processor = pre_processor
54
+ self.model = model.eval()
55
+ if chunk_size < 1:
56
+ raise ValueError("`chunk_size` must be a positive integer")
57
+ self.chunk_size = chunk_size
58
+
59
+ @torch.inference_mode()
60
+ def forward(
61
+ self,
62
+ crops: Sequence[np.ndarray] | Iterable[np.ndarray],
63
+ **kwargs: Any,
64
+ ) -> list[tuple[str, float]]:
65
+ """Recognize the formula of each image
66
+
67
+ Args:
68
+ crops: a list of formula images (numpy arrays of shape H x W x C), a lazy page source
69
+ (cf. `DocumentFile.from_images(..., lazy=True)`) or any iterable of images
70
+ **kwargs: keyword arguments forwarded to the model
71
+
72
+ Returns:
73
+ the LaTeX string (tokens separated by spaces) and the confidence of each image
74
+ """
75
+ return predict_by_chunks(
76
+ lambda chunk: self._predict(chunk, **kwargs), crops, self.chunk_size, self.pre_processor.batch_size
77
+ )
78
+
79
+ @torch.inference_mode()
80
+ def _predict(self, crops: Sequence[np.ndarray], **kwargs: Any) -> list[tuple[str, float]]:
81
+ if len(crops) == 0:
82
+ return []
83
+ # Dimension check
84
+ if any(crop.ndim != 3 for crop in crops):
85
+ raise ValueError("incorrect input shape: all crops are expected to be multi-channel 2D images.")
86
+ empty = next((crop for crop in crops if not all(s > 0 for s in crop.shape)), None)
87
+ if empty is not None:
88
+ raise ValueError(f"incorrect input shape: crops are expected to be non-empty, got shape {empty.shape}.")
89
+
90
+ processed_batches = self.pre_processor(list(crops))
91
+ _params = next(self.model.parameters())
92
+ self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
93
+ self.model, processed_batches, _params.device, _params.dtype
94
+ )
95
+ raw = [self.model(batch, return_preds=True, **kwargs)["preds"] for batch in processed_batches]
96
+ return [pred for batch in raw for pred in batch]
97
+
98
+ @torch.inference_mode()
99
+ def predict_regions(
100
+ self,
101
+ pages: list[np.ndarray],
102
+ regions: list[dict[str, Any] | None],
103
+ class_name: str = "Formula",
104
+ **kwargs: Any,
105
+ ) -> list[list[dict[str, Any]]]:
106
+ """Recognize the formulas a layout model located on pages
107
+
108
+ Args:
109
+ pages: the page images
110
+ regions: the per-page layout predictions `{"class_names", "boxes", "scores"}` (None for none)
111
+ class_name: the layout class of the formula regions
112
+ **kwargs: keyword arguments forwarded to the model
113
+
114
+ Returns:
115
+ a per-page list of formulas `{"geometry", "value", "confidence", "score"}`, with the geometry of the
116
+ layout region (page-relative) and its layout score
117
+ """
118
+ crops: list[np.ndarray] = []
119
+ meta: list[tuple[int, np.ndarray, float | None]] = []
120
+ for p_idx, (page, region) in enumerate(zip(pages, regions)):
121
+ region = region or {}
122
+ scores = region.get("scores")
123
+ for r_idx, (cls_name, box) in enumerate(zip(region.get("class_names", []), region.get("boxes", []))):
124
+ crop = _crop_region(page, box) if cls_name == class_name else None
125
+ if crop is not None:
126
+ crops.append(crop)
127
+ meta.append((p_idx, np.asarray(box), None if scores is None else float(scores[r_idx])))
128
+
129
+ formulas: list[list[dict[str, Any]]] = [[] for _ in pages]
130
+ for (p_idx, box, score), (latex, confidence) in zip(meta, self(crops, **kwargs) if crops else []):
131
+ formulas[p_idx].append({"geometry": box, "value": latex, "confidence": confidence, "score": score})
132
+ return formulas
@@ -0,0 +1,102 @@
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
+ from doctr.models.utils import _CompiledModule
9
+
10
+ from .. import formula
11
+ from .._utils import ConfidenceAggregation, _resolve_confidence_aggregation
12
+ from ..preprocessor import PreProcessor
13
+ from .predictor import FormulaPredictor
14
+
15
+ __all__ = ["formula_predictor"]
16
+
17
+ ARCHS: list[str] = ["formulanet"]
18
+
19
+
20
+ def _predictor(
21
+ arch: Any,
22
+ pretrained: bool,
23
+ confidence_aggregation: ConfidenceAggregation | None = None,
24
+ max_decode_length: int | None = None,
25
+ **kwargs: Any,
26
+ ) -> FormulaPredictor:
27
+ if confidence_aggregation is not None:
28
+ _resolve_confidence_aggregation(confidence_aggregation)
29
+
30
+ if isinstance(arch, str):
31
+ if arch not in ARCHS:
32
+ raise ValueError(f"unknown architecture '{arch}'")
33
+ _model = formula.__dict__[arch](
34
+ pretrained=pretrained, pretrained_backbone=kwargs.get("pretrained_backbone", True)
35
+ )
36
+ else:
37
+ # Adding the type for torch compiled models to the allowed architectures
38
+ allowed_archs = [formula.FormulaNet, _CompiledModule]
39
+ if not isinstance(arch, tuple(allowed_archs)):
40
+ raise ValueError(f"unknown architecture: {type(arch)}")
41
+ _model = arch
42
+
43
+ if confidence_aggregation is not None:
44
+ _model.postprocessor.confidence_aggregation = confidence_aggregation
45
+ if max_decode_length is not None:
46
+ _model.max_decode_length = max_decode_length
47
+
48
+ kwargs.pop("pretrained_backbone", None)
49
+ kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
50
+ kwargs["std"] = kwargs.get("std", _model.cfg["std"])
51
+ kwargs["batch_size"] = kwargs.get("batch_size", 16)
52
+ chunk_size = kwargs.pop("chunk_size", 128)
53
+ # Same resizing as during training: aspect ratio preserved, padded at the bottom-right
54
+ kwargs.setdefault("symmetric_pad", False)
55
+ predictor = FormulaPredictor(
56
+ PreProcessor(_model.cfg["input_shape"][1:], preserve_aspect_ratio=True, **kwargs),
57
+ _model,
58
+ chunk_size=chunk_size,
59
+ )
60
+ return predictor
61
+
62
+
63
+ def formula_predictor(
64
+ arch: Any = "formulanet",
65
+ pretrained: bool = False,
66
+ batch_size: int = 16,
67
+ confidence_aggregation: ConfidenceAggregation | None = None,
68
+ max_decode_length: int | None = None,
69
+ **kwargs: Any,
70
+ ) -> FormulaPredictor:
71
+ """Formula recognition architecture: turns images of mathematical formulas into LaTeX strings.
72
+
73
+ >>> import numpy as np
74
+ >>> from doctr.models import formula_predictor
75
+ >>> model = formula_predictor(arch='formulanet', pretrained=True)
76
+ >>> input_crop = (255 * np.random.rand(64, 256, 3)).astype(np.uint8)
77
+ >>> out = model([input_crop])
78
+
79
+ Args:
80
+ arch: name of the architecture or model itself to use (e.g. 'formulanet')
81
+ pretrained: If True, returns a model pre-trained on a formula recognition dataset
82
+ batch_size: number of samples the model processes in parallel
83
+ confidence_aggregation: aggregation method of the token probabilities into the formula confidence:
84
+ "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a callable. If None, the one of
85
+ the model is kept ("mean" by default)
86
+ max_decode_length: maximum number of tokens generated per formula. If None, the one of the model is kept
87
+ (2048 by default). A model instance passed as `arch` is modified.
88
+ chunk_size: maximum number of formula images decoded and processed at once (128 by default): longer inputs and
89
+ lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
90
+ **kwargs: optional keyword arguments passed to the architecture
91
+
92
+ Returns:
93
+ Formula recognition predictor
94
+ """
95
+ return _predictor(
96
+ arch=arch,
97
+ pretrained=pretrained,
98
+ batch_size=batch_size,
99
+ confidence_aggregation=confidence_aggregation,
100
+ max_decode_length=max_decode_length,
101
+ **kwargs,
102
+ )
@@ -3,8 +3,10 @@
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 collections.abc import Collection
6
7
  from typing import Any
7
8
 
9
+ from doctr.io.elements import Document, KIEDocument
8
10
  from doctr.models.builder import KIEDocumentBuilder
9
11
 
10
12
  from ..classification.predictor import OrientationPredictor
@@ -26,11 +28,20 @@ class _KIEPredictor(_OCRPredictor):
26
28
  symmetric_pad: if True and preserve_aspect_ratio is True, pas the image symmetrically.
27
29
  detect_orientation: if True, the estimated general page orientation will be added to the predictions for each
28
30
  page. Doing so will slightly deteriorate the overall latency.
31
+ ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
32
+ layout model will be used to locate the regions of the specified classes, and these regions will
33
+ be masked out (filled with black) before passing the pages to the detection/recognition modules.
34
+ preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
35
+ original page coordinates. Useful for redaction and annotation.
36
+ page_chunk_size: the maximum number of pages processed at once for lazy page sources, iterators and
37
+ `stream`, so that the memory footprint does not grow with the number of pages. Lists and tuples of pages
38
+ are processed in a single pass.
29
39
  kwargs: keyword args of `DocumentBuilder`
30
40
  """
31
41
 
32
42
  crop_orientation_predictor: OrientationPredictor | None
33
43
  page_orientation_predictor: OrientationPredictor | None
44
+ _document_cls: type[Document] = KIEDocument
34
45
 
35
46
  def __init__(
36
47
  self,
@@ -39,10 +50,21 @@ class _KIEPredictor(_OCRPredictor):
39
50
  preserve_aspect_ratio: bool = True,
40
51
  symmetric_pad: bool = True,
41
52
  detect_orientation: bool = False,
53
+ ignore_regions: Collection[str] | None = None,
54
+ preserve_original_coords: bool = False,
55
+ page_chunk_size: int = 32,
42
56
  **kwargs: Any,
43
57
  ) -> None:
44
58
  super().__init__(
45
- assume_straight_pages, straighten_pages, preserve_aspect_ratio, symmetric_pad, detect_orientation, **kwargs
59
+ assume_straight_pages,
60
+ straighten_pages,
61
+ preserve_aspect_ratio,
62
+ symmetric_pad,
63
+ detect_orientation,
64
+ ignore_regions,
65
+ preserve_original_coords=preserve_original_coords,
66
+ page_chunk_size=page_chunk_size,
67
+ **kwargs,
46
68
  )
47
69
 
48
70
  # Remove the following arguments from kwargs after initialization of the parent class
@@ -3,15 +3,17 @@
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 collections.abc import Iterable, Sequence
6
7
  from typing import Any
7
8
 
8
9
  import numpy as np
9
10
  import torch
10
11
  from torch import nn
11
12
 
12
- from doctr.io.elements import Document
13
+ from doctr.io.elements import Document, KIEDocument
13
14
  from doctr.models._utils import get_language, invert_data_structure
14
15
  from doctr.models.detection.predictor import DetectionPredictor
16
+ from doctr.models.layout.predictor import LayoutPredictor
15
17
  from doctr.models.recognition.predictor import RecognitionPredictor
16
18
  from doctr.utils.geometry import detach_scores
17
19
 
@@ -35,6 +37,12 @@ class KIEPredictor(nn.Module, _KIEPredictor):
35
37
  page. Doing so will slightly deteriorate the overall latency.
36
38
  detect_language: if True, the language prediction will be added to the predictions for each
37
39
  page. Doing so will slightly deteriorate the overall latency.
40
+ preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
41
+ original page coordinates. Useful for redaction and annotation.
42
+ layout_predictor: optional layout detection module
43
+ page_chunk_size: the maximum number of pages processed at once (32 by default) for lazy page sources
44
+ (cf. `DocumentFile.from_pdf(..., lazy=True)`), iterators and :meth:`stream`, with a memory footprint that
45
+ does not grow with the number of pages. Lists and tuples of pages are processed in a single pass.
38
46
  **kwargs: keyword args of `DocumentBuilder`
39
47
  """
40
48
 
@@ -48,6 +56,8 @@ class KIEPredictor(nn.Module, _KIEPredictor):
48
56
  symmetric_pad: bool = True,
49
57
  detect_orientation: bool = False,
50
58
  detect_language: bool = False,
59
+ preserve_original_coords: bool = False,
60
+ layout_predictor: LayoutPredictor | None = None,
51
61
  **kwargs: Any,
52
62
  ) -> None:
53
63
  nn.Module.__init__(self)
@@ -60,33 +70,67 @@ class KIEPredictor(nn.Module, _KIEPredictor):
60
70
  preserve_aspect_ratio,
61
71
  symmetric_pad,
62
72
  detect_orientation,
73
+ preserve_original_coords=preserve_original_coords,
63
74
  **kwargs,
64
75
  )
65
76
  self.detect_orientation = detect_orientation
66
77
  self.detect_language = detect_language
78
+ self.layout_predictor = layout_predictor.eval() if layout_predictor is not None else None
67
79
 
68
80
  @torch.inference_mode()
69
81
  def forward(
82
+ self,
83
+ pages: Sequence[np.ndarray] | Iterable[np.ndarray],
84
+ **kwargs: Any,
85
+ ) -> Document:
86
+ """Predict on a document
87
+
88
+ Args:
89
+ pages: a list of pages (numpy arrays of shape H x W x C), processed in a single pass, or a lazy page
90
+ source (cf. `DocumentFile.from_pdf(..., lazy=True)`) or any iterable of pages, processed chunk by
91
+ chunk (`page_chunk_size` pages at a time) with a bounded memory footprint
92
+ **kwargs: keyword arguments forwarded to the sub-predictors, and `on_error` for lazy page sources
93
+ (cf. :meth:`stream`): "skip" leaves out the pages that cannot be read instead of raising an error
94
+
95
+ Returns:
96
+ the predicted document
97
+ """
98
+ return self._run(pages, **kwargs)
99
+
100
+ @torch.inference_mode()
101
+ def _predict_pages(
70
102
  self,
71
103
  pages: list[np.ndarray],
72
104
  **kwargs: Any,
73
105
  ) -> Document:
106
+ if len(pages) == 0:
107
+ return KIEDocument(pages=[])
108
+
74
109
  # Dimension check
75
110
  if any(page.ndim != 3 for page in pages):
76
111
  raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
77
112
 
78
113
  origin_page_shapes = [page.shape[:2] for page in pages]
79
114
 
80
- # Localize text elements
81
- loc_preds, out_maps = self.det_predictor(pages, return_maps=True, **kwargs)
115
+ if not self.straighten_pages:
116
+ # Detect layout regions on the pages
117
+ regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
118
+ det_pages = self._mask_regions(pages, regions)
119
+ else:
120
+ det_pages = pages
121
+
122
+ # Localize text elements (segmentation maps are only materialized when actually consumed)
123
+ if self.detect_orientation or self.straighten_pages:
124
+ loc_preds, out_maps = self.det_predictor(det_pages, return_maps=True, **kwargs)
125
+ bin_thresh = kwargs.get("bin_thresh", getattr(self.det_predictor.model.postprocessor, "bin_thresh", 0.3))
126
+ seg_maps = [
127
+ ((np.expand_dims(np.amax(out_map, axis=-1), axis=-1) > bin_thresh).astype(np.uint8) * 255)
128
+ for out_map in out_maps
129
+ ]
130
+ else:
131
+ loc_preds = self.det_predictor(det_pages, **kwargs)
82
132
 
83
133
  # Detect document rotation and rotate pages
84
- seg_maps = [
85
- np.where(np.expand_dims(np.amax(out_map, axis=-1), axis=-1) > kwargs.get("bin_thresh", 0.3), 255, 0).astype(
86
- np.uint8
87
- )
88
- for out_map in out_maps
89
- ]
90
134
  if self.detect_orientation:
91
135
  general_pages_orientations, origin_pages_orientations = self._get_orientations(pages, seg_maps)
92
136
  orientations = [
@@ -97,12 +141,21 @@ class KIEPredictor(nn.Module, _KIEPredictor):
97
141
  general_pages_orientations = None
98
142
  origin_pages_orientations = None
99
143
  if self.straighten_pages:
100
- pages = self._straighten_pages(pages, seg_maps, general_pages_orientations, origin_pages_orientations)
144
+ _orig_shapes = origin_page_shapes
145
+ _orig_pages = list(pages)
146
+ pages, m_invs = self._straighten_pages(
147
+ pages, seg_maps, general_pages_orientations, origin_pages_orientations
148
+ )
101
149
  # update page shapes after straightening
102
150
  origin_page_shapes = [page.shape[:2] for page in pages]
151
+ _straight_shapes = origin_page_shapes
152
+
153
+ # Detect layout regions on the pages
154
+ regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
155
+ det_pages = self._mask_regions(pages, regions)
103
156
 
104
157
  # Forward again to get predictions on straight pages
105
- loc_preds = self.det_predictor(pages, **kwargs)
158
+ loc_preds = self._detect_straightened(loc_preds, _orig_pages, pages, det_pages, **kwargs)
106
159
 
107
160
  dict_loc_preds: dict[str, list[np.ndarray]] = invert_data_structure(loc_preds) # type: ignore[assignment]
108
161
 
@@ -113,19 +166,33 @@ class KIEPredictor(nn.Module, _KIEPredictor):
113
166
  dict_loc_preds[class_name] = _loc_preds
114
167
  objectness_scores[class_name] = _scores
115
168
 
116
- # Apply hooks to loc_preds if any
117
- for hook in self.hooks:
118
- dict_loc_preds = hook(dict_loc_preds)
169
+ # Apply hooks to loc_preds if any, before the crops are extracted so that the hooked boxes are read
170
+ if self.hooks:
171
+ # Pass a copy, so that a hook modifying its input in place does not alter the reference
172
+ hooked_preds: Any = {class_name: list(preds) for class_name, preds in dict_loc_preds.items()}
173
+ for hook in self.hooks:
174
+ hooked_preds = hook(hooked_preds)
175
+ if not isinstance(hooked_preds, dict) or set(hooked_preds) != set(dict_loc_preds):
176
+ raise ValueError(
177
+ "hooks of the KIE predictor must return a dict with the same classes as their input: "
178
+ f"{sorted(dict_loc_preds)}"
179
+ )
180
+ for class_name in dict_loc_preds.keys():
181
+ dict_loc_preds[class_name], objectness_scores[class_name] = self._align_hook_output(
182
+ dict_loc_preds[class_name], hooked_preds[class_name], objectness_scores[class_name]
183
+ )
119
184
 
120
185
  # Crop images
121
186
  crops = {}
122
187
  for class_name in dict_loc_preds.keys():
123
- crops[class_name], dict_loc_preds[class_name] = self._prepare_crops(
188
+ crops[class_name], dict_loc_preds[class_name], objectness_scores[class_name] = self._prepare_crops(
124
189
  pages,
125
190
  dict_loc_preds[class_name],
191
+ objectness_scores[class_name],
126
192
  assume_straight_pages=self.assume_straight_pages,
127
193
  assume_horizontal=self._page_orientation_disabled,
128
194
  )
195
+
129
196
  # Rectify crop orientation
130
197
  crop_orientations: Any = {}
131
198
  if not self.assume_straight_pages:
@@ -173,7 +240,12 @@ class KIEPredictor(nn.Module, _KIEPredictor):
173
240
  crop_orientations_per_page,
174
241
  orientations,
175
242
  languages_dict,
243
+ regions,
176
244
  )
245
+
246
+ # manipulate the already built Document to restore the original pages / shapes and geometries
247
+ if self.straighten_pages and self.preserve_original_coords:
248
+ out = self._remap_to_original_coords(out, _orig_shapes, _straight_shapes, m_invs, _orig_pages) # type: ignore[assignment]
177
249
  return out
178
250
 
179
251
  @staticmethod
@@ -0,0 +1,2 @@
1
+ from .zoo import *
2
+ from .lw_detr import *
@@ -0,0 +1 @@
1
+ from .pytorch import *