python-doctr 1.0.0__py3-none-any.whl → 1.1.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 (138) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -0
  3. doctr/contrib/artefacts.py +1 -1
  4. doctr/contrib/base.py +1 -1
  5. doctr/datasets/__init__.py +2 -0
  6. doctr/datasets/coco_text.py +5 -3
  7. doctr/datasets/cord.py +3 -2
  8. doctr/datasets/datasets/base.py +13 -25
  9. doctr/datasets/datasets/pytorch.py +15 -5
  10. doctr/datasets/detection.py +3 -2
  11. doctr/datasets/doc_artefacts.py +3 -2
  12. doctr/datasets/funsd.py +3 -2
  13. doctr/datasets/generator/base.py +6 -5
  14. doctr/datasets/generator/pytorch.py +5 -6
  15. doctr/datasets/ic03.py +4 -3
  16. doctr/datasets/ic13.py +5 -3
  17. doctr/datasets/iiit5k.py +3 -2
  18. doctr/datasets/iiithws.py +5 -3
  19. doctr/datasets/imgur5k.py +5 -3
  20. doctr/datasets/layout.py +123 -0
  21. doctr/datasets/mjsynth.py +5 -3
  22. doctr/datasets/ocr.py +3 -2
  23. doctr/datasets/orientation.py +3 -2
  24. doctr/datasets/recognition.py +3 -2
  25. doctr/datasets/sroie.py +3 -2
  26. doctr/datasets/svhn.py +3 -2
  27. doctr/datasets/svt.py +4 -3
  28. doctr/datasets/synthtext.py +3 -2
  29. doctr/datasets/table_structure.py +97 -0
  30. doctr/datasets/utils.py +15 -6
  31. doctr/datasets/vocabs.py +3 -1
  32. doctr/datasets/wildreceipt.py +5 -3
  33. doctr/file_utils.py +4 -2
  34. doctr/io/__init__.py +1 -0
  35. doctr/io/elements.py +253 -261
  36. doctr/io/exporters.py +1275 -0
  37. doctr/io/html.py +1 -1
  38. doctr/io/image/base.py +4 -3
  39. doctr/io/image/pytorch.py +6 -4
  40. doctr/io/pdf.py +1 -1
  41. doctr/io/reader.py +1 -1
  42. doctr/models/__init__.py +2 -0
  43. doctr/models/_utils.py +111 -25
  44. doctr/models/builder.py +533 -62
  45. doctr/models/classification/__init__.py +2 -0
  46. doctr/models/classification/magc_resnet/pytorch.py +2 -2
  47. doctr/models/classification/mobilenet/pytorch.py +7 -7
  48. doctr/models/classification/predictor/pytorch.py +7 -3
  49. doctr/models/classification/resnet/pytorch.py +6 -6
  50. doctr/models/classification/starnet/__init__.py +1 -0
  51. doctr/models/classification/starnet/pytorch.py +202 -0
  52. doctr/models/classification/textnet/pytorch.py +7 -6
  53. doctr/models/classification/vgg/pytorch.py +4 -3
  54. doctr/models/classification/vip/layers/pytorch.py +5 -5
  55. doctr/models/classification/vip/pytorch.py +5 -5
  56. doctr/models/classification/vit/pytorch.py +4 -4
  57. doctr/models/classification/vit_det/__init__.py +1 -0
  58. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  60. doctr/models/classification/vit_det/pytorch.py +346 -0
  61. doctr/models/classification/zoo.py +4 -1
  62. doctr/models/core.py +1 -1
  63. doctr/models/detection/_utils/base.py +24 -8
  64. doctr/models/detection/_utils/pytorch.py +1 -1
  65. doctr/models/detection/core.py +34 -19
  66. doctr/models/detection/differentiable_binarization/base.py +7 -5
  67. doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
  68. doctr/models/detection/fast/base.py +6 -2
  69. doctr/models/detection/fast/pytorch.py +4 -4
  70. doctr/models/detection/linknet/base.py +6 -2
  71. doctr/models/detection/linknet/pytorch.py +4 -4
  72. doctr/models/detection/predictor/pytorch.py +4 -3
  73. doctr/models/detection/zoo.py +3 -3
  74. doctr/models/factory/hub.py +72 -52
  75. doctr/models/kie_predictor/base.py +17 -2
  76. doctr/models/kie_predictor/pytorch.py +42 -11
  77. doctr/models/layout/__init__.py +2 -0
  78. doctr/models/layout/lw_detr/__init__.py +1 -0
  79. doctr/models/layout/lw_detr/base.py +309 -0
  80. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  81. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  82. doctr/models/layout/lw_detr/pytorch.py +838 -0
  83. doctr/models/layout/predictor/__init__.py +1 -0
  84. doctr/models/layout/predictor/pytorch.py +82 -0
  85. doctr/models/layout/zoo.py +90 -0
  86. doctr/models/modules/layers/pytorch.py +140 -4
  87. doctr/models/modules/transformer/pytorch.py +1 -1
  88. doctr/models/modules/vision_transformer/pytorch.py +1 -1
  89. doctr/models/predictor/base.py +138 -16
  90. doctr/models/predictor/pytorch.py +151 -9
  91. doctr/models/preprocessor/pytorch.py +78 -23
  92. doctr/models/reading_order/__init__.py +1 -0
  93. doctr/models/reading_order/base.py +667 -0
  94. doctr/models/recognition/core.py +1 -1
  95. doctr/models/recognition/crnn/pytorch.py +6 -8
  96. doctr/models/recognition/master/base.py +1 -1
  97. doctr/models/recognition/master/pytorch.py +7 -8
  98. doctr/models/recognition/parseq/base.py +1 -1
  99. doctr/models/recognition/parseq/pytorch.py +5 -5
  100. doctr/models/recognition/predictor/_utils.py +1 -1
  101. doctr/models/recognition/predictor/pytorch.py +2 -2
  102. doctr/models/recognition/sar/pytorch.py +2 -2
  103. doctr/models/recognition/utils.py +9 -11
  104. doctr/models/recognition/viptr/pytorch.py +4 -6
  105. doctr/models/recognition/vitstr/base.py +1 -1
  106. doctr/models/recognition/vitstr/pytorch.py +6 -6
  107. doctr/models/recognition/zoo.py +6 -7
  108. doctr/models/table_structure/__init__.py +2 -0
  109. doctr/models/table_structure/predictor/__init__.py +1 -0
  110. doctr/models/table_structure/predictor/pytorch.py +80 -0
  111. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  112. doctr/models/table_structure/tablecenternet/base.py +485 -0
  113. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  114. doctr/models/table_structure/zoo.py +82 -0
  115. doctr/models/utils/pytorch.py +316 -16
  116. doctr/models/zoo.py +91 -3
  117. doctr/transforms/functional/base.py +3 -2
  118. doctr/transforms/functional/pytorch.py +1 -1
  119. doctr/transforms/modules/base.py +248 -83
  120. doctr/transforms/modules/pytorch.py +213 -74
  121. doctr/utils/common_types.py +22 -2
  122. doctr/utils/data.py +5 -4
  123. doctr/utils/fonts.py +56 -17
  124. doctr/utils/geometry.py +136 -19
  125. doctr/utils/metrics.py +351 -19
  126. doctr/utils/multithreading.py +6 -3
  127. doctr/utils/reconstitution.py +697 -133
  128. doctr/utils/repr.py +1 -1
  129. doctr/utils/visualization.py +63 -4
  130. doctr/version.py +1 -1
  131. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
  132. python_doctr-1.1.0.dist-info/RECORD +179 -0
  133. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  134. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  135. python_doctr-1.0.0.dist-info/RECORD +0 -149
  136. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  137. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  138. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -23,7 +23,8 @@ class DetectionDataset(AbstractDataset):
