python-doctr 1.0.1__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.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +506 -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 +2 -1
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +5 -4
- doctr/datasets/generator/pytorch.py +4 -5
- doctr/datasets/ic03.py +3 -2
- 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 +123 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +2 -1
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +3 -2
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +14 -5
- doctr/datasets/vocabs.py +2 -0
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +252 -260
- doctr/io/exporters.py +1275 -0
- doctr/io/image/base.py +3 -2
- doctr/io/image/pytorch.py +5 -3
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +56 -8
- doctr/models/builder.py +532 -61
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +6 -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 +3 -0
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +33 -18
- doctr/models/detection/differentiable_binarization/base.py +6 -4
- doctr/models/detection/differentiable_binarization/pytorch.py +3 -3
- doctr/models/detection/fast/base.py +5 -1
- doctr/models/detection/fast/pytorch.py +3 -3
- doctr/models/detection/linknet/base.py +5 -1
- doctr/models/detection/linknet/pytorch.py +3 -3
- doctr/models/detection/predictor/pytorch.py +3 -2
- doctr/models/detection/zoo.py +2 -2
- doctr/models/factory/hub.py +56 -41
- doctr/models/kie_predictor/base.py +16 -1
- doctr/models/kie_predictor/pytorch.py +41 -10
- 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 +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/predictor/base.py +137 -15
- doctr/models/predictor/pytorch.py +150 -8
- doctr/models/preprocessor/pytorch.py +77 -22
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/crnn/pytorch.py +5 -7
- doctr/models/recognition/master/pytorch.py +6 -7
- doctr/models/recognition/parseq/pytorch.py +4 -4
- doctr/models/recognition/predictor/pytorch.py +1 -1
- doctr/models/recognition/sar/pytorch.py +1 -1
- doctr/models/recognition/utils.py +8 -10
- doctr/models/recognition/viptr/pytorch.py +3 -5
- doctr/models/recognition/vitstr/pytorch.py +5 -5
- doctr/models/recognition/zoo.py +5 -6
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +314 -15
- doctr/models/zoo.py +90 -2
- doctr/transforms/modules/base.py +247 -82
- doctr/transforms/modules/pytorch.py +212 -73
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +4 -2
- doctr/utils/fonts.py +55 -16
- doctr/utils/geometry.py +135 -18
- doctr/utils/metrics.py +350 -18
- doctr/utils/multithreading.py +5 -2
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +62 -3
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/METADATA +67 -27
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.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.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
doctr/datasets/generator/base.py
CHANGED
|
@@ -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[[
|
|
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]
|
|
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[[
|
|
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]
|
|
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:
|
|
@@ -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,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
|
-
>>>
|
|
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
|
@@ -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
|
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
|
doctr/datasets/layout.py
ADDED
|
@@ -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
|
@@ -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
|
-
>>>
|
|
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
|
-
>>>
|
|
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
|
@@ -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
|
-
>>>
|
|
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)
|
doctr/datasets/orientation.py
CHANGED
|
@@ -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
|
-
>>>
|
|
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
|
doctr/datasets/recognition.py
CHANGED
|
@@ -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
|
-
>>>
|
|
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
|
@@ -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
|
-
>>>
|
|
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
|
@@ -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
|
-
>>>
|
|
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
|
@@ -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 SVT(VisionDataset):
|
|
|
25
25
|
|
|
26
26
|
>>> from doctr.datasets import SVT
|
|
27
27
|
>>> train_set = SVT(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
|
doctr/datasets/synthtext.py
CHANGED
|
@@ -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
|
-
>>>
|
|
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
|
@@ -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
|
|
84
|
-
except
|
|
85
|
-
missing_chars = [char for char in input_string if char not in
|
|
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 (
|
|
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))
|
doctr/datasets/vocabs.py
CHANGED
|
@@ -9,6 +9,8 @@ import string
|
|
|
9
9
|
__all__ = ["VOCABS"]
|
|
10
10
|
|
|
11
11
|
_BASE_VOCABS = {
|
|
12
|
+
# LaTeX
|
|
13
|
+
"latex": "".join(sorted(set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\{}^_=+-<>()[]/.,| "))),
|
|
12
14
|
# Latin
|
|
13
15
|
"digits": string.digits,
|
|
14
16
|
"ascii_letters": string.ascii_letters,
|
doctr/datasets/wildreceipt.py
CHANGED
|
@@ -30,10 +30,12 @@ class WILDRECEIPT(AbstractDataset):
|
|
|
30
30
|
>>> from doctr.datasets import WILDRECEIPT
|
|
31
31
|
>>> train_set = WILDRECEIPT(train=True, img_folder="/path/to/wildreceipt/",
|
|
32
32
|
>>> label_path="/path/to/wildreceipt/train.txt")
|
|
33
|
-
>>>
|
|
33
|
+
>>> sample = train_set[0]
|
|
34
|
+
>>> img, target = sample.image, sample.target
|
|
34
35
|
>>> test_set = WILDRECEIPT(train=False, img_folder="/path/to/wildreceipt/",
|
|
35
36
|
>>> label_path="/path/to/wildreceipt/test.txt")
|
|
36
|
-
>>>
|
|
37
|
+
>>> sample = test_set[0]
|
|
38
|
+
>>> img, target = sample.image, sample.target
|
|
37
39
|
|
|
38
40
|
Args:
|
|
39
41
|
img_folder: folder with all the images of the dataset
|
doctr/file_utils.py
CHANGED
|
@@ -8,6 +8,8 @@ import logging
|
|
|
8
8
|
|
|
9
9
|
__all__ = ["requires_package", "CLASS_NAME"]
|
|
10
10
|
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
11
13
|
CLASS_NAME: str = "words"
|
|
12
14
|
ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
|
|
13
15
|
|
|
@@ -22,7 +24,7 @@ def requires_package(name: str, extra_message: str | None = None) -> None: # pr
|
|
|
22
24
|
"""
|
|
23
25
|
try:
|
|
24
26
|
_pkg_version = importlib.metadata.version(name)
|
|
25
|
-
|
|
27
|
+
logger.info(f"{name} version {_pkg_version} available.")
|
|
26
28
|
except importlib.metadata.PackageNotFoundError:
|
|
27
29
|
raise ImportError(
|
|
28
30
|
f"\n\n{extra_message if extra_message is not None else ''} "
|