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
@@ -27,10 +27,12 @@ class COCOTEXT(AbstractDataset):
27
27
  >>> from doctr.datasets import COCOTEXT
28
28
  >>> train_set = COCOTEXT(train=True, img_folder="/path/to/coco_text/train2014/",
29
29
  >>> label_path="/path/to/coco_text/cocotext.v2.json")
30
- >>> img, target = train_set[0]
30
+ >>> sample = train_set[0]
31
+ >>> img, target = sample.image, sample.target
31
32
  >>> test_set = COCOTEXT(train=False, img_folder="/path/to/coco_text/train2014/",
32
33
  >>> label_path = "/path/to/coco_text/cocotext.v2.json")
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/cord.py CHANGED
@@ -26,7 +26,8 @@ class CORD(VisionDataset):
26
26
 
27
27
  >>> from doctr.datasets import CORD
28
28
  >>> train_set = CORD(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
@@ -9,12 +9,8 @@ from collections.abc import Callable
9
9
  from pathlib import Path
10
10
  from typing import Any
11
11
 
12
- import numpy as np
13
-
14
12
  from doctr.io.image import get_img_shape
15
- from doctr.utils.data import download_from_url
16
-
17
- from ...models.utils import _copy_tensor
13
+ from doctr.utils import Sample, download_from_url
18
14
 
19
15
  __all__ = ["_AbstractDataset", "_VisionDataset"]
20
16
 
@@ -26,8 +22,8 @@ class _AbstractDataset:
26
22
  def __init__(
27
23
  self,
28
24
  root: str | Path,
29
- img_transforms: Callable[[Any], Any] | None = None,
30
- sample_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
25
+ img_transforms: Callable[[Sample], Sample] | None = None,
26
+ sample_transforms: Callable[[Sample], Sample] | None = None,
31
27
  pre_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
32
28
  ) -> None:
33
29
  if not Path(root).is_dir():
@@ -45,32 +41,24 @@ class _AbstractDataset:
45
41
  def _read_sample(self, index: int) -> tuple[Any, Any]:
46
42
  raise NotImplementedError
47
43
 
48
- def __getitem__(self, index: int) -> tuple[Any, Any]:
44
+ def __getitem__(self, index: int) -> Sample:
49
45
  # Read image
50
46
  img, target = self._read_sample(index)
47
+ mask = None
48
+
51
49
  # Pre-transforms (format conversion at run-time etc.)
52
50
  if self._pre_transforms is not None:
53
51
  img, target = self._pre_transforms(img, target)
54
52
 
53
+ sample = Sample(image=img, mask=mask, target=target)
54
+
55
55
  if self.img_transforms is not None:
56
- # typing issue cf. https://github.com/python/mypy/issues/5485
57
- img = self.img_transforms(img)
56
+ sample = self.img_transforms(sample)
58
57
 
59
58
  if self.sample_transforms is not None:
60
- # Conditions to assess it is detection model with multiple classes and avoid confusion with other tasks.
61
- if (
62
- isinstance(target, dict)
63
- and all(isinstance(item, np.ndarray) for item in target.values())
64
- and set(target.keys()) != {"boxes", "labels"} # avoid confusion with obj detection target
65
- ):
66
- img_transformed = _copy_tensor(img)
67
- for class_name, bboxes in target.items():
68
- img_transformed, target[class_name] = self.sample_transforms(img, bboxes)
69
- img = img_transformed
70
- else:
71
- img, target = self.sample_transforms(img, target)
72
-
73
- return img, target
59
+ sample = self.sample_transforms(sample)
60
+
61
+ return sample
74
62
 
75
63
  def extra_repr(self) -> str:
76
64
  return ""
@@ -11,6 +11,7 @@ import numpy as np
11
11
  import torch
12
12
 
13
13
  from doctr.io import read_img_as_tensor, tensor_from_numpy
14
+ from doctr.utils import Sample
14
15
 
15
16
  from .base import _AbstractDataset, _VisionDataset
16
17
 
@@ -48,11 +49,20 @@ class AbstractDataset(_AbstractDataset):
48
49
  return img, deepcopy(target)
49
50
 
50
51
  @staticmethod
51
- def collate_fn(samples: list[tuple[torch.Tensor, Any]]) -> tuple[torch.Tensor, list[Any]]:
52
- images, targets = zip(*samples)
53
- images = torch.stack(images, dim=0) # type: ignore[assignment]
52
+ def collate_fn(
53
+ samples: list[Sample],
54
+ ) -> tuple[torch.Tensor, list[Any]] | tuple[tuple[torch.Tensor, torch.Tensor], list[Any]]:
55
+ _images = [s.image for s in samples]
56
+ targets = [s.target for s in samples]
54
57
 
55
- return images, list(targets) # type: ignore[return-value]
58
+ _masks = [s.mask for s in samples if s.mask is not None]
59
+
60
+ images = torch.stack(_images, dim=0)
61
+ if _masks:
62
+ masks = torch.stack(_masks, dim=0)
63
+ return (images, masks), targets
64
+
65
+ return images, targets
56
66
 
57
67
 
58
68
  class VisionDataset(AbstractDataset, _VisionDataset): # noqa: D101
@@ -5,6 +5,7 @@
5
5
 
6
6
  import json
7
7
  import os
8
+ from functools import partial
8
9
  from typing import Any
9
10
 
10
11
  import numpy as np
@@ -23,7 +24,8 @@ class DetectionDataset(AbstractDataset):
23
24
  >>> from doctr.datasets import DetectionDataset
24
25
  >>> train_set = DetectionDataset(img_folder="/path/to/images",
25
26
  >>> label_path="/path/to/labels.json")
26
- >>> img, target = train_set[0]
27
+ >>> sample = train_set[0]
28
+ >>> img, target = sample.image, sample.target
27
29
 
28
30
  Args:
29
31
  img_folder: folder with all the images of the dataset
@@ -63,6 +65,10 @@ class DetectionDataset(AbstractDataset):
63
65
 
64
66
  self.data.append((img_name, (np.asarray(geoms, dtype=np_dtype), polygons_classes)))
65
67
 
68
+ # Every sample exposes the full (sorted) set of classes so that the class -> channel mapping
69
+ # is identical across samples, even when a class has no box in a given image.
70
+ self._pre_transforms = partial(pre_transform_multiclass, class_names=self.class_names)
71
+
66
72
  def format_polygons(
67
73
  self, polygons: list | dict, use_polygons: bool, np_dtype: type
68
74
  ) -> tuple[np.ndarray, list[str]]:
@@ -80,11 +86,16 @@ class DetectionDataset(AbstractDataset):
80
86
  if isinstance(polygons, list):
81
87
  self._class_names += [CLASS_NAME]
82
88
  polygons_classes = [CLASS_NAME for _ in polygons]
83
- _polygons: np.ndarray = np.asarray(polygons, dtype=np_dtype)
89
+ _polygons: np.ndarray = (
90
+ np.asarray(polygons, dtype=np_dtype) if polygons else np.zeros((0, 4, 2), dtype=np_dtype)
91
+ )
84
92
  elif isinstance(polygons, dict):
85
93
  self._class_names += list(polygons.keys())
86
94
  polygons_classes = [k for k, v in polygons.items() for _ in v]
87
- _polygons = np.concatenate([np.asarray(poly, dtype=np_dtype) for poly in polygons.values() if poly], axis=0)
95
+ arrays: list[np.ndarray] = [np.asarray(poly, dtype=np_dtype) for poly in polygons.values() if poly]
96
+ _polygons = (
97
+ np.concatenate(arrays, axis=0) if arrays else np.zeros((0, 4, 2), dtype=np_dtype)
98
+ ) # image without any box
88
99
  else:
89
100
  raise TypeError(f"polygons should be a dictionary or list, it was {type(polygons)}")
90
101
  geoms = _polygons if use_polygons else np.concatenate((_polygons.min(axis=1), _polygons.max(axis=1)), axis=1)
@@ -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
@@ -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
@@ -4,20 +4,91 @@
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
6
  import random
7
- from collections.abc import Callable
7
+ from collections.abc import Callable, Sequence
8
+ from functools import lru_cache
8
9
  from typing import Any
9
10
 
10
- from PIL import Image, ImageDraw
11
+ from PIL import Image, ImageDraw, ImageFont
11
12
 
12
13
  from doctr.io.image import tensor_from_pil
13
- from doctr.utils.fonts import get_font
14
+ from doctr.utils import Sample
15
+ from doctr.utils.fonts import get_font, get_font_candidates
14
16
 
15
17
  from ..datasets import AbstractDataset
16
18
 
19
+ # Size the synthetic samples are rendered at, and therefore the size the vocabulary is
20
+ # probed at: whether a glyph carries ink is a property of the rasterized outline.
21
+ DEFAULT_FONT_SIZE = 32
22
+ # Unicode non-characters: permanently unassigned, so a font never maps them and always
23
+ # falls back to ".notdef". Rendering them is how we learn what that fallback looks like.
24
+ NON_CHARACTERS = ("\ufffe", "\U0010ffff")
25
+
26
+
27
+ @lru_cache(maxsize=32)
28
+ def _load_font(font_family: str | None, font_size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
29
+ return get_font(font_family, font_size)
30
+
31
+
32
+ def _glyph_ink(font: ImageFont.FreeTypeFont | ImageFont.ImageFont, char: str) -> tuple[tuple[int, int], bytes] | None:
33
+ """Rasterized glyph of a character, None if it is drawn without ink."""
34
+ mask = font.getmask(char, mode="L")
35
+ return (mask.size, bytes(mask)) if mask.getbbox() is not None else None
36
+
37
+
38
+ @lru_cache(maxsize=32)
39
+ def _notdef_ink(font_family: str | None, font_size: int) -> frozenset[tuple[tuple[int, int], bytes]]:
40
+ """Glyph a font falls back to for characters it does not cover (the ".notdef" box)."""
41
+ font = _load_font(font_family, font_size)
42
+ return frozenset(ink for char in NON_CHARACTERS if (ink := _glyph_ink(font, char)) is not None)
43
+
44
+
45
+ @lru_cache(maxsize=8192)
46
+ def _renders_char(char: str, font_family: str | None, font_size: int) -> bool:
47
+ """Whether a font draws the actual glyph of a character, rather than nothing or a box."""
48
+ ink = _glyph_ink(_load_font(font_family, font_size), char)
49
+ return ink is not None and ink not in _notdef_ink(font_family, font_size)
50
+
51
+
52
+ def _resolve_fonts(font_family: str | list[str] | None) -> list[str | None]:
53
+ font_families: list[str | None] = [*font_family] if isinstance(font_family, list) else [font_family]
54
+ for font in font_families:
55
+ try:
56
+ _ = _load_font(font, DEFAULT_FONT_SIZE)
57
+ except OSError:
58
+ raise ValueError(f"unable to locate font: {font}")
59
+ return font_families
60
+
61
+
62
+ def _fonts_per_char(
63
+ vocab: str, font_families: Sequence[str | None], font_size: int = DEFAULT_FONT_SIZE
64
+ ) -> dict[str, tuple[str | None, ...]]:
65
+ """Map each character of the vocab to the fonts able to render it."""
66
+ # Whitespace is inkless in every font by design, so no font can be said to "cover" it;
67
+ # judging it by ink would reject any vocabulary containing a space.
68
+ mapping = {
69
+ char: tuple(font for font in font_families if char.isspace() or _renders_char(char, font, font_size))
70
+ for char in dict.fromkeys(vocab)
71
+ }
72
+ missing = [char for char, fonts in mapping.items() if not fonts]
73
+ if missing:
74
+ fallbacks = [font for font in get_font_candidates() if font not in font_families]
75
+ mapping.update({
76
+ char: tuple(font for font in fallbacks if _renders_char(char, font, font_size)) for char in missing
77
+ })
78
+ unrenderable = [char for char in missing if not mapping[char]]
79
+ if unrenderable:
80
+ raise ValueError(
81
+ f"the following characters cannot be rendered, neither by the given fonts {list(font_families)} "
82
+ f"nor by the system fonts {fallbacks}: "
83
+ f"{', '.join(f'{char!r} (U+{ord(char):04X})' for char in unrenderable)}. "
84
+ "They are drawn blank or as a '.notdef' box, please provide font(s) covering the whole vocab."
85
+ )
86
+ return mapping
87
+
17
88
 
18
89
  def synthesize_text_img(
19
90
  text: str,
20
- font_size: int = 32,
91
+ font_size: int = DEFAULT_FONT_SIZE,
21
92
  font_family: str | None = None,
22
93
  background_color: tuple[int, int, int] | None = None,
23
94
  text_color: tuple[int, int, int] | None = None,
@@ -33,13 +104,22 @@ def synthesize_text_img(
33
104
 
34
105
  Returns:
35
106
  PIL image of the text
107
+
108
+ Raises:
109
+ ValueError: if the text is empty or rendered without ink
36
110
  """
111
+ if not text:
112
+ raise ValueError("unable to synthesize an image from an empty text")
113
+
37
114
  background_color = (0, 0, 0) if background_color is None else background_color
38
115
  text_color = (255, 255, 255) if text_color is None else text_color
39
116
 
40
- font = get_font(font_family, font_size)
117
+ font = _load_font(font_family, font_size)
41
118
  left, top, right, bottom = font.getbbox(text)
42
119
  text_w, text_h = right - left, bottom - top
120
+ if text_w <= 0 or text_h <= 0:
121
+ raise ValueError(f"font {font_family!r} draws no ink for {text!r}, resulting in a zero-dimension image")
122
+
43
123
  h, w = int(round(1.3 * text_h)), int(round(1.1 * text_w))
44
124
  # If single letter, make the image square, otherwise expand to meet the text size
45
125
  img_size = (h, w) if len(text) > 1 else (max(h, w), max(h, w))
@@ -47,8 +127,8 @@ def synthesize_text_img(
47
127
  img = Image.new("RGB", img_size[::-1], color=background_color)
48
128
  d = ImageDraw.Draw(img)
49
129
 
50
- # Offset so that the text is centered
51
- text_pos = (int(round((img_size[1] - text_w) / 2)), int(round((img_size[0] - text_h) / 2)))
130
+ # Offset so that the text is centered: the ink starts at (left, top) from the drawing origin, not at (0, 0)
131
+ text_pos = (int(round((img_size[1] - text_w) / 2)) - left, int(round((img_size[0] - text_h) / 2)) - top)
52
132
  # Draw the text
53
133
  d.text(text_pos, text, font=font, fill=text_color)
54
134
  return img
@@ -62,18 +142,12 @@ class _CharacterGenerator(AbstractDataset):
62
142
  cache_samples: bool = False,
63
143
  font_family: str | list[str] | None = None,
64
144
  img_transforms: Callable[[Any], Any] | None = None,
65
- sample_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
145
+ sample_transforms: Callable[[Sample], Sample] | None = None,
66
146
  ) -> None:
67
147
  self.vocab = vocab
68
148
  self._num_samples = num_samples
69
- self.font_family = font_family if isinstance(font_family, list) else [font_family] # type: ignore[list-item]
70
- # Validate fonts
71
- if isinstance(font_family, list):
72
- for font in self.font_family:
73
- try:
74
- _ = get_font(font, 10)
75
- except OSError:
76
- raise ValueError(f"unable to locate font: {font}")
149
+ self.font_family = _resolve_fonts(font_family)
150
+ self._fonts_per_char = _fonts_per_char(self.vocab, self.font_family)
77
151
  self.img_transforms = img_transforms
78
152
  self.sample_transforms = sample_transforms
79
153
 
@@ -82,7 +156,7 @@ class _CharacterGenerator(AbstractDataset):
82
156
  self._data = [
83
157
  (synthesize_text_img(char, font_family=font), idx) # type: ignore[misc]
84
158
  for idx, char in enumerate(self.vocab)
85
- for font in self.font_family
159
+ for font in self._fonts_per_char[char]
86
160
  ]
87
161
 
88
162
  def __len__(self) -> int:
@@ -95,7 +169,9 @@ class _CharacterGenerator(AbstractDataset):
95
169
  pil_img, target = self._data[idx] # type: ignore[misc]
96
170
  else:
97
171
  target = index % len(self.vocab)
98
- pil_img = synthesize_text_img(self.vocab[target], font_family=random.choice(self.font_family))
172
+ char = self.vocab[target]
173
+ font = random.choice(self._fonts_per_char[char]) # nosec B311
174
+ pil_img = synthesize_text_img(char, font_family=font)
99
175
  img = tensor_from_pil(pil_img)
100
176
 
101
177
  return img, target
@@ -111,33 +187,42 @@ class _WordGenerator(AbstractDataset):
111
187
  cache_samples: bool = False,
112
188
  font_family: str | list[str] | None = None,
113
189
  img_transforms: Callable[[Any], Any] | None = None,
114
- sample_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
190
+ sample_transforms: Callable[[Sample], Sample] | None = None,
115
191
  ) -> None:
192
+ # An empty word can not be drawn: checked here, instead of failing on random samples during training
193
+ if not 1 <= min_chars <= max_chars:
194
+ raise ValueError(
195
+ f"expected 1 <= min_chars <= max_chars, but got min_chars={min_chars} and max_chars={max_chars}"
196
+ )
116
197
  self.vocab = vocab
117
198
  self.wordlen_range = (min_chars, max_chars)
118
199
  self._num_samples = num_samples
119
- self.font_family = font_family if isinstance(font_family, list) else [font_family] # type: ignore[list-item]
120
- # Validate fonts
121
- if isinstance(font_family, list):
122
- for font in self.font_family:
123
- try:
124
- _ = get_font(font, 10)
125
- except OSError:
126
- raise ValueError(f"unable to locate font: {font}")
200
+ self.font_family = _resolve_fonts(font_family)
201
+ fonts_per_char = _fonts_per_char(self.vocab, self.font_family)
202
+ # A word is drawn with a single font, so the font is picked first and the word is
203
+ # built from the characters this font can render, weighted by its coverage
204
+ self._vocab_per_font = {
205
+ font: "".join(char for char in self.vocab if font in fonts_per_char[char])
206
+ for font in dict.fromkeys(font for fonts in fonts_per_char.values() for font in fonts)
207
+ }
208
+ self._fonts = list(self._vocab_per_font)
209
+ self._font_weights = [len(vocab_) for vocab_ in self._vocab_per_font.values()]
127
210
  self.img_transforms = img_transforms
128
211
  self.sample_transforms = sample_transforms
129
212
 
130
213
  self._data: list[Image.Image] = []
131
214
  if cache_samples:
132
- _words = [self._generate_string(*self.wordlen_range) for _ in range(num_samples)]
133
- self._data = [
134
- (synthesize_text_img(text, font_family=random.choice(self.font_family)), text) # type: ignore[misc]
135
- for text in _words
136
- ]
215
+ self._data = [self._synthesize_sample() for _ in range(num_samples)] # type: ignore[misc]
216
+
217
+ def _generate_string(self, min_chars: int, max_chars: int, vocab: str | None = None) -> str:
218
+ num_chars = random.randint(min_chars, max_chars) # nosec B311
219
+ characters = self.vocab if vocab is None else vocab
220
+ return "".join(random.choice(characters) for _ in range(num_chars)) # nosec B311
137
221
 
138
- def _generate_string(self, min_chars: int, max_chars: int) -> str:
139
- num_chars = random.randint(min_chars, max_chars)
140
- return "".join(random.choice(self.vocab) for _ in range(num_chars))
222
+ def _synthesize_sample(self) -> tuple[Image.Image, str]:
223
+ font = random.choices(self._fonts, weights=self._font_weights)[0] # nosec B311
224
+ text = self._generate_string(*self.wordlen_range, vocab=self._vocab_per_font[font])
225
+ return synthesize_text_img(text, font_family=font), text
141
226
 
142
227
  def __len__(self) -> int:
143
228
  return self._num_samples
@@ -147,8 +232,7 @@ class _WordGenerator(AbstractDataset):
147
232
  if len(self._data) > 0:
148
233
  pil_img, target = self._data[index] # type: ignore[misc]
149
234
  else:
150
- target = self._generate_string(*self.wordlen_range)
151
- pil_img = synthesize_text_img(target, font_family=random.choice(self.font_family))
235
+ pil_img, target = self._synthesize_sample()
152
236
  img = tensor_from_pil(pil_img)
153
237
 
154
238
  return img, target
@@ -3,8 +3,6 @@
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,11 +34,12 @@ 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
43
- min_chars: minimum number of characters in a word
42
+ min_chars: minimum number of characters in a word, at least 1
44
43
  max_chars: maximum number of characters in a word
45
44
  num_samples: number of samples that will be generated iterating over the dataset
46
45
  cache_samples: whether generated images should be cached firsthand
doctr/datasets/ic03.py CHANGED
@@ -4,9 +4,9 @@
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
@@ -84,8 +85,9 @@ class IC03(VisionDataset):
84
85
  name, _resolution, rectangles = image
85
86
 
86
87
  # File existence check
87
- if not os.path.exists(os.path.join(tmp_root, name.text)):
88
- raise FileNotFoundError(f"unable to locate {os.path.join(tmp_root, name.text)}")
88
+ img_name = name.text
89
+ if not img_name or not os.path.exists(os.path.join(tmp_root, img_name)):
90
+ raise FileNotFoundError(f"unable to locate {os.path.join(tmp_root, img_name or '')}")
89
91
 
90
92
  if use_polygons:
91
93
  # (x, y) coordinates of top left, top right, bottom right, bottom left corners
@@ -120,14 +122,14 @@ class IC03(VisionDataset):
120
122
  labels = [lab.text for rect in rectangles for lab in rect if lab.text]
121
123
 
122
124
  if recognition_task:
123
- crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root, name.text), geoms=boxes)
125
+ crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root, img_name), geoms=boxes)
124
126
  for crop, label in zip(crops, labels):
125
127
  if crop.shape[0] > 0 and crop.shape[1] > 0 and len(label) > 0 and " " not in label:
126
128
  self.data.append((crop, label))
127
129
  elif detection_task:
128
- self.data.append((name.text, boxes))
130
+ self.data.append((img_name, boxes))
129
131
  else:
130
- self.data.append((name.text, dict(boxes=boxes, labels=labels)))
132
+ self.data.append((img_name, dict(boxes=boxes, labels=labels)))
131
133
 
132
134
  self.root = tmp_root
133
135
 
doctr/datasets/ic13.py CHANGED
@@ -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
@@ -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
@@ -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
@@ -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