23
23
  >>> from doctr.datasets import DetectionDataset
24
24
  >>> train_set = DetectionDataset(img_folder="/path/to/images",
25
25
  >>> label_path="/path/to/labels.json")
26
- >>> img, target = train_set[0]
26
+ >>> sample = train_set[0]
27
+ >>> img, target = sample.image, sample.target
27
28
 
28
29
  Args:
29
30
  img_folder: folder with all the images of the dataset
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -23,7 +23,8 @@ class DocArtefacts(VisionDataset):
23
23
 
24
24
  >>> from doctr.datasets import DocArtefacts
25
25
  >>> train_set = DocArtefacts(train=True, download=True)
26
- >>> img, target = train_set[0]
26
+ >>> sample = train_set[0]
27
+ >>> img, target = sample.image, sample.target
27
28
 
28
29
  Args:
29
30
  train: whether the subset should be the training one
doctr/datasets/funsd.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -26,7 +26,8 @@ class FUNSD(VisionDataset):
26
26
 
27
27
  >>> from doctr.datasets import FUNSD
28
28
  >>> train_set = FUNSD(train=True, download=True)
29
- >>> img, target = train_set[0]
29
+ >>> sample = train_set[0]
30
+ >>> img, target = sample.image, sample.target
30
31
 
31
32
  Args:
