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
@@ -92,8 +92,6 @@ class LinkNetPostProcessor(DetectionPostProcessor):
92
92
  Args:
93
93
  pred: Pred map from differentiable linknet output
94
94
  bitmap: Bitmap map computed from pred (binarized)
95
- angle_tol: Comparison tolerance of the angle with the median angle across the page
96
- ratio_tol: Under this limit aspect ratio, we cannot resolve the direction of the crop
97
95
 
98
96
  Returns:
99
97
  np tensor boxes for the bitmap, each box is a 6-element list
@@ -154,6 +152,8 @@ class _LinkNet(BaseModel):
154
152
 
155
153
  min_size_box: int = 3
156
154
  assume_straight_pages: bool = True
155
+ mask_empty_classes: bool = False
156
+ class_names: list[str] # set by the framework model
157
157
  shrink_ratio = 0.5
158
158
 
159
159
  def build_target(
@@ -185,10 +185,22 @@ class _LinkNet(BaseModel):
185
185
  seg_mask: np.ndarray = np.ones(target_shape, dtype=bool)
186
186
 
187
187
  for idx, tgt in enumerate(target):
188
- for class_idx, _tgt in enumerate(tgt.values()):
188
+ unknown = set(tgt) - set(self.class_names)
189
+ missing = set(self.class_names) - set(tgt)
190
+ if unknown or missing:
191
+ raise ValueError(
192
+ f"target classes {sorted(tgt)} do not match the model classes {list(self.class_names)}"
193
+ + (f" (unknown: {sorted(unknown)})" if unknown else "")
194
+ + (f" (missing: {sorted(missing)})" if missing else "")
195
+ )
196
+ # Channels follow the order of the model's class names, whatever the order of the target dict
197
+ for class_idx, class_name in enumerate(self.class_names):
198
+ _tgt = tgt[class_name]
189
199
  # Draw each polygon on gt
190
- if _tgt.shape[0] == 0:
191
- # Empty image, full masked
200
+ if _tgt.shape[0] == 0 and self.mask_empty_classes:
201
+ # No box for this class: with `mask_empty_classes` the channel is ignored by the loss (partially
202
+ # annotated data); by default it is supervised as background, an image without any box being
203
+ # a true negative
192
204
  seg_mask[idx, class_idx] = False
193
205
 
194
206
  # Absolute bounding boxes
@@ -98,6 +98,8 @@ class LinkNet(nn.Module, _LinkNet):
98
98
  exportable: onnx exportable returns only logits
99
99
  cfg: the configuration dict of the model
100
100
  class_names: list of class names
101
+ mask_empty_classes: if True, a class without any box in an image is masked out of the loss (use it for
102
+ partially annotated data); by default the absence is supervised as background
101
103
  """
102
104
 
103
105
  def __init__(
@@ -110,9 +112,11 @@ class LinkNet(nn.Module, _LinkNet):
110
112
  exportable: bool = False,
111
113
  cfg: dict[str, Any] | None = None,
112
114
  class_names: list[str] = [CLASS_NAME],
115
+ mask_empty_classes: bool = False,
113
116
  ) -> None:
114
117
  super().__init__()
115
118
  self.class_names = class_names
119
+ self.mask_empty_classes = mask_empty_classes
116
120
  num_classes: int = len(self.class_names)
117
121
  self.cfg = cfg
118
122
  self.exportable = exportable
@@ -235,6 +239,9 @@ class LinkNet(nn.Module, _LinkNet):
235
239
  seg_target, seg_mask = torch.from_numpy(_target).to(dtype=out_map.dtype), torch.from_numpy(_mask)
236
240
  seg_target, seg_mask = seg_target.to(out_map.device), seg_mask.to(out_map.device)
237
241
  seg_mask = seg_mask.to(dtype=torch.float32)
242
+ if not torch.any(seg_mask):
243
+ # Fully masked batch: nothing to supervise
244
+ return out_map.sum() * 0
238
245
 
239
246
  bce_loss = F.binary_cross_entropy_with_logits(out_map, seg_target, reduction="none")
240
247
  proba_map = torch.sigmoid(out_map)
@@ -3,12 +3,15 @@
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
7
+ from functools import partial
6
8
  from typing import Any
7
9
 
8
10
  import numpy as np
9
11
  import torch
10
12
  from torch import nn
11
13
 
14
+ from doctr.models._utils import merge_columns, merge_items, predict_by_chunks
12
15
  from doctr.models.detection._utils import _remove_padding
13
16
  from doctr.models.preprocessor import PreProcessor
14
17
  from doctr.models.utils import set_device_and_dtype
@@ -22,24 +25,61 @@ class DetectionPredictor(nn.Module):
22
25
  Args:
23
26
  pre_processor: transform inputs for easier batched model inference
24
27
  model: core detection architecture
28
+ chunk_size: the maximum number of pages decoded and processed at once (32 by default). Longer
29
+ inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
30
+ chunk by chunk, with a memory footprint that does not grow with the number of pages. It is rounded
31
+ up to a multiple of the batch size, so that the predictions are the same as in a single pass.
25
32
  """
26
33
 
27
34
  def __init__(
28
35
  self,
29
36
  pre_processor: PreProcessor,
30
37
  model: nn.Module,
38
+ chunk_size: int = 32,
31
39
  ) -> None:
32
40
  super().__init__()
33
41
  self.pre_processor = pre_processor
34
42
  self.model = model.eval()
43
+ if chunk_size < 1:
44
+ raise ValueError("`chunk_size` must be a positive integer")
45
+ self.chunk_size = chunk_size
35
46
 
36
47
  @torch.inference_mode()
37
48
  def forward(
49
+ self,
50
+ pages: Sequence[np.ndarray] | Iterable[np.ndarray],
51
+ return_maps: bool = False,
52
+ **kwargs: Any,
53
+ ) -> list[dict[str, np.ndarray]] | tuple[list[dict[str, np.ndarray]], list[np.ndarray]]:
54
+ """Localize the text elements of pages
55
+
56
+ Args:
57
+ pages: a list of pages (numpy arrays of shape H x W x C), a lazy page source
58
+ (cf. `DocumentFile.from_pdf(..., lazy=True)`) or any iterable of pages
59
+ return_maps: whether to also return the segmentation map of each page
60
+ **kwargs: keyword arguments forwarded to the model
61
+
62
+ Returns:
63
+ the predictions of each page, and their segmentation maps if `return_maps` is True
64
+ """
65
+ return predict_by_chunks(
66
+ partial(self._predict, return_maps=return_maps, **kwargs),
67
+ pages,
68
+ self.chunk_size,
69
+ self.pre_processor.batch_size,
70
+ merge=merge_columns if return_maps else merge_items,
71
+ )
72
+
73
+ @torch.inference_mode()
74
+ def _predict(
38
75
  self,
39
76
  pages: list[np.ndarray],
40
77
  return_maps: bool = False,
41
78
  **kwargs: Any,
42
79
  ) -> list[dict[str, np.ndarray]] | tuple[list[dict[str, np.ndarray]], list[np.ndarray]]:
80
+ if len(pages) == 0:
81
+ return ([], []) if return_maps else []
82
+
43
83
  # Extract parameters from the preprocessor
44
84
  preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
45
85
  symmetric_pad = self.pre_processor.resize.symmetric_pad
@@ -58,9 +58,11 @@ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = True,
58
58
  kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
59
59
  kwargs["std"] = kwargs.get("std", _model.cfg["std"])
60
60
  kwargs["batch_size"] = kwargs.get("batch_size", 2)
61
+ chunk_size = kwargs.pop("chunk_size", 32)
61
62
  predictor = DetectionPredictor(
62
63
  PreProcessor(_model.cfg["input_shape"][1:], **kwargs),
63
64
  _model,
65
+ chunk_size=chunk_size,
64
66
  )
65
67
  return predictor
66
68
 
@@ -90,6 +92,8 @@ def detection_predictor(
90
92
  running the detection model on it
91
93
  symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
92
94
  batch_size: number of samples the model processes in parallel
95
+ chunk_size: maximum number of pages decoded and processed at once (32 by default): longer inputs and
96
+ lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
93
97
  **kwargs: optional keyword arguments passed to the architecture
94
98
 
95
99
  Returns:
@@ -33,6 +33,7 @@ AVAILABLE_ARCHS = {
33
33
  "recognition": models.recognition.zoo.ARCHS,
34
34
  "layout": models.layout.zoo.ARCHS,
35
35
  "table_structure": models.table_structure.zoo.ARCHS,
36
+ "formula": models.formula.zoo.ARCHS,
36
37
  }
37
38
 
38
39
 
@@ -99,8 +100,8 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
99
100
 
100
101
  if run_config is None and arch is None:
101
102
  raise ValueError("run_config or arch must be specified")
102
- if task not in ["classification", "detection", "recognition", "layout", "table_structure"]:
103
- raise ValueError("task must be one of classification, detection, recognition, layout, table_structure")
103
+ if task not in ["classification", "detection", "recognition", "layout", "table_structure", "formula"]:
104
+ raise ValueError("task must be one of classification, detection, recognition, layout, table_structure, formula")
104
105
 
105
106
  # default readme
106
107
  readme = f"""---
@@ -223,6 +224,8 @@ def from_hub(repo_id: str, **kwargs: Any):
223
224
  model = models.layout.__dict__[arch](pretrained=False, class_names=cfg["class_names"])
224
225
  elif task == "table_structure":
225
226
  model = models.table_structure.__dict__[arch](pretrained=False)
227
+ elif task == "formula":
228
+ model = models.formula.__dict__[arch](pretrained=False, input_shape=cfg["input_shape"], vocab=cfg["vocab"])
226
229
 
227
230
  # update model cfg
228
231
  model.cfg = cfg
@@ -0,0 +1,2 @@
1
+ from .formulanet import *
2
+ from .zoo import *
@@ -0,0 +1,2 @@
1
+ from .base import *
2
+ from .pytorch import *
@@ -0,0 +1,70 @@
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 Sequence
7
+
8
+ import numpy as np
9
+
10
+ from doctr.datasets import encode_sequences, normalize_latex
11
+ from doctr.utils.repr import NestedObject
12
+
13
+ from ..._utils import ConfidenceAggregation, _confidence_aggregation_repr, _resolve_confidence_aggregation
14
+
15
+ __all__ = ["_FormulaNet", "_FormulaNetPostProcessor"]
16
+
17
+
18
+ class _FormulaNet:
19
+ vocab: list[str]
20
+ max_length: int
21
+
22
+ def build_target(self, gts: list[str]) -> tuple[np.ndarray, list[int]]:
23
+ r"""Encode LaTeX labels into token sequences `[SOS, tokens..., EOS, PAD...]`
24
+
25
+ The labels are tokenized first (cf. :func:`doctr.datasets.normalize_latex`), so they can be given either raw
26
+ (e.g. `\frac{a}{b}`) or normalized (e.g. `\frac { a } { b }`).
27
+
28
+ Args:
29
+ gts: list of ground-truth LaTeX labels
30
+
31
+ Returns:
32
+ the encoded sequences, of shape (N, L), and the number of tokens of each label
33
+ """
34
+ normalized = [normalize_latex(gt) for gt in gts]
35
+ encoded = encode_sequences(
36
+ sequences=normalized,
37
+ vocab=self.vocab,
38
+ target_size=self.max_length + 2, # SOS + tokens + EOS
39
+ eos=len(self.vocab),
40
+ sos=len(self.vocab) + 1,
41
+ pad=len(self.vocab) + 2,
42
+ dynamic_seq_length=True,
43
+ )
44
+ seq_len = [len(label.split()) for label in normalized]
45
+ return encoded, seq_len
46
+
47
+
48
+ class _FormulaNetPostProcessor(NestedObject):
49
+ """Turns the token scores of a formula recognition model into LaTeX strings
50
+
51
+ Args:
52
+ vocab: the list of LaTeX tokens of the model
53
+ confidence_aggregation: aggregation method of the token probabilities into the formula confidence:
54
+ "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a callable
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ vocab: Sequence[str],
60
+ confidence_aggregation: ConfidenceAggregation = "mean",
61
+ ) -> None:
62
+ _resolve_confidence_aggregation(confidence_aggregation)
63
+ self.vocab = list(vocab)
64
+ self.confidence_aggregation = confidence_aggregation
65
+
66
+ def extra_repr(self) -> str:
67
+ return (
68
+ f"vocab_size={len(self.vocab)}, "
69
+ f"confidence_aggregation={_confidence_aggregation_repr(self.confidence_aggregation)}"
70
+ )