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.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +669 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +14 -3
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +121 -37
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +9 -7
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +129 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +5 -4
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +10 -8
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +104 -21
- doctr/datasets/vocabs.py +320 -148
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +3 -0
- doctr/io/elements.py +381 -271
- doctr/io/exporters.py +1915 -0
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -7
- doctr/io/image/pytorch.py +13 -5
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +3 -0
- doctr/models/_utils.py +206 -13
- doctr/models/builder.py +590 -137
- doctr/models/classification/__init__.py +3 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +34 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +14 -2
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +32 -18
- doctr/models/detection/differentiable_binarization/base.py +23 -9
- doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
- doctr/models/detection/fast/base.py +22 -6
- doctr/models/detection/fast/pytorch.py +24 -11
- doctr/models/detection/linknet/base.py +22 -6
- doctr/models/detection/linknet/pytorch.py +10 -3
- doctr/models/detection/predictor/pytorch.py +43 -2
- doctr/models/detection/zoo.py +6 -2
- doctr/models/factory/hub.py +59 -41
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +23 -1
- doctr/models/kie_predictor/pytorch.py +87 -15
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +895 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +114 -0
- doctr/models/layout/zoo.py +94 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +415 -17
- doctr/models/predictor/pytorch.py +109 -12
- doctr/models/preprocessor/pytorch.py +82 -25
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +1127 -0
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +40 -16
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +84 -22
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +126 -25
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +68 -12
- doctr/models/recognition/sar/pytorch.py +21 -7
- doctr/models/recognition/utils.py +80 -50
- doctr/models/recognition/viptr/pytorch.py +38 -14
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +11 -7
- doctr/models/recognition/zoo.py +36 -9
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +231 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +675 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
- doctr/models/table_structure/zoo.py +87 -0
- doctr/models/utils/pytorch.py +381 -25
- doctr/models/zoo.py +141 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +261 -82
- doctr/transforms/modules/pytorch.py +396 -76
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +24 -11
- doctr/utils/fonts.py +64 -17
- doctr/utils/geometry.py +167 -28
- doctr/utils/metrics.py +481 -19
- doctr/utils/multithreading.py +127 -4
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +73 -10
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
- python_doctr-1.2.0.dist-info/RECORD +191 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/datasets/coco_text.py
CHANGED
|
@@ -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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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/datasets/base.py
CHANGED
|
@@ -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
|
|
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[[
|
|
30
|
-
sample_transforms: Callable[[
|
|
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) ->
|
|
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
|
-
|
|
57
|
-
img = self.img_transforms(img)
|
|
56
|
+
sample = self.img_transforms(sample)
|
|
58
57
|
|
|
59
58
|
if self.sample_transforms is not None:
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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(
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
|
|
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
|
doctr/datasets/detection.py
CHANGED
|
@@ -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
|
-
>>>
|
|
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 =
|
|
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
|
-
|
|
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)
|
doctr/datasets/doc_artefacts.py
CHANGED
|
@@ -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
|
-
>>>
|
|
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
|
-
>>>
|
|
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/generator/base.py
CHANGED
|
@@ -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
|
|
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 =
|
|
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 =
|
|
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[[
|
|
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 =
|
|
70
|
-
|
|
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.
|
|
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
|
-
|
|
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[[
|
|
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 =
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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
|
|
139
|
-
|
|
140
|
-
|
|
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.
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
|
|
88
|
-
|
|
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,
|
|
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((
|
|
130
|
+
self.data.append((img_name, boxes))
|
|
129
131
|
else:
|
|
130
|
-
self.data.append((
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|