32
33
  train: whether the subset should be the training one
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -10,6 +10,7 @@ from typing import Any
10
10
  from PIL import Image, ImageDraw
11
11
 
12
12
  from doctr.io.image import tensor_from_pil
13
+ from doctr.utils import Sample
13
14
  from doctr.utils.fonts import get_font
14
15
 
15
16
  from ..datasets import AbstractDataset
@@ -62,11 +63,11 @@ class _CharacterGenerator(AbstractDataset):
62
63
  cache_samples: bool = False,
63
64
  font_family: str | list[str] | None = None,
64
65
  img_transforms: Callable[[Any], Any] | None = None,
65
- sample_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
66
+ sample_transforms: Callable[[Sample], Sample] | None = None,
66
67
  ) -> None:
67
68
  self.vocab = vocab
68
69
  self._num_samples = num_samples
69
- self.font_family = font_family if isinstance(font_family, list) else [font_family] # type: ignore[list-item]
70
+ self.font_family = font_family if isinstance(font_family, list) else [font_family]
70
71
  # Validate fonts
71
72
  if isinstance(font_family, list):
72
73
  for font in self.font_family:
@@ -111,12 +112,12 @@ class _WordGenerator(AbstractDataset):
111
112
  cache_samples: bool = False,
112
113
  font_family: str | list[str] | None = None,
113
114
  img_transforms: Callable[[Any], Any] | None = None,
114
- sample_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
115
+ sample_transforms: Callable[[Sample], Sample] | None = None,
115
116
  ) -> None:
116
117
  self.vocab = vocab
117
118
  self.wordlen_range = (min_chars, max_chars)
118
119
  self._num_samples = num_samples
119
- self.font_family = font_family if isinstance(font_family, list) else [font_family] # type: ignore[list-item]
120
+ self.font_family = font_family if isinstance(font_family, list) else [font_family]
120
121
  # Validate fonts
121
122
  if isinstance(font_family, list):
122
123
  for font in self.font_family:
@@ -1,10 +1,8 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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 torch.utils.data._utils.collate import default_collate
7
-
8
6
  from .base import _CharacterGenerator, _WordGenerator
9
7
 
10
8
  __all__ = ["CharacterGenerator", "WordGenerator"]
@@ -15,7 +13,8 @@ class CharacterGenerator(_CharacterGenerator):
15
13
 
16
14
  >>> from doctr.datasets import CharacterGenerator
17
15
  >>> ds = CharacterGenerator(vocab='abdef', num_samples=100)
18
- >>> img, target = ds[0]
16
+ >>> sample = ds[0]
17
+ >>> img, target = sample.image, sample.target
19
18
 
20
19
  Args:
21
20
  vocab: vocabulary to take the character from
@@ -28,7 +27,6 @@ class CharacterGenerator(_CharacterGenerator):
28
27
 
29
28
  def __init__(self, *args, **kwargs) -> None:
30
29
  super().__init__(*args, **kwargs)
31
- setattr(self, "collate_fn", default_collate)
32
30
 
33
31
 
34
32
  class WordGenerator(_WordGenerator):
