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/layout.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
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 functools import partial
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from .datasets import AbstractDataset
|
|
14
|
+
from .utils import pre_transform_multiclass
|
|
15
|
+
|
|
16
|
+
__all__ = ["LayoutDataset"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class LayoutDataset(AbstractDataset):
|
|
20
|
+
"""Implements a document layout detection dataset.
|
|
21
|
+
|
|
22
|
+
>>> from doctr.datasets import LayoutDataset
|
|
23
|
+
>>> train_set = LayoutDataset(
|
|
24
|
+
>>> img_folder="/path/to/images",
|
|
25
|
+
>>> label_path="/path/to/labels.json",
|
|
26
|
+
>>> )
|
|
27
|
+
>>> sample = train_set[0]
|
|
28
|
+
>>> img, target = sample.image, sample.target
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
img_folder: folder containing the dataset images
|
|
32
|
+
label_path: path to the labels.json file
|
|
33
|
+
use_polygons: whether to keep polygons instead of converting to straight boxes
|
|
34
|
+
**kwargs: keyword arguments from `AbstractDataset`
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
img_folder: str,
|
|
40
|
+
label_path: str,
|
|
41
|
+
use_polygons: bool = False,
|
|
42
|
+
**kwargs: Any,
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__(
|
|
45
|
+
img_folder,
|
|
46
|
+
pre_transforms=pre_transform_multiclass,
|
|
47
|
+
**kwargs,
|
|
48
|
+
)
|
|
49
|
+
self._class_names: list[str] = []
|
|
50
|
+
if not os.path.exists(label_path):
|
|
51
|
+
raise FileNotFoundError(f"unable to locate {label_path}")
|
|
52
|
+
with open(label_path, "rb") as f:
|
|
53
|
+
labels = json.load(f)
|
|
54
|
+
|
|
55
|
+
self.data: list[tuple[str, tuple[np.ndarray, list[str]]]] = []
|
|
56
|
+
np_dtype = np.float32
|
|
57
|
+
|
|
58
|
+
for img_name, label in labels.items():
|
|
59
|
+
img_path = os.path.join(self.root, img_name)
|
|
60
|
+
|
|
61
|
+
# File existence check
|
|
62
|
+
if not os.path.exists(img_path):
|
|
63
|
+
raise FileNotFoundError(f"unable to locate {img_path}")
|
|
64
|
+
|
|
65
|
+
polygons = label.get("polygons")
|
|
66
|
+
class_names = label.get("classes")
|
|
67
|
+
|
|
68
|
+
if polygons is None:
|
|
69
|
+
raise KeyError(f"missing 'polygons' for image: {img_name}")
|
|
70
|
+
if class_names is None:
|
|
71
|
+
raise KeyError(f"missing 'classes' for image: {img_name}")
|
|
72
|
+
|
|
73
|
+
if len(polygons) != len(class_names):
|
|
74
|
+
raise ValueError(
|
|
75
|
+
f"number of polygons ({len(polygons)}) does not match "
|
|
76
|
+
f"number of classes ({len(class_names)}) for image: {img_name}"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
geoms, polygon_classes = self.format_polygons(
|
|
80
|
+
polygons=polygons,
|
|
81
|
+
class_names=class_names,
|
|
82
|
+
use_polygons=use_polygons,
|
|
83
|
+
np_dtype=np_dtype,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
self.data.append((
|
|
87
|
+
img_name,
|
|
88
|
+
(
|
|
89
|
+
np.asarray(geoms, dtype=np_dtype),
|
|
90
|
+
polygon_classes,
|
|
91
|
+
),
|
|
92
|
+
))
|
|
93
|
+
|
|
94
|
+
# Expose every class in every sample so the class -> channel mapping never shifts
|
|
95
|
+
self._pre_transforms = partial(pre_transform_multiclass, class_names=self.class_names)
|
|
96
|
+
|
|
97
|
+
def format_polygons(
|
|
98
|
+
self,
|
|
99
|
+
polygons: list,
|
|
100
|
+
class_names: list[str],
|
|
101
|
+
use_polygons: bool,
|
|
102
|
+
np_dtype: type,
|
|
103
|
+
) -> tuple[np.ndarray, list[str]]:
|
|
104
|
+
"""Format polygons into an array.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
polygons: list of polygons
|
|
108
|
+
class_names: list of class names corresponding to polygons
|
|
109
|
+
use_polygons: whether polygons should be preserved
|
|
110
|
+
np_dtype: numpy dtype
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
geoms: polygons or straight boxes
|
|
114
|
+
polygon_classes: list of classes
|
|
115
|
+
"""
|
|
116
|
+
self._class_names += class_names
|
|
117
|
+
|
|
118
|
+
_polygons: np.ndarray = (
|
|
119
|
+
np.asarray(polygons, dtype=np_dtype) if len(polygons) else np.zeros((0, 4, 2), dtype=np_dtype)
|
|
120
|
+
) # an image without any region is a valid (all-background) sample
|
|
121
|
+
if _polygons.ndim != 3 or _polygons.shape[1:] != (4, 2):
|
|
122
|
+
raise ValueError(f"polygons are expected to have shape (N, 4, 2), got {_polygons.shape}")
|
|
123
|
+
geoms = _polygons if use_polygons else np.concatenate((_polygons.min(axis=1), _polygons.max(axis=1)), axis=1)
|
|
124
|
+
|
|
125
|
+
return geoms, class_names
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def class_names(self) -> list[str]:
|
|
129
|
+
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
|
|
@@ -46,10 +47,10 @@ class RecognitionDataset(AbstractDataset):
|
|
|
46
47
|
self.data.append((img_name, label))
|
|
47
48
|
|
|
48
49
|
def merge_dataset(self, ds: AbstractDataset) -> None:
|
|
49
|
-
# Update data with new root for self
|
|
50
|
-
self.data = [(str(Path(self.root).joinpath(img_path)), label) for img_path, label in self.data]
|
|
50
|
+
# Update data with new root for self (absolute paths, a relative one would be read from the new root)
|
|
51
|
+
self.data = [(str(Path(self.root).absolute().joinpath(img_path)), label) for img_path, label in self.data]
|
|
51
52
|
# Define new root
|
|
52
53
|
self.root = Path("/")
|
|
53
54
|
# Merge with ds data
|
|
54
55
|
for img_path, label in ds.data:
|
|
55
|
-
self.data.append((str(Path(ds.root).joinpath(img_path)), label))
|
|
56
|
+
self.data.append((str(Path(ds.root).absolute().joinpath(img_path)), label))
|
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
|
|
@@ -77,8 +78,9 @@ class SVT(VisionDataset):
|
|
|
77
78
|
name, _, _, _resolution, rectangles = image
|
|
78
79
|
|
|
79
80
|
# File existence check
|
|
80
|
-
|
|
81
|
-
|
|
81
|
+
img_name = name.text
|
|
82
|
+
if not img_name or not os.path.exists(os.path.join(tmp_root, img_name)):
|
|
83
|
+
raise FileNotFoundError(f"unable to locate {os.path.join(tmp_root, img_name or '')}")
|
|
82
84
|
|
|
83
85
|
if use_polygons:
|
|
84
86
|
# (x, y) coordinates of top left, top right, bottom right, bottom left corners
|
|
@@ -111,14 +113,14 @@ class SVT(VisionDataset):
|
|
|
111
113
|
labels = [lab.text for rect in rectangles for lab in rect]
|
|
112
114
|
|
|
113
115
|
if recognition_task:
|
|
114
|
-
crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root,
|
|
116
|
+
crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root, img_name), geoms=boxes)
|
|
115
117
|
for crop, label in zip(crops, labels):
|
|
116
|
-
if crop.shape[0] > 0 and crop.shape[1] > 0 and
|
|
118
|
+
if crop.shape[0] > 0 and crop.shape[1] > 0 and label and " " not in label:
|
|
117
119
|
self.data.append((crop, label))
|
|
118
120
|
elif detection_task:
|
|
119
|
-
self.data.append((
|
|
121
|
+
self.data.append((img_name, boxes))
|
|
120
122
|
else:
|
|
121
|
-
self.data.append((
|
|
123
|
+
self.data.append((img_name, dict(boxes=boxes, labels=labels)))
|
|
122
124
|
|
|
123
125
|
self.root = tmp_root
|
|
124
126
|
|
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
|
@@ -3,11 +3,12 @@
|
|
|
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
|
+
import re
|
|
6
7
|
import string
|
|
7
8
|
import unicodedata
|
|
8
9
|
from collections.abc import Sequence
|
|
9
10
|
from collections.abc import Sequence as SequenceType
|
|
10
|
-
from functools import
|
|
11
|
+
from functools import lru_cache
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
from typing import Any, TypeVar
|
|
13
14
|
|
|
@@ -21,6 +22,8 @@ from .vocabs import VOCABS
|
|
|
21
22
|
|
|
22
23
|
__all__ = [
|
|
23
24
|
"translate",
|
|
25
|
+
"tokenize_latex",
|
|
26
|
+
"normalize_latex",
|
|
24
27
|
"encode_string",
|
|
25
28
|
"decode_sequence",
|
|
26
29
|
"encode_sequences",
|
|
@@ -66,53 +69,121 @@ def translate(
|
|
|
66
69
|
return translated
|
|
67
70
|
|
|
68
71
|
|
|
72
|
+
# A LaTeX token: an environment delimiter (e.g. \begin{array}), a command (e.g. \frac, \operatorname*), a control
|
|
73
|
+
# symbol (e.g. \{, \, or \\) or any other non-whitespace character
|
|
74
|
+
_LATEX_TOKEN = re.compile(r"\\(?:begin|end)\s*\{[a-zA-Z]+\*?\}|\\[a-zA-Z]+\*?|\\.|\S", re.DOTALL)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def tokenize_latex(latex: str) -> list[str]:
|
|
78
|
+
r"""Split a LaTeX string into tokens: commands, environment delimiters, control symbols and single characters
|
|
79
|
+
|
|
80
|
+
>>> from doctr.datasets import tokenize_latex
|
|
81
|
+
>>> tokenize_latex(r"\frac{a}{b^2}")
|
|
82
|
+
['\\frac', '{', 'a', '}', '{', 'b', '^', '2', '}']
|
|
83
|
+
|
|
84
|
+
The whitespaces are not part of the tokens (a control space `\ ` is tokenized as `\space`, which renders the same):
|
|
85
|
+
tokenizing a string and joining the tokens with spaces gives a normalized string which tokenizes into the same
|
|
86
|
+
tokens.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
latex: the LaTeX string to tokenize
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
the list of tokens
|
|
93
|
+
"""
|
|
94
|
+
tokens = []
|
|
95
|
+
for tok in _LATEX_TOKEN.findall(latex):
|
|
96
|
+
if tok.startswith(("\\begin", "\\end")):
|
|
97
|
+
# Drop the whitespaces between an environment delimiter and its name (e.g. "\begin {array}")
|
|
98
|
+
tok = re.sub(r"\s+", "", tok)
|
|
99
|
+
elif len(tok) == 2 and tok[1].isspace():
|
|
100
|
+
tok = "\\space"
|
|
101
|
+
tokens.append(tok)
|
|
102
|
+
return tokens
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def normalize_latex(latex: str) -> str:
|
|
106
|
+
r"""Normalize a LaTeX string into space-separated tokens (cf. :func:`tokenize_latex`)
|
|
107
|
+
|
|
108
|
+
>>> from doctr.datasets import normalize_latex
|
|
109
|
+
>>> normalize_latex(r"\frac{a}{b^2}")
|
|
110
|
+
'\\frac { a } { b ^ 2 }'
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
latex: the LaTeX string to normalize
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
the normalized string, rendering the same as the input
|
|
117
|
+
"""
|
|
118
|
+
return " ".join(tokenize_latex(latex))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@lru_cache(maxsize=32)
|
|
122
|
+
def _vocab_lookup_table(vocab: str | tuple[str, ...]) -> dict[str, int]:
|
|
123
|
+
"""Cached token -> index table for a vocab (the first occurrence of a duplicated token wins)"""
|
|
124
|
+
return {token: idx for idx, token in reversed(list(enumerate(vocab)))}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _split_tokens(input_string: str, vocab: str | Sequence[str]) -> list[str]:
|
|
128
|
+
"""Split a string into the units of a vocab: characters for a string vocab, whitespace-separated tokens for a
|
|
129
|
+
list of tokens"""
|
|
130
|
+
return list(input_string) if isinstance(vocab, str) else input_string.split()
|
|
131
|
+
|
|
132
|
+
|
|
69
133
|
def encode_string(
|
|
70
134
|
input_string: str,
|
|
71
|
-
vocab: str,
|
|
135
|
+
vocab: str | Sequence[str],
|
|
72
136
|
) -> list[int]:
|
|
73
137
|
"""Given a predefined mapping, encode the string to a sequence of numbers
|
|
74
138
|
|
|
75
139
|
Args:
|
|
76
140
|
input_string: string to encode
|
|
77
|
-
vocab: vocabulary
|
|
141
|
+
vocab: vocabulary, the encoding is given by the indexing of its units: a string of characters, or a list of
|
|
142
|
+
tokens (e.g. LaTeX commands), in which case the input string is split on whitespaces
|
|
78
143
|
|
|
79
144
|
Returns:
|
|
80
145
|
A list encoding the input_string
|
|
81
146
|
"""
|
|
147
|
+
table = _vocab_lookup_table(vocab if isinstance(vocab, str) else tuple(vocab))
|
|
148
|
+
tokens = _split_tokens(input_string, vocab)
|
|
82
149
|
try:
|
|
83
|
-
return
|
|
84
|
-
except
|
|
85
|
-
|
|
150
|
+
return [table[token] for token in tokens]
|
|
151
|
+
except KeyError as e:
|
|
152
|
+
missing = [token for token in tokens if token not in table]
|
|
86
153
|
raise ValueError(
|
|
87
|
-
f"Some characters cannot be found in 'vocab': {set(
|
|
154
|
+
f"Some characters cannot be found in 'vocab': {set(missing)}.\n"
|
|
88
155
|
f"Please check the input string `{input_string}` and the vocabulary `{vocab}`"
|
|
89
156
|
) from e
|
|
90
157
|
|
|
91
158
|
|
|
92
159
|
def decode_sequence(
|
|
93
160
|
input_seq: np.ndarray | SequenceType[int],
|
|
94
|
-
mapping: str,
|
|
161
|
+
mapping: str | Sequence[str],
|
|
95
162
|
) -> str:
|
|
96
163
|
"""Given a predefined mapping, decode the sequence of numbers to a string
|
|
97
164
|
|
|
98
165
|
Args:
|
|
99
166
|
input_seq: array to decode
|
|
100
|
-
mapping: vocabulary
|
|
167
|
+
mapping: vocabulary, the encoding is given by the indexing of its units: a string of characters, or a list of
|
|
168
|
+
tokens, in which case the decoded tokens are joined with spaces
|
|
101
169
|
|
|
102
170
|
Returns:
|
|
103
171
|
A string, decoded from input_seq
|
|
104
172
|
"""
|
|
105
173
|
if not isinstance(input_seq, (Sequence, np.ndarray)):
|
|
106
174
|
raise TypeError("Invalid sequence type")
|
|
107
|
-
if isinstance(input_seq, np.ndarray) and (input_seq.dtype
|
|
108
|
-
raise AssertionError("Input must be an array of int, with
|
|
175
|
+
if isinstance(input_seq, np.ndarray) and not np.issubdtype(input_seq.dtype, np.integer):
|
|
176
|
+
raise AssertionError("Input must be an array of int, with values between 0 and the mapping size")
|
|
177
|
+
# A negative index would silently wrap around to the end of the mapping (e.g. an EOS of -1 read as a char)
|
|
178
|
+
if len(input_seq) > 0 and (min(input_seq) < 0 or max(input_seq) >= len(mapping)):
|
|
179
|
+
raise AssertionError("Input must be an array of int, with values between 0 and the mapping size")
|
|
109
180
|
|
|
110
|
-
return "".join(map(mapping.__getitem__, input_seq))
|
|
181
|
+
return ("" if isinstance(mapping, str) else " ").join(map(mapping.__getitem__, input_seq))
|
|
111
182
|
|
|
112
183
|
|
|
113
184
|
def encode_sequences(
|
|
114
185
|
sequences: list[str],
|
|
115
|
-
vocab: str,
|
|
186
|
+
vocab: str | Sequence[str],
|
|
116
187
|
target_size: int | None = None,
|
|
117
188
|
eos: int = -1,
|
|
118
189
|
sos: int | None = None,
|
|
@@ -123,7 +194,8 @@ def encode_sequences(
|
|
|
123
194
|
|
|
124
195
|
Args:
|
|
125
196
|
sequences: the list of character sequences of size N
|
|
126
|
-
vocab: the ordered vocab to use for encoding
|
|
197
|
+
vocab: the ordered vocab to use for encoding: a string of characters, or a list of tokens (cf.
|
|
198
|
+
:func:`encode_string`)
|
|
127
199
|
target_size: maximum length of the encoded data
|
|
128
200
|
eos: encoding of End Of String
|
|
129
201
|
sos: optional encoding of Start Of String
|
|
@@ -136,9 +208,10 @@ def encode_sequences(
|
|
|
136
208
|
if 0 <= eos < len(vocab):
|
|
137
209
|
raise ValueError("argument 'eos' needs to be outside of vocab possible indices")
|
|
138
210
|
|
|
211
|
+
encoded_seqs = [encode_string(seq, vocab) for seq in sequences]
|
|
139
212
|
if not isinstance(target_size, int) or dynamic_seq_length:
|
|
140
|
-
# Maximum
|
|
141
|
-
max_length = max(len(
|
|
213
|
+
# Maximum sequence length (in vocab units) + EOS
|
|
214
|
+
max_length = max((len(seq) for seq in encoded_seqs), default=0) + 1
|
|
142
215
|
if isinstance(sos, int):
|
|
143
216
|
max_length += 1
|
|
144
217
|
if isinstance(pad, int):
|
|
@@ -156,7 +229,7 @@ def encode_sequences(
|
|
|
156
229
|
encoded_data: np.ndarray = np.full([len(sequences), target_size], default_symbol, dtype=np.int32)
|
|
157
230
|
|
|
158
231
|
# Encode the strings
|
|
159
|
-
for idx, seq in enumerate(
|
|
232
|
+
for idx, seq in enumerate(encoded_seqs):
|
|
160
233
|
if isinstance(pad, int): # add eos at the end of the sequence
|
|
161
234
|
seq.append(eos)
|
|
162
235
|
encoded_data[idx, : min(len(seq), target_size)] = seq[: min(len(seq), target_size)]
|
|
@@ -209,20 +282,30 @@ def crop_bboxes_from_image(img_path: str | Path, geoms: np.ndarray) -> list[np.n
|
|
|
209
282
|
raise ValueError("Invalid geometry format")
|
|
210
283
|
|
|
211
284
|
|
|
212
|
-
def pre_transform_multiclass(
|
|
285
|
+
def pre_transform_multiclass(
|
|
286
|
+
img, target: tuple[np.ndarray, list], class_names: list[str] | None = None
|
|
287
|
+
) -> tuple[np.ndarray, dict[str, np.ndarray]]:
|
|
213
288
|
"""Converts multiclass target to relative coordinates.
|
|
214
289
|
|
|
215
290
|
Args:
|
|
216
291
|
img: Image
|
|
217
292
|
target: tuple of target polygons and their classes names
|
|
293
|
+
class_names: if given, the returned dictionary contains exactly these classes, in this order.
|
|
294
|
+
Classes without any box in this sample map to an empty array. This keeps the class -> channel
|
|
295
|
+
mapping stable across samples, which the detection models rely on.
|
|
218
296
|
|
|
219
297
|
Returns:
|
|
220
298
|
Image and dictionary of boxes, with class names as keys
|
|
221
299
|
"""
|
|
222
300
|
boxes = convert_to_relative_coords(target[0], get_img_shape(img))
|
|
223
301
|
boxes_classes = target[1]
|
|
224
|
-
|
|
302
|
+
keys = list(class_names) if class_names is not None else sorted(set(boxes_classes))
|
|
303
|
+
boxes_dict: dict[str, list] = {k: [] for k in keys}
|
|
225
304
|
for k, poly in zip(boxes_classes, boxes):
|
|
305
|
+
if k not in boxes_dict:
|
|
306
|
+
raise ValueError(f"unknown class '{k}', expected one of {keys}")
|
|
226
307
|
boxes_dict[k].append(poly)
|
|
227
|
-
|
|
228
|
-
|
|
308
|
+
return img, {
|
|
309
|
+
k: np.stack(v, axis=0) if v else np.zeros((0, *boxes.shape[1:]), dtype=boxes.dtype)
|
|
310
|
+
for k, v in boxes_dict.items()
|
|
311
|
+
}
|