@@ -36,7 +34,8 @@ class WordGenerator(_WordGenerator):
36
34
 
37
35
  >>> from doctr.datasets import WordGenerator
38
36
  >>> ds = WordGenerator(vocab='abdef', min_chars=1, max_chars=32, num_samples=100)
39
- >>> img, target = ds[0]
37
+ >>> sample = ds[0]
38
+ >>> img, target = sample.image, sample.target
40
39
 
41
40
  Args:
42
41
  vocab: vocabulary to take the character from
doctr/datasets/ic03.py CHANGED
@@ -1,12 +1,12 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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
6
  import os
7
+ import xml.etree.ElementTree as ET # nosec B405
7
8
  from typing import Any
8
9
 
9
- import defusedxml.ElementTree as ET
10
10
  import numpy as np
11
11
  from tqdm import tqdm
12
12
 
@@ -25,7 +25,8 @@ class IC03(VisionDataset):
25
25
 
26
26
  >>> from doctr.datasets import IC03
27
27
  >>> train_set = IC03(train=True, download=True)
28
- >>> img, target = train_set[0]
28
+ >>> sample = train_set[0]
29
+ >>> img, target = sample.image, sample.target
29
30
 
30
31
  Args:
31
32
  train: whether the subset should be the training one
doctr/datasets/ic13.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -27,10 +27,12 @@ class IC13(AbstractDataset):
27
27
  >>> from doctr.datasets import IC13
28
28
  >>> train_set = IC13(img_folder="/path/to/Challenge2_Training_Task12_Images",
29
29
  >>> label_folder="/path/to/Challenge2_Training_Task1_GT")
30
- >>> img, target = train_set[0]
30
+ >>> sample = train_set[0]
31
+ >>> img, target = sample.image, sample.target
31
32
  >>> test_set = IC13(img_folder="/path/to/Challenge2_Test_Task12_Images",
32
33
  >>> label_folder="/path/to/Challenge2_Test_Task1_GT")
33
- >>> img, target = test_set[0]
34
+ >>> sample = test_set[0]
35
+ >>> img, target = sample.image, sample.target
34
36
 
35
37
  Args:
36
38
  img_folder: folder with all the images of the dataset
doctr/datasets/iiit5k.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -28,7 +28,8 @@ class IIIT5K(VisionDataset):
28
28
  >>> # NOTE: this dataset is for character-level localization
29
29
  >>> from doctr.datasets import IIIT5K
30
30
  >>> train_set = IIIT5K(train=True, download=True)
31
- >>> img, target = train_set[0]
31
+ >>> sample = train_set[0]
32
+ >>> img, target = sample.image, sample.target
32
33
 
33
34
  Args:
34
35
  train: whether the subset should be the training one
doctr/datasets/iiithws.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -25,11 +25,13 @@ class IIITHWS(AbstractDataset):
25
25
  >>> train_set = IIITHWS(img_folder="/path/to/iiit-hws/Images_90K_Normalized",
26
26
  >>> label_path="/path/to/IIIT-HWS-90K.txt",
27
27
  >>> train=True)
28
- >>> img, target = train_set[0]
28
+ >>> sample = train_set[0]
29
+ >>> img, target = sample.image, sample.target
29
30
  >>> test_set = IIITHWS(img_folder="/path/to/iiit-hws/Images_90K_Normalized",
30
31
  >>> label_path="/path/to/IIIT-HWS-90K.txt")
31
32
  >>> train=False)
32
- >>> img, target = test_set[0]
33
+ >>> sample = test_set[0]
34
+ >>> img, target = sample.image, sample.target
33
35
 
34
36
  Args:
35
37
  img_folder: folder with all the images of the dataset
doctr/datasets/imgur5k.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -34,10 +34,12 @@ class IMGUR5K(AbstractDataset):
34
34
  >>> from doctr.datasets import IMGUR5K
35
35
  >>> train_set = IMGUR5K(train=True, img_folder="/path/to/IMGUR5K-Handwriting-Dataset/images",
36
36
  >>> label_path="/path/to/IMGUR5K-Handwriting-Dataset/dataset_info/imgur5k_annotations.json")
37
- >>> img, target = train_set[0]
37
+ >>> sample = train_set[0]
38
+ >>> img, target = sample.image, sample.target
38
39
  >>> test_set = IMGUR5K(train=False, img_folder="/path/to/IMGUR5K-Handwriting-Dataset/images",
39
40
  >>> label_path="/path/to/IMGUR5K-Handwriting-Dataset/dataset_info/imgur5k_annotations.json")
40
- >>> img, target = test_set[0]
41
+ >>> sample = test_set[0]
42
+ >>> img, target = sample.image, sample.target
41
43
 
42
44
  Args:
43
45
  img_folder: folder with all the images of the dataset
@@ -0,0 +1,123 @@
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
+ import json
7
+ import os
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+
12
+ from .datasets import AbstractDataset
13
+ from .utils import pre_transform_multiclass
14
+
15
+ __all__ = ["LayoutDataset"]
16
+
17
+
18
+ class LayoutDataset(AbstractDataset):
19
+ """Implements a document layout detection dataset.
20
+
21
+ >>> from doctr.datasets import LayoutDataset
22
+ >>> train_set = LayoutDataset(
23
+ >>> img_folder="/path/to/images",
24
+ >>> label_path="/path/to/labels.json",
25
+ >>> )
26
+ >>> sample = train_set[0]
27
+ >>> img, target = sample.image, sample.target
28
+
29
+ Args:
30
+ img_folder: folder containing the dataset images
31
+ label_path: path to the labels.json file
32
+ use_polygons: whether to keep polygons instead of converting to straight boxes
33
+ **kwargs: keyword arguments from `AbstractDataset`
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ img_folder: str,
39
+ label_path: str,
40
+ use_polygons: bool = False,
41
+ **kwargs: Any,
42
+ ) -> None:
43
+ super().__init__(
44
+ img_folder,
45
+ pre_transforms=pre_transform_multiclass,
46
+ **kwargs,
47
+ )
48
+ self._class_names: list[str] = []
49
+ if not os.path.exists(label_path):
50
+ raise FileNotFoundError(f"unable to locate {label_path}")
51
+ with open(label_path, "rb") as f:
52
+ labels = json.load(f)
53
+
54
+ self.data: list[tuple[str, tuple[np.ndarray, list[str]]]] = []
55
+ np_dtype = np.float32
56
+
57
+ for img_name, label in labels.items():
58
+ img_path = os.path.join(self.root, img_name)
59
+
60
+ # File existence check
61
+ if not os.path.exists(img_path):
62
+ raise FileNotFoundError(f"unable to locate {img_path}")
63
+
64
+ polygons = label.get("polygons")
65
+ class_names = label.get("classes")
66
+
67
+ if polygons is None:
68
+ raise KeyError(f"missing 'polygons' for image: {img_name}")
69
+ if class_names is None:
70
+ raise KeyError(f"missing 'classes' for image: {img_name}")
71
+
72
+ if len(polygons) != len(class_names):
73
+ raise ValueError(
74
+ f"number of polygons ({len(polygons)}) does not match "
75
+ f"number of classes ({len(class_names)}) for image: {img_name}"
76
+ )
77
+
78
+ geoms, polygon_classes = self.format_polygons(
79
+ polygons=polygons,
80
+ class_names=class_names,
81
+ use_polygons=use_polygons,
82
+ np_dtype=np_dtype,
83
+ )
84
+
85
+ self.data.append((
86
+ img_name,
87
+ (
88
+ np.asarray(geoms, dtype=np_dtype),
89
+ polygon_classes,
90
+ ),
91
+ ))
92
+
93
+ def format_polygons(
94
+ self,
95
+ polygons: list,
96
+ class_names: list[str],
97
+ use_polygons: bool,
98
+ np_dtype: type,
99
+ ) -> tuple[np.ndarray, list[str]]:
100
+ """Format polygons into an array.
101
+
102
+ Args:
103
+ polygons: list of polygons
104
+ class_names: list of class names corresponding to polygons
105
+ use_polygons: whether polygons should be preserved
106
+ np_dtype: numpy dtype
107
+
108
+ Returns:
109
+ geoms: polygons or straight boxes
110
+ polygon_classes: list of classes
111
+ """
112
+ self._class_names += class_names
113
+
114
+ _polygons: np.ndarray = np.asarray(polygons, dtype=np_dtype)
115
+ if _polygons.ndim != 3 or _polygons.shape[1:] != (4, 2):
116
+ raise ValueError(f"polygons are expected to have shape (N, 4, 2), got {_polygons.shape}")
117
+ geoms = _polygons if use_polygons else np.concatenate((_polygons.min(axis=1), _polygons.max(axis=1)), axis=1)
118
+
119
+ return geoms, class_names
120
+
121
+ @property
122
+ def class_names(self) -> list[str]:
123
+ return sorted(set(self._class_names))
doctr/datasets/mjsynth.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -23,11 +23,13 @@ class MJSynth(AbstractDataset):
23
23
  >>> train_set = MJSynth(img_folder="/path/to/mjsynth/mnt/ramdisk/max/90kDICT32px",
24
24
  >>> label_path="/path/to/mjsynth/mnt/ramdisk/max/90kDICT32px/imlist.txt",
25
25
  >>> train=True)
26
- >>> img, target = train_set[0]
26
+ >>> sample = train_set[0]
27
+ >>> img, target = sample.image, sample.target
27
28
  >>> test_set = MJSynth(img_folder="/path/to/mjsynth/mnt/ramdisk/max/90kDICT32px",
28
29
  >>> label_path="/path/to/mjsynth/mnt/ramdisk/max/90kDICT32px/imlist.txt")
29
30
  >>> train=False)
30
- >>> img, target = test_set[0]
31
+ >>> sample = test_set[0]
32
+ >>> img, target = sample.image, sample.target
31
33
 
32
34
  Args:
33
35
  img_folder: folder with all the images of the dataset
doctr/datasets/ocr.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -21,7 +21,8 @@ class OCRDataset(AbstractDataset):
21
21
  >>> from doctr.datasets import OCRDataset
22
22
  >>> train_set = OCRDataset(img_folder="/path/to/images",
23
23
  >>> label_file="/path/to/labels.json")
24
- >>> img, target = train_set[0]
24
+ >>> sample = train_set[0]
25
+ >>> img, target = sample.image, sample.target
25
26
 
26
27
  Args:
27
28
  img_folder: local path to image folder (all jpg at the root)
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -18,7 +18,8 @@ class OrientationDataset(AbstractDataset):
18
18
 
19
19
  >>> from doctr.datasets import OrientationDataset
20
20
  >>> train_set = OrientationDataset(img_folder="/path/to/images")
21
- >>> img, target = train_set[0]
21
+ >>> sample = train_set[0]
22
+ >>> img, target = sample.image, sample.target
22
23
 
23
24
  Args:
24
25
  img_folder: folder with all the images of the dataset
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -19,7 +19,8 @@ class RecognitionDataset(AbstractDataset):
19
19
  >>> from doctr.datasets import RecognitionDataset
20
20
  >>> train_set = RecognitionDataset(img_folder="/path/to/images",
21
21
  >>> labels_path="/path/to/labels.json")
22
- >>> img, target = train_set[0]
22
+ >>> sample = train_set[0]
23
+ >>> img, target = sample.image, sample.target
23
24
 
24
25
  Args:
25
26
  img_folder: path to the images folder
doctr/datasets/sroie.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -26,7 +26,8 @@ class SROIE(VisionDataset):
26
26
 
27
27
  >>> from doctr.datasets import SROIE
28
28
  >>> train_set = SROIE(train=True, download=True)
29
- >>> img, target = train_set[0]
29
+ >>> sample = train_set[0]
30
+ >>> img, target = sample.image, sample.target
30
31
 
31
32
  Args:
32
33
  train: whether the subset should be the training one
doctr/datasets/svhn.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -25,7 +25,8 @@ class SVHN(VisionDataset):
25
25
 
26
26
  >>> from doctr.datasets import SVHN
27
27
  >>> train_set = SVHN(train=True, download=True)
28
- >>> img, target = train_set[0]
28
+ >>> sample = train_set[0]
29
+ >>> img, target = sample.image, sample.target
29
30
 
30
31
  Args:
31
32
  train: whether the subset should be the training one
doctr/datasets/svt.py CHANGED
@@ -1,12 +1,12 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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
6
  import os
7
+ import xml.etree.ElementTree as ET # nosec B405
7
8
  from typing import Any
8
9
 
9
- import defusedxml.ElementTree as ET
10
10
  import numpy as np
11
11
  from tqdm import tqdm
12
12
 
@@ -25,7 +25,8 @@ class SVT(VisionDataset):
25
25
 
26
26
  >>> from doctr.datasets import SVT
27
27
  >>> train_set = SVT(train=True, download=True)
28
- >>> img, target = train_set[0]
28
+ >>> sample = train_set[0]
29
+ >>> img, target = sample.image, sample.target
29
30
 
30
31
  Args:
31
32
  train: whether the subset should be the training one
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -28,7 +28,8 @@ class SynthText(VisionDataset):
28
28
 
29
29
  >>> from doctr.datasets import SynthText
30
30
  >>> train_set = SynthText(train=True, download=True)
31
- >>> img, target = train_set[0]
31
+ >>> sample = train_set[0]
32
+ >>> img, target = sample.image, sample.target
32
33
 
33
34
  Args:
34
35
  train: whether the subset should be the training one
@@ -0,0 +1,97 @@
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
+ import json
7
+ import os
8
+ from typing import Any, cast
9
+
10
+ import numpy as np
11
+
12
+ from doctr.io import read_img_as_tensor
13
+ from doctr.io.image import get_img_shape
14
+ from doctr.utils import Sample
15
+ from doctr.utils.geometry import convert_to_relative_coords
16
+
17
+ from .datasets import AbstractDataset
18
+
19
+ __all__ = ["TableStructureDataset"]
20
+
21
+
22
+ class TableStructureDataset(AbstractDataset):
23
+ """Table structure recognition dataset for table structure recognition.
24
+
25
+ The labels file maps each image name to its cells and their logical coordinates::
26
+
27
+ {
28
+ "table_0.jpg": {
29
+ "cells": [[[x0, y0], [x1, y1], [x2, y2], [x3, y3]], ...], # quads (TL, TR, BR, BL), abs px
30
+ "logic": [[start_col, end_col, start_row, end_row], ...] # 0-indexed, per cell
31
+ },
32
+ ...
33
+ }
34
+
35
+ Each sample yields the image and a target containing relative cells and their logical coordinates. Cells have
36
+ shape `(N, 4)` by default, or `(N, 4, 2)` when `use_polygons=True`. Logical coordinates have shape
37
+ `(N, 4)`.
38
+
39
+ >>> from doctr.datasets import TableStructureDataset
40
+ >>> from doctr.transforms import Resize
41
+ >>> train_set = TableStructureDataset(
42
+ >>> img_folder="/path/to/images",
43
+ >>> label_path="/path/to/labels.json",
44
+ >>> )
45
+ >>> img, target = train_set[0]
46
+
47
+ Args:
48
+ img_folder: folder with all the dataset images
49
+ label_path: path to the JSON labels
50
+ use_polygons: whether to keep cell polygons instead of converting them to straight boxes
51
+ **kwargs: keyword arguments from `AbstractDataset` (e.g. `img_transforms`, `sample_transforms`)
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ img_folder: str,
57
+ label_path: str,
58
+ use_polygons: bool = False,
59
+ **kwargs: Any,
60
+ ) -> None:
61
+ super().__init__(img_folder, **kwargs)
62
+
63
+ if not os.path.exists(label_path):
64
+ raise FileNotFoundError(f"unable to locate {label_path}")
65
+ with open(label_path, "rb") as f:
66
+ labels = json.load(f)
67
+
68
+ self.data: list[tuple[str, dict[str, np.ndarray]]] = []
69
+ for img_name, label in labels.items():
70
+ img_path = os.path.join(self.root, img_name)
71
+
72
+ if not os.path.exists(img_path):
73
+ raise FileNotFoundError(f"unable to locate {img_path}")
74
+
75
+ cells = np.asarray(label["cells"], dtype=np.float32)
76
+ logic = np.asarray(label["logic"], dtype=np.int64)
77
+ if cells.ndim != 3 or cells.shape[1:] != (4, 2): # pragma: no cover
78
+ raise ValueError(f"cells are expected to have shape (N, 4, 2), got {cells.shape}")
79
+ if logic.shape[0] != cells.shape[0] or logic.shape[1] != 4: # pragma: no cover
80
+ raise ValueError(f"logic is expected to have shape (N, 4), got {logic.shape}")
81
+ if not use_polygons:
82
+ cells = np.concatenate((cells.min(axis=1), cells.max(axis=1)), axis=1)
83
+ self.data.append((img_name, {"cells": cells, "logic": logic}))
84
+
85
+ # NOTE: Override basic dataset method __getitem__ to handle table-specific targets
86
+ def __getitem__(self, index: int) -> Sample:
87
+ img_name, label = self.data[index]
88
+ img = read_img_as_tensor(os.path.join(self.root, img_name))
89
+ # Convert cells to relative coordinates, then let img/sample transforms resize image + geometry.
90
+ rel_cells = np.clip(convert_to_relative_coords(label["cells"].copy(), get_img_shape(img)), 0, 1)
91
+ sample = Sample(image=img, mask=None, target=rel_cells)
92
+ if self.img_transforms is not None:
93
+ sample = self.img_transforms(sample)
94
+ if self.sample_transforms is not None:
95
+ sample = self.sample_transforms(sample)
96
+ target: dict[str, np.ndarray] = {"cells": cast(np.ndarray, sample.target), "logic": label["logic"]}
97
+ return Sample(image=sample.image, mask=None, target=target)
doctr/datasets/utils.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -7,7 +7,7 @@ import string
7
7
  import unicodedata
8
8
  from collections.abc import Sequence
9
9
  from collections.abc import Sequence as SequenceType
10
- from functools import partial
10
+ from functools import lru_cache, partial
11
11
  from pathlib import Path
12
12
  from typing import Any, TypeVar
13
13
 
@@ -66,6 +66,12 @@ def translate(
66
66
  return translated
67
67
 
68
68
 
69
+ @lru_cache(maxsize=32)
70
+ def _vocab_lookup_table(vocab: str) -> dict[str, int]:
71
+ """Cached char -> index table for a vocab"""
72
+ return {char: idx for idx, char in reversed(list(enumerate(vocab)))}
73
+
74
+
69
75
  def encode_string(
70
76
  input_string: str,
71
77
  vocab: str,
@@ -79,10 +85,11 @@ def encode_string(
79
85
  Returns:
80
86
  A list encoding the input_string
81
87
  """
88
+ table = _vocab_lookup_table(vocab)
82
89
  try:
83
- return list(map(vocab.index, input_string))
84
- except ValueError as e:
85
- missing_chars = [char for char in input_string if char not in vocab]
90
+ return [table[char] for char in input_string]
91
+ except KeyError as e:
92
+ missing_chars = [char for char in input_string if char not in table]
86
93
  raise ValueError(
87
94
  f"Some characters cannot be found in 'vocab': {set(missing_chars)}.\n"
88
95
  f"Please check the input string `{input_string}` and the vocabulary `{vocab}`"
@@ -104,7 +111,9 @@ def decode_sequence(
104
111
  """
105
112
  if not isinstance(input_seq, (Sequence, np.ndarray)):
106
113
  raise TypeError("Invalid sequence type")
107
- if isinstance(input_seq, np.ndarray) and (input_seq.dtype != np.int_ or input_seq.max() >= len(mapping)):
114
+ if isinstance(input_seq, np.ndarray) and (
115
+ not np.issubdtype(input_seq.dtype, np.integer) or (input_seq.size > 0 and input_seq.max() >= len(mapping))
116
+ ):
108
117
  raise AssertionError("Input must be an array of int, with max less than mapping size")
109
118
 
110
119
  return "".join(map(mapping.__getitem__, input_seq))