python-doctr 0.8.0__py3-none-any.whl → 0.9.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/__init__.py +1 -1
- doctr/contrib/__init__.py +0 -0
- doctr/contrib/artefacts.py +131 -0
- doctr/contrib/base.py +105 -0
- doctr/datasets/datasets/pytorch.py +2 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/imgur5k.py +1 -1
- doctr/datasets/loader.py +1 -6
- doctr/datasets/utils.py +2 -1
- doctr/datasets/vocabs.py +9 -2
- doctr/file_utils.py +26 -12
- doctr/io/elements.py +40 -6
- doctr/io/html.py +2 -2
- doctr/io/image/pytorch.py +6 -8
- doctr/io/image/tensorflow.py +1 -1
- doctr/io/pdf.py +5 -2
- doctr/io/reader.py +6 -0
- doctr/models/__init__.py +0 -1
- doctr/models/_utils.py +57 -20
- doctr/models/builder.py +71 -13
- doctr/models/classification/mobilenet/pytorch.py +45 -9
- doctr/models/classification/mobilenet/tensorflow.py +38 -7
- doctr/models/classification/predictor/pytorch.py +18 -11
- doctr/models/classification/predictor/tensorflow.py +16 -10
- doctr/models/classification/textnet/pytorch.py +3 -3
- doctr/models/classification/textnet/tensorflow.py +3 -3
- doctr/models/classification/zoo.py +39 -15
- doctr/models/detection/__init__.py +1 -0
- doctr/models/detection/_utils/__init__.py +1 -0
- doctr/models/detection/_utils/base.py +66 -0
- doctr/models/detection/differentiable_binarization/base.py +4 -3
- doctr/models/detection/differentiable_binarization/pytorch.py +2 -2
- doctr/models/detection/differentiable_binarization/tensorflow.py +14 -18
- doctr/models/detection/fast/__init__.py +6 -0
- doctr/models/detection/fast/base.py +257 -0
- doctr/models/detection/fast/pytorch.py +442 -0
- doctr/models/detection/fast/tensorflow.py +428 -0
- doctr/models/detection/linknet/base.py +4 -3
- doctr/models/detection/predictor/pytorch.py +15 -1
- doctr/models/detection/predictor/tensorflow.py +15 -1
- doctr/models/detection/zoo.py +21 -4
- doctr/models/factory/hub.py +3 -12
- doctr/models/kie_predictor/base.py +9 -3
- doctr/models/kie_predictor/pytorch.py +41 -20
- doctr/models/kie_predictor/tensorflow.py +36 -16
- doctr/models/modules/layers/pytorch.py +89 -10
- doctr/models/modules/layers/tensorflow.py +88 -10
- doctr/models/modules/transformer/pytorch.py +2 -2
- doctr/models/predictor/base.py +77 -50
- doctr/models/predictor/pytorch.py +31 -20
- doctr/models/predictor/tensorflow.py +27 -17
- doctr/models/preprocessor/pytorch.py +4 -4
- doctr/models/preprocessor/tensorflow.py +3 -2
- doctr/models/recognition/master/pytorch.py +2 -2
- doctr/models/recognition/parseq/pytorch.py +4 -3
- doctr/models/recognition/parseq/tensorflow.py +4 -3
- doctr/models/recognition/sar/pytorch.py +7 -6
- doctr/models/recognition/sar/tensorflow.py +3 -9
- doctr/models/recognition/vitstr/pytorch.py +1 -1
- doctr/models/recognition/zoo.py +1 -1
- doctr/models/zoo.py +2 -2
- doctr/py.typed +0 -0
- doctr/transforms/functional/base.py +1 -1
- doctr/transforms/functional/pytorch.py +4 -4
- doctr/transforms/modules/base.py +37 -15
- doctr/transforms/modules/pytorch.py +66 -8
- doctr/transforms/modules/tensorflow.py +63 -7
- doctr/utils/fonts.py +7 -5
- doctr/utils/geometry.py +35 -12
- doctr/utils/metrics.py +33 -174
- doctr/utils/reconstitution.py +126 -0
- doctr/utils/visualization.py +5 -118
- doctr/version.py +1 -1
- {python_doctr-0.8.0.dist-info → python_doctr-0.9.0.dist-info}/METADATA +96 -91
- {python_doctr-0.8.0.dist-info → python_doctr-0.9.0.dist-info}/RECORD +79 -75
- {python_doctr-0.8.0.dist-info → python_doctr-0.9.0.dist-info}/WHEEL +1 -1
- doctr/models/artefacts/__init__.py +0 -2
- doctr/models/artefacts/barcode.py +0 -74
- doctr/models/artefacts/face.py +0 -63
- doctr/models/obj_detection/__init__.py +0 -1
- doctr/models/obj_detection/faster_rcnn/__init__.py +0 -4
- doctr/models/obj_detection/faster_rcnn/pytorch.py +0 -81
- {python_doctr-0.8.0.dist-info → python_doctr-0.9.0.dist-info}/LICENSE +0 -0
- {python_doctr-0.8.0.dist-info → python_doctr-0.9.0.dist-info}/top_level.txt +0 -0
- {python_doctr-0.8.0.dist-info → python_doctr-0.9.0.dist-info}/zip-safe +0 -0
doctr/models/predictor/base.py
CHANGED
|
@@ -3,16 +3,16 @@
|
|
|
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 typing import Any, Callable, List, Optional, Tuple
|
|
6
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
7
7
|
|
|
8
8
|
import numpy as np
|
|
9
9
|
|
|
10
10
|
from doctr.models.builder import DocumentBuilder
|
|
11
|
-
from doctr.utils.geometry import extract_crops, extract_rcrops
|
|
11
|
+
from doctr.utils.geometry import extract_crops, extract_rcrops, rotate_image
|
|
12
12
|
|
|
13
|
-
from .._utils import rectify_crops, rectify_loc_preds
|
|
14
|
-
from ..classification import crop_orientation_predictor
|
|
15
|
-
from ..classification.predictor import
|
|
13
|
+
from .._utils import estimate_orientation, rectify_crops, rectify_loc_preds
|
|
14
|
+
from ..classification import crop_orientation_predictor, page_orientation_predictor
|
|
15
|
+
from ..classification.predictor import OrientationPredictor
|
|
16
16
|
|
|
17
17
|
__all__ = ["_OCRPredictor"]
|
|
18
18
|
|
|
@@ -29,10 +29,13 @@ class _OCRPredictor:
|
|
|
29
29
|
accordingly. Doing so will improve performances for documents with page-uniform rotations.
|
|
30
30
|
preserve_aspect_ratio: if True, resize preserving the aspect ratio (with padding)
|
|
31
31
|
symmetric_pad: if True and preserve_aspect_ratio is True, pas the image symmetrically.
|
|
32
|
+
detect_orientation: if True, the estimated general page orientation will be added to the predictions for each
|
|
33
|
+
page. Doing so will slightly deteriorate the overall latency.
|
|
32
34
|
**kwargs: keyword args of `DocumentBuilder`
|
|
33
35
|
"""
|
|
34
36
|
|
|
35
|
-
crop_orientation_predictor: Optional[
|
|
37
|
+
crop_orientation_predictor: Optional[OrientationPredictor]
|
|
38
|
+
page_orientation_predictor: Optional[OrientationPredictor]
|
|
36
39
|
|
|
37
40
|
def __init__(
|
|
38
41
|
self,
|
|
@@ -40,16 +43,69 @@ class _OCRPredictor:
|
|
|
40
43
|
straighten_pages: bool = False,
|
|
41
44
|
preserve_aspect_ratio: bool = True,
|
|
42
45
|
symmetric_pad: bool = True,
|
|
46
|
+
detect_orientation: bool = False,
|
|
43
47
|
**kwargs: Any,
|
|
44
48
|
) -> None:
|
|
45
49
|
self.assume_straight_pages = assume_straight_pages
|
|
46
50
|
self.straighten_pages = straighten_pages
|
|
47
51
|
self.crop_orientation_predictor = None if assume_straight_pages else crop_orientation_predictor(pretrained=True)
|
|
52
|
+
self.page_orientation_predictor = (
|
|
53
|
+
page_orientation_predictor(pretrained=True)
|
|
54
|
+
if detect_orientation or straighten_pages or not assume_straight_pages
|
|
55
|
+
else None
|
|
56
|
+
)
|
|
48
57
|
self.doc_builder = DocumentBuilder(**kwargs)
|
|
49
58
|
self.preserve_aspect_ratio = preserve_aspect_ratio
|
|
50
59
|
self.symmetric_pad = symmetric_pad
|
|
51
60
|
self.hooks: List[Callable] = []
|
|
52
61
|
|
|
62
|
+
def _general_page_orientations(
|
|
63
|
+
self,
|
|
64
|
+
pages: List[np.ndarray],
|
|
65
|
+
) -> List[Tuple[int, float]]:
|
|
66
|
+
_, classes, probs = zip(self.page_orientation_predictor(pages)) # type: ignore[misc]
|
|
67
|
+
# Flatten to list of tuples with (value, confidence)
|
|
68
|
+
page_orientations = [
|
|
69
|
+
(orientation, prob)
|
|
70
|
+
for page_classes, page_probs in zip(classes, probs)
|
|
71
|
+
for orientation, prob in zip(page_classes, page_probs)
|
|
72
|
+
]
|
|
73
|
+
return page_orientations
|
|
74
|
+
|
|
75
|
+
def _get_orientations(
|
|
76
|
+
self, pages: List[np.ndarray], seg_maps: List[np.ndarray]
|
|
77
|
+
) -> Tuple[List[Tuple[int, float]], List[int]]:
|
|
78
|
+
general_pages_orientations = self._general_page_orientations(pages)
|
|
79
|
+
origin_page_orientations = [
|
|
80
|
+
estimate_orientation(seq_map, general_orientation)
|
|
81
|
+
for seq_map, general_orientation in zip(seg_maps, general_pages_orientations)
|
|
82
|
+
]
|
|
83
|
+
return general_pages_orientations, origin_page_orientations
|
|
84
|
+
|
|
85
|
+
def _straighten_pages(
|
|
86
|
+
self,
|
|
87
|
+
pages: List[np.ndarray],
|
|
88
|
+
seg_maps: List[np.ndarray],
|
|
89
|
+
general_pages_orientations: Optional[List[Tuple[int, float]]] = None,
|
|
90
|
+
origin_pages_orientations: Optional[List[int]] = None,
|
|
91
|
+
) -> List[np.ndarray]:
|
|
92
|
+
general_pages_orientations = (
|
|
93
|
+
general_pages_orientations if general_pages_orientations else self._general_page_orientations(pages)
|
|
94
|
+
)
|
|
95
|
+
origin_pages_orientations = (
|
|
96
|
+
origin_pages_orientations
|
|
97
|
+
if origin_pages_orientations
|
|
98
|
+
else [
|
|
99
|
+
estimate_orientation(seq_map, general_orientation)
|
|
100
|
+
for seq_map, general_orientation in zip(seg_maps, general_pages_orientations)
|
|
101
|
+
]
|
|
102
|
+
)
|
|
103
|
+
return [
|
|
104
|
+
# We exapnd if the page is wider than tall and the angle is 90 or -90
|
|
105
|
+
rotate_image(page, angle, expand=page.shape[1] > page.shape[0] and abs(angle) == 90)
|
|
106
|
+
for page, angle in zip(pages, origin_pages_orientations)
|
|
107
|
+
]
|
|
108
|
+
|
|
53
109
|
@staticmethod
|
|
54
110
|
def _generate_crops(
|
|
55
111
|
pages: List[np.ndarray],
|
|
@@ -88,68 +144,39 @@ class _OCRPredictor:
|
|
|
88
144
|
self,
|
|
89
145
|
crops: List[List[np.ndarray]],
|
|
90
146
|
loc_preds: List[np.ndarray],
|
|
91
|
-
) -> Tuple[List[List[np.ndarray]], List[np.ndarray]]:
|
|
147
|
+
) -> Tuple[List[List[np.ndarray]], List[np.ndarray], List[Tuple[int, float]]]:
|
|
92
148
|
# Work at a page level
|
|
93
|
-
orientations = [self.crop_orientation_predictor(page_crops) for page_crops in crops] # type: ignore[misc]
|
|
149
|
+
orientations, classes, probs = zip(*[self.crop_orientation_predictor(page_crops) for page_crops in crops]) # type: ignore[misc]
|
|
94
150
|
rect_crops = [rectify_crops(page_crops, orientation) for page_crops, orientation in zip(crops, orientations)]
|
|
95
151
|
rect_loc_preds = [
|
|
96
152
|
rectify_loc_preds(page_loc_preds, orientation) if len(page_loc_preds) > 0 else page_loc_preds
|
|
97
153
|
for page_loc_preds, orientation in zip(loc_preds, orientations)
|
|
98
154
|
]
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
if self.preserve_aspect_ratio:
|
|
107
|
-
# Rectify loc_preds to remove padding
|
|
108
|
-
rectified_preds = []
|
|
109
|
-
for page, loc_pred in zip(pages, loc_preds):
|
|
110
|
-
h, w = page.shape[0], page.shape[1]
|
|
111
|
-
if h > w:
|
|
112
|
-
# y unchanged, dilate x coord
|
|
113
|
-
if self.symmetric_pad:
|
|
114
|
-
if self.assume_straight_pages:
|
|
115
|
-
loc_pred[:, [0, 2]] = np.clip((loc_pred[:, [0, 2]] - 0.5) * h / w + 0.5, 0, 1)
|
|
116
|
-
else:
|
|
117
|
-
loc_pred[:, :, 0] = np.clip((loc_pred[:, :, 0] - 0.5) * h / w + 0.5, 0, 1)
|
|
118
|
-
else:
|
|
119
|
-
if self.assume_straight_pages:
|
|
120
|
-
loc_pred[:, [0, 2]] *= h / w
|
|
121
|
-
else:
|
|
122
|
-
loc_pred[:, :, 0] *= h / w
|
|
123
|
-
elif w > h:
|
|
124
|
-
# x unchanged, dilate y coord
|
|
125
|
-
if self.symmetric_pad:
|
|
126
|
-
if self.assume_straight_pages:
|
|
127
|
-
loc_pred[:, [1, 3]] = np.clip((loc_pred[:, [1, 3]] - 0.5) * w / h + 0.5, 0, 1)
|
|
128
|
-
else:
|
|
129
|
-
loc_pred[:, :, 1] = np.clip((loc_pred[:, :, 1] - 0.5) * w / h + 0.5, 0, 1)
|
|
130
|
-
else:
|
|
131
|
-
if self.assume_straight_pages:
|
|
132
|
-
loc_pred[:, [1, 3]] *= w / h
|
|
133
|
-
else:
|
|
134
|
-
loc_pred[:, :, 1] *= w / h
|
|
135
|
-
rectified_preds.append(loc_pred)
|
|
136
|
-
return rectified_preds
|
|
137
|
-
return loc_preds
|
|
155
|
+
# Flatten to list of tuples with (value, confidence)
|
|
156
|
+
crop_orientations = [
|
|
157
|
+
(orientation, prob)
|
|
158
|
+
for page_classes, page_probs in zip(classes, probs)
|
|
159
|
+
for orientation, prob in zip(page_classes, page_probs)
|
|
160
|
+
]
|
|
161
|
+
return rect_crops, rect_loc_preds, crop_orientations # type: ignore[return-value]
|
|
138
162
|
|
|
139
163
|
@staticmethod
|
|
140
164
|
def _process_predictions(
|
|
141
165
|
loc_preds: List[np.ndarray],
|
|
142
166
|
word_preds: List[Tuple[str, float]],
|
|
143
|
-
|
|
167
|
+
crop_orientations: List[Dict[str, Any]],
|
|
168
|
+
) -> Tuple[List[np.ndarray], List[List[Tuple[str, float]]], List[List[Dict[str, Any]]]]:
|
|
144
169
|
text_preds = []
|
|
170
|
+
crop_orientation_preds = []
|
|
145
171
|
if len(loc_preds) > 0:
|
|
146
|
-
# Text
|
|
172
|
+
# Text & crop orientation predictions at page level
|
|
147
173
|
_idx = 0
|
|
148
174
|
for page_boxes in loc_preds:
|
|
149
175
|
text_preds.append(word_preds[_idx : _idx + page_boxes.shape[0]])
|
|
176
|
+
crop_orientation_preds.append(crop_orientations[_idx : _idx + page_boxes.shape[0]])
|
|
150
177
|
_idx += page_boxes.shape[0]
|
|
151
178
|
|
|
152
|
-
return loc_preds, text_preds
|
|
179
|
+
return loc_preds, text_preds, crop_orientation_preds
|
|
153
180
|
|
|
154
181
|
def add_hook(self, hook: Callable) -> None:
|
|
155
182
|
"""Add a hook to the predictor
|
|
@@ -10,10 +10,10 @@ import torch
|
|
|
10
10
|
from torch import nn
|
|
11
11
|
|
|
12
12
|
from doctr.io.elements import Document
|
|
13
|
-
from doctr.models._utils import
|
|
13
|
+
from doctr.models._utils import get_language
|
|
14
14
|
from doctr.models.detection.predictor import DetectionPredictor
|
|
15
15
|
from doctr.models.recognition.predictor import RecognitionPredictor
|
|
16
|
-
from doctr.utils.geometry import
|
|
16
|
+
from doctr.utils.geometry import detach_scores
|
|
17
17
|
|
|
18
18
|
from .base import _OCRPredictor
|
|
19
19
|
|
|
@@ -55,7 +55,13 @@ class OCRPredictor(nn.Module, _OCRPredictor):
|
|
|
55
55
|
self.det_predictor = det_predictor.eval() # type: ignore[attr-defined]
|
|
56
56
|
self.reco_predictor = reco_predictor.eval() # type: ignore[attr-defined]
|
|
57
57
|
_OCRPredictor.__init__(
|
|
58
|
-
self,
|
|
58
|
+
self,
|
|
59
|
+
assume_straight_pages,
|
|
60
|
+
straighten_pages,
|
|
61
|
+
preserve_aspect_ratio,
|
|
62
|
+
symmetric_pad,
|
|
63
|
+
detect_orientation,
|
|
64
|
+
**kwargs,
|
|
59
65
|
)
|
|
60
66
|
self.detect_orientation = detect_orientation
|
|
61
67
|
self.detect_language = detect_language
|
|
@@ -81,19 +87,16 @@ class OCRPredictor(nn.Module, _OCRPredictor):
|
|
|
81
87
|
for out_map in out_maps
|
|
82
88
|
]
|
|
83
89
|
if self.detect_orientation:
|
|
84
|
-
|
|
90
|
+
general_pages_orientations, origin_pages_orientations = self._get_orientations(pages, seg_maps) # type: ignore[arg-type]
|
|
85
91
|
orientations = [
|
|
86
|
-
{"value": orientation_page, "confidence": None} for orientation_page in
|
|
92
|
+
{"value": orientation_page, "confidence": None} for orientation_page in origin_pages_orientations
|
|
87
93
|
]
|
|
88
94
|
else:
|
|
89
95
|
orientations = None
|
|
96
|
+
general_pages_orientations = None
|
|
97
|
+
origin_pages_orientations = None
|
|
90
98
|
if self.straighten_pages:
|
|
91
|
-
|
|
92
|
-
origin_page_orientations
|
|
93
|
-
if self.detect_orientation
|
|
94
|
-
else [estimate_orientation(seq_map) for seq_map in seg_maps]
|
|
95
|
-
)
|
|
96
|
-
pages = [rotate_image(page, -angle, expand=False) for page, angle in zip(pages, origin_page_orientations)]
|
|
99
|
+
pages = self._straighten_pages(pages, seg_maps, general_pages_orientations, origin_pages_orientations) # type: ignore
|
|
97
100
|
# Forward again to get predictions on straight pages
|
|
98
101
|
loc_preds = self.det_predictor(pages, **kwargs)
|
|
99
102
|
|
|
@@ -102,30 +105,36 @@ class OCRPredictor(nn.Module, _OCRPredictor):
|
|
|
102
105
|
), "Detection Model in ocr_predictor should output only one class"
|
|
103
106
|
|
|
104
107
|
loc_preds = [list(loc_pred.values())[0] for loc_pred in loc_preds]
|
|
108
|
+
# Detach objectness scores from loc_preds
|
|
109
|
+
loc_preds, objectness_scores = detach_scores(loc_preds)
|
|
105
110
|
# Check whether crop mode should be switched to channels first
|
|
106
111
|
channels_last = len(pages) == 0 or isinstance(pages[0], np.ndarray)
|
|
107
112
|
|
|
108
|
-
# Rectify crops if aspect ratio
|
|
109
|
-
loc_preds = self._remove_padding(pages, loc_preds)
|
|
110
|
-
|
|
111
113
|
# Apply hooks to loc_preds if any
|
|
112
114
|
for hook in self.hooks:
|
|
113
115
|
loc_preds = hook(loc_preds)
|
|
114
116
|
|
|
115
117
|
# Crop images
|
|
116
118
|
crops, loc_preds = self._prepare_crops(
|
|
117
|
-
pages,
|
|
119
|
+
pages, # type: ignore[arg-type]
|
|
118
120
|
loc_preds,
|
|
119
121
|
channels_last=channels_last,
|
|
120
122
|
assume_straight_pages=self.assume_straight_pages,
|
|
121
123
|
)
|
|
122
|
-
# Rectify crop orientation
|
|
124
|
+
# Rectify crop orientation and get crop orientation predictions
|
|
125
|
+
crop_orientations: Any = []
|
|
123
126
|
if not self.assume_straight_pages:
|
|
124
|
-
crops, loc_preds = self._rectify_crops(crops, loc_preds)
|
|
127
|
+
crops, loc_preds, _crop_orientations = self._rectify_crops(crops, loc_preds)
|
|
128
|
+
crop_orientations = [
|
|
129
|
+
{"value": orientation[0], "confidence": orientation[1]} for orientation in _crop_orientations
|
|
130
|
+
]
|
|
131
|
+
|
|
125
132
|
# Identify character sequences
|
|
126
133
|
word_preds = self.reco_predictor([crop for page_crops in crops for crop in page_crops], **kwargs)
|
|
134
|
+
if not crop_orientations:
|
|
135
|
+
crop_orientations = [{"value": 0, "confidence": None} for _ in word_preds]
|
|
127
136
|
|
|
128
|
-
boxes, text_preds = self._process_predictions(loc_preds, word_preds)
|
|
137
|
+
boxes, text_preds, crop_orientations = self._process_predictions(loc_preds, word_preds, crop_orientations)
|
|
129
138
|
|
|
130
139
|
if self.detect_language:
|
|
131
140
|
languages = [get_language(" ".join([item[0] for item in text_pred])) for text_pred in text_preds]
|
|
@@ -134,10 +143,12 @@ class OCRPredictor(nn.Module, _OCRPredictor):
|
|
|
134
143
|
languages_dict = None
|
|
135
144
|
|
|
136
145
|
out = self.doc_builder(
|
|
137
|
-
pages,
|
|
146
|
+
pages, # type: ignore[arg-type]
|
|
138
147
|
boxes,
|
|
148
|
+
objectness_scores,
|
|
139
149
|
text_preds,
|
|
140
|
-
origin_page_shapes,
|
|
150
|
+
origin_page_shapes, # type: ignore[arg-type]
|
|
151
|
+
crop_orientations,
|
|
141
152
|
orientations,
|
|
142
153
|
languages_dict,
|
|
143
154
|
)
|
|
@@ -9,10 +9,10 @@ import numpy as np
|
|
|
9
9
|
import tensorflow as tf
|
|
10
10
|
|
|
11
11
|
from doctr.io.elements import Document
|
|
12
|
-
from doctr.models._utils import
|
|
12
|
+
from doctr.models._utils import get_language
|
|
13
13
|
from doctr.models.detection.predictor import DetectionPredictor
|
|
14
14
|
from doctr.models.recognition.predictor import RecognitionPredictor
|
|
15
|
-
from doctr.utils.geometry import
|
|
15
|
+
from doctr.utils.geometry import detach_scores
|
|
16
16
|
from doctr.utils.repr import NestedObject
|
|
17
17
|
|
|
18
18
|
from .base import _OCRPredictor
|
|
@@ -56,7 +56,13 @@ class OCRPredictor(NestedObject, _OCRPredictor):
|
|
|
56
56
|
self.det_predictor = det_predictor
|
|
57
57
|
self.reco_predictor = reco_predictor
|
|
58
58
|
_OCRPredictor.__init__(
|
|
59
|
-
self,
|
|
59
|
+
self,
|
|
60
|
+
assume_straight_pages,
|
|
61
|
+
straighten_pages,
|
|
62
|
+
preserve_aspect_ratio,
|
|
63
|
+
symmetric_pad,
|
|
64
|
+
detect_orientation,
|
|
65
|
+
**kwargs,
|
|
60
66
|
)
|
|
61
67
|
self.detect_orientation = detect_orientation
|
|
62
68
|
self.detect_language = detect_language
|
|
@@ -81,19 +87,16 @@ class OCRPredictor(NestedObject, _OCRPredictor):
|
|
|
81
87
|
for out_map in out_maps
|
|
82
88
|
]
|
|
83
89
|
if self.detect_orientation:
|
|
84
|
-
|
|
90
|
+
general_pages_orientations, origin_pages_orientations = self._get_orientations(pages, seg_maps)
|
|
85
91
|
orientations = [
|
|
86
|
-
{"value": orientation_page, "confidence": None} for orientation_page in
|
|
92
|
+
{"value": orientation_page, "confidence": None} for orientation_page in origin_pages_orientations
|
|
87
93
|
]
|
|
88
94
|
else:
|
|
89
95
|
orientations = None
|
|
96
|
+
general_pages_orientations = None
|
|
97
|
+
origin_pages_orientations = None
|
|
90
98
|
if self.straighten_pages:
|
|
91
|
-
|
|
92
|
-
origin_page_orientations
|
|
93
|
-
if self.detect_orientation
|
|
94
|
-
else [estimate_orientation(seq_map) for seq_map in seg_maps]
|
|
95
|
-
)
|
|
96
|
-
pages = [rotate_image(page, -angle, expand=False) for page, angle in zip(pages, origin_page_orientations)]
|
|
99
|
+
pages = self._straighten_pages(pages, seg_maps, general_pages_orientations, origin_pages_orientations)
|
|
97
100
|
# forward again to get predictions on straight pages
|
|
98
101
|
loc_preds_dict = self.det_predictor(pages, **kwargs) # type: ignore[assignment]
|
|
99
102
|
|
|
@@ -101,9 +104,8 @@ class OCRPredictor(NestedObject, _OCRPredictor):
|
|
|
101
104
|
len(loc_pred) == 1 for loc_pred in loc_preds_dict
|
|
102
105
|
), "Detection Model in ocr_predictor should output only one class"
|
|
103
106
|
loc_preds: List[np.ndarray] = [list(loc_pred.values())[0] for loc_pred in loc_preds_dict] # type: ignore[union-attr]
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
loc_preds = self._remove_padding(pages, loc_preds)
|
|
107
|
+
# Detach objectness scores from loc_preds
|
|
108
|
+
loc_preds, objectness_scores = detach_scores(loc_preds)
|
|
107
109
|
|
|
108
110
|
# Apply hooks to loc_preds if any
|
|
109
111
|
for hook in self.hooks:
|
|
@@ -113,14 +115,20 @@ class OCRPredictor(NestedObject, _OCRPredictor):
|
|
|
113
115
|
crops, loc_preds = self._prepare_crops(
|
|
114
116
|
pages, loc_preds, channels_last=True, assume_straight_pages=self.assume_straight_pages
|
|
115
117
|
)
|
|
116
|
-
# Rectify crop orientation
|
|
118
|
+
# Rectify crop orientation and get crop orientation predictions
|
|
119
|
+
crop_orientations: Any = []
|
|
117
120
|
if not self.assume_straight_pages:
|
|
118
|
-
crops, loc_preds = self._rectify_crops(crops, loc_preds)
|
|
121
|
+
crops, loc_preds, _crop_orientations = self._rectify_crops(crops, loc_preds)
|
|
122
|
+
crop_orientations = [
|
|
123
|
+
{"value": orientation[0], "confidence": orientation[1]} for orientation in _crop_orientations
|
|
124
|
+
]
|
|
119
125
|
|
|
120
126
|
# Identify character sequences
|
|
121
127
|
word_preds = self.reco_predictor([crop for page_crops in crops for crop in page_crops], **kwargs)
|
|
128
|
+
if not crop_orientations:
|
|
129
|
+
crop_orientations = [{"value": 0, "confidence": None} for _ in word_preds]
|
|
122
130
|
|
|
123
|
-
boxes, text_preds = self._process_predictions(loc_preds, word_preds)
|
|
131
|
+
boxes, text_preds, crop_orientations = self._process_predictions(loc_preds, word_preds, crop_orientations)
|
|
124
132
|
|
|
125
133
|
if self.detect_language:
|
|
126
134
|
languages = [get_language(" ".join([item[0] for item in text_pred])) for text_pred in text_preds]
|
|
@@ -131,8 +139,10 @@ class OCRPredictor(NestedObject, _OCRPredictor):
|
|
|
131
139
|
out = self.doc_builder(
|
|
132
140
|
pages,
|
|
133
141
|
boxes,
|
|
142
|
+
objectness_scores,
|
|
134
143
|
text_preds,
|
|
135
144
|
origin_page_shapes, # type: ignore[arg-type]
|
|
145
|
+
crop_orientations,
|
|
136
146
|
orientations,
|
|
137
147
|
languages_dict,
|
|
138
148
|
)
|
|
@@ -79,7 +79,7 @@ class PreProcessor(nn.Module):
|
|
|
79
79
|
else:
|
|
80
80
|
x = x.to(dtype=torch.float32) # type: ignore[union-attr]
|
|
81
81
|
|
|
82
|
-
return x
|
|
82
|
+
return x
|
|
83
83
|
|
|
84
84
|
def __call__(self, x: Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]]) -> List[torch.Tensor]:
|
|
85
85
|
"""Prepare document data for model forwarding
|
|
@@ -103,7 +103,7 @@ class PreProcessor(nn.Module):
|
|
|
103
103
|
elif x.dtype not in (torch.uint8, torch.float16, torch.float32):
|
|
104
104
|
raise TypeError("unsupported data type for torch.Tensor")
|
|
105
105
|
# Resizing
|
|
106
|
-
if x.shape[-2] != self.resize.size[0] or x.shape[-1] != self.resize.size[1]:
|
|
106
|
+
if x.shape[-2] != self.resize.size[0] or x.shape[-1] != self.resize.size[1]:
|
|
107
107
|
x = F.resize(
|
|
108
108
|
x, self.resize.size, interpolation=self.resize.interpolation, antialias=self.resize.antialias
|
|
109
109
|
)
|
|
@@ -118,11 +118,11 @@ class PreProcessor(nn.Module):
|
|
|
118
118
|
# Sample transform (to tensor, resize)
|
|
119
119
|
samples = list(multithread_exec(self.sample_transforms, x))
|
|
120
120
|
# Batching
|
|
121
|
-
batches = self.batch_inputs(samples)
|
|
121
|
+
batches = self.batch_inputs(samples)
|
|
122
122
|
else:
|
|
123
123
|
raise TypeError(f"invalid input type: {type(x)}")
|
|
124
124
|
|
|
125
125
|
# Batch transforms (normalize)
|
|
126
126
|
batches = list(multithread_exec(self.normalize, batches))
|
|
127
127
|
|
|
128
|
-
return batches
|
|
128
|
+
return batches
|
|
@@ -41,6 +41,7 @@ class PreProcessor(NestedObject):
|
|
|
41
41
|
self.resize = Resize(output_size, **kwargs)
|
|
42
42
|
# Perform the division by 255 at the same time
|
|
43
43
|
self.normalize = Normalize(mean, std)
|
|
44
|
+
self._runs_on_cuda = tf.test.is_gpu_available()
|
|
44
45
|
|
|
45
46
|
def batch_inputs(self, samples: List[tf.Tensor]) -> List[tf.Tensor]:
|
|
46
47
|
"""Gather samples into batches for inference purposes
|
|
@@ -113,13 +114,13 @@ class PreProcessor(NestedObject):
|
|
|
113
114
|
|
|
114
115
|
elif isinstance(x, list) and all(isinstance(sample, (np.ndarray, tf.Tensor)) for sample in x):
|
|
115
116
|
# Sample transform (to tensor, resize)
|
|
116
|
-
samples = list(multithread_exec(self.sample_transforms, x))
|
|
117
|
+
samples = list(multithread_exec(self.sample_transforms, x, threads=1 if self._runs_on_cuda else None))
|
|
117
118
|
# Batching
|
|
118
119
|
batches = self.batch_inputs(samples)
|
|
119
120
|
else:
|
|
120
121
|
raise TypeError(f"invalid input type: {type(x)}")
|
|
121
122
|
|
|
122
123
|
# Batch transforms (normalize)
|
|
123
|
-
batches = list(multithread_exec(self.normalize, batches))
|
|
124
|
+
batches = list(multithread_exec(self.normalize, batches, threads=1 if self._runs_on_cuda else None))
|
|
124
125
|
|
|
125
126
|
return batches
|
|
@@ -107,7 +107,7 @@ class MASTER(_MASTER, nn.Module):
|
|
|
107
107
|
# NOTE: nn.TransformerDecoder takes the inverse from this implementation
|
|
108
108
|
# [True, True, True, ..., False, False, False] -> False is masked
|
|
109
109
|
# (N, 1, 1, max_length)
|
|
110
|
-
target_pad_mask = (target != self.vocab_size + 2).unsqueeze(1).unsqueeze(1)
|
|
110
|
+
target_pad_mask = (target != self.vocab_size + 2).unsqueeze(1).unsqueeze(1)
|
|
111
111
|
target_length = target.size(1)
|
|
112
112
|
# sub mask filled diagonal with True = see and False = masked (max_length, max_length)
|
|
113
113
|
# NOTE: onnxruntime tril/triu works only with float currently (onnxruntime 1.11.1 - opset 14)
|
|
@@ -142,7 +142,7 @@ class MASTER(_MASTER, nn.Module):
|
|
|
142
142
|
# Input length : number of timesteps
|
|
143
143
|
input_len = model_output.shape[1]
|
|
144
144
|
# Add one for additional <eos> token (sos disappear in shift!)
|
|
145
|
-
seq_len = seq_len + 1
|
|
145
|
+
seq_len = seq_len + 1
|
|
146
146
|
# Compute loss: don't forget to shift gt! Otherwise the model learns to output the gt[t-1]!
|
|
147
147
|
# The "masked" first gt char is <sos>. Delete last logit of the model output.
|
|
148
148
|
cce = F.cross_entropy(model_output[:, :-1, :].permute(0, 2, 1), gt[:, 1:], reduction="none")
|
|
@@ -212,7 +212,7 @@ class PARSeq(_PARSeq, nn.Module):
|
|
|
212
212
|
|
|
213
213
|
sos_idx = torch.zeros(len(final_perms), 1, device=seqlen.device)
|
|
214
214
|
eos_idx = torch.full((len(final_perms), 1), max_num_chars + 1, device=seqlen.device)
|
|
215
|
-
combined = torch.cat([sos_idx, final_perms + 1, eos_idx], dim=1).int()
|
|
215
|
+
combined = torch.cat([sos_idx, final_perms + 1, eos_idx], dim=1).int()
|
|
216
216
|
if len(combined) > 1:
|
|
217
217
|
combined[1, 1:] = max_num_chars + 1 - torch.arange(max_num_chars + 1, device=seqlen.device)
|
|
218
218
|
return combined
|
|
@@ -282,7 +282,8 @@ class PARSeq(_PARSeq, nn.Module):
|
|
|
282
282
|
ys[:, i + 1] = pos_prob.squeeze().argmax(-1)
|
|
283
283
|
|
|
284
284
|
# Stop decoding if all sequences have reached the EOS token
|
|
285
|
-
|
|
285
|
+
# NOTE: `break` isn't correctly translated to Onnx so we don't break here if we want to export
|
|
286
|
+
if not self.exportable and max_len is None and (ys == self.vocab_size).any(dim=-1).all():
|
|
286
287
|
break
|
|
287
288
|
|
|
288
289
|
logits = torch.cat(pos_logits, dim=1) # (N, max_length, vocab_size + 1)
|
|
@@ -297,7 +298,7 @@ class PARSeq(_PARSeq, nn.Module):
|
|
|
297
298
|
|
|
298
299
|
# Create padding mask for refined target input maskes all behind EOS token as False
|
|
299
300
|
# (N, 1, 1, max_length)
|
|
300
|
-
target_pad_mask = ~((ys == self.vocab_size).int().cumsum(-1) > 0).unsqueeze(1).unsqueeze(1)
|
|
301
|
+
target_pad_mask = ~((ys == self.vocab_size).int().cumsum(-1) > 0).unsqueeze(1).unsqueeze(1)
|
|
301
302
|
mask = (target_pad_mask.bool() & query_mask[:, : ys.shape[1]].bool()).int()
|
|
302
303
|
logits = self.head(self.decode(ys, features, mask, target_query=pos_queries))
|
|
303
304
|
|
|
@@ -288,10 +288,11 @@ class PARSeq(_PARSeq, Model):
|
|
|
288
288
|
)
|
|
289
289
|
|
|
290
290
|
# Stop decoding if all sequences have reached the EOS token
|
|
291
|
-
#
|
|
291
|
+
# NOTE: `break` isn't correctly translated to Onnx so we don't break here if we want to export
|
|
292
292
|
if (
|
|
293
|
-
|
|
294
|
-
and
|
|
293
|
+
not self.exportable
|
|
294
|
+
and max_len is None
|
|
295
|
+
and tf.reduce_any(tf.reduce_all(tf.equal(ys, tf.constant(self.vocab_size)), axis=-1))
|
|
295
296
|
):
|
|
296
297
|
break
|
|
297
298
|
|
|
@@ -125,25 +125,26 @@ class SARDecoder(nn.Module):
|
|
|
125
125
|
if t == 0:
|
|
126
126
|
# step to init the first states of the LSTMCell
|
|
127
127
|
hidden_state_init = cell_state_init = torch.zeros(
|
|
128
|
-
features.size(0), features.size(1), device=features.device
|
|
128
|
+
features.size(0), features.size(1), device=features.device, dtype=features.dtype
|
|
129
129
|
)
|
|
130
130
|
hidden_state, cell_state = hidden_state_init, cell_state_init
|
|
131
131
|
prev_symbol = holistic
|
|
132
132
|
elif t == 1:
|
|
133
133
|
# step to init a 'blank' sequence of length vocab_size + 1 filled with zeros
|
|
134
134
|
# (N, vocab_size + 1) --> (N, embedding_units)
|
|
135
|
-
prev_symbol = torch.zeros(
|
|
135
|
+
prev_symbol = torch.zeros(
|
|
136
|
+
features.size(0), self.vocab_size + 1, device=features.device, dtype=features.dtype
|
|
137
|
+
)
|
|
136
138
|
prev_symbol = self.embed(prev_symbol)
|
|
137
139
|
else:
|
|
138
|
-
if gt is not None:
|
|
140
|
+
if gt is not None and self.training:
|
|
139
141
|
# (N, embedding_units) -2 because of <bos> and <eos> (same)
|
|
140
142
|
prev_symbol = self.embed(gt_embedding[:, t - 2])
|
|
141
143
|
else:
|
|
142
144
|
# -1 to start at timestep where prev_symbol was initialized
|
|
143
145
|
index = logits_list[t - 1].argmax(-1)
|
|
144
146
|
# update prev_symbol with ones at the index of the previous logit vector
|
|
145
|
-
|
|
146
|
-
prev_symbol = prev_symbol.scatter_(1, index.unsqueeze(1), 1)
|
|
147
|
+
prev_symbol = self.embed(self.embed_tgt(index))
|
|
147
148
|
|
|
148
149
|
# (N, C), (N, C) take the last hidden state and cell state from current timestep
|
|
149
150
|
hidden_state_init, cell_state_init = self.lstm_cell(prev_symbol, (hidden_state_init, cell_state_init))
|
|
@@ -292,7 +293,7 @@ class SAR(nn.Module, RecognitionModel):
|
|
|
292
293
|
# Input length : number of timesteps
|
|
293
294
|
input_len = model_output.shape[1]
|
|
294
295
|
# Add one for additional <eos> token
|
|
295
|
-
seq_len = seq_len + 1
|
|
296
|
+
seq_len = seq_len + 1
|
|
296
297
|
# Compute loss
|
|
297
298
|
# (N, L, vocab_size + 1)
|
|
298
299
|
cce = F.cross_entropy(model_output.permute(0, 2, 1), gt, reduction="none")
|
|
@@ -177,23 +177,17 @@ class SARDecoder(layers.Layer, NestedObject):
|
|
|
177
177
|
elif t == 1:
|
|
178
178
|
# step to init a 'blank' sequence of length vocab_size + 1 filled with zeros
|
|
179
179
|
# (N, vocab_size + 1) --> (N, embedding_units)
|
|
180
|
-
prev_symbol = tf.zeros([features.shape[0], self.vocab_size + 1])
|
|
180
|
+
prev_symbol = tf.zeros([features.shape[0], self.vocab_size + 1], dtype=features.dtype)
|
|
181
181
|
prev_symbol = self.embed(prev_symbol, **kwargs)
|
|
182
182
|
else:
|
|
183
|
-
if gt is not None:
|
|
183
|
+
if gt is not None and kwargs.get("training", False):
|
|
184
184
|
# (N, embedding_units) -2 because of <bos> and <eos> (same)
|
|
185
185
|
prev_symbol = self.embed(gt_embedding[:, t - 2], **kwargs)
|
|
186
186
|
else:
|
|
187
187
|
# -1 to start at timestep where prev_symbol was initialized
|
|
188
188
|
index = tf.argmax(logits_list[t - 1], axis=-1)
|
|
189
189
|
# update prev_symbol with ones at the index of the previous logit vector
|
|
190
|
-
|
|
191
|
-
index = tf.ones_like(index)
|
|
192
|
-
prev_symbol = tf.scatter_nd(
|
|
193
|
-
tf.expand_dims(index, axis=1),
|
|
194
|
-
prev_symbol,
|
|
195
|
-
tf.constant([features.shape[0], features.shape[-1]], dtype=tf.int64),
|
|
196
|
-
)
|
|
190
|
+
prev_symbol = self.embed(self.embed_tgt(index, **kwargs), **kwargs)
|
|
197
191
|
|
|
198
192
|
# (N, C), (N, C) take the last hidden state and cell state from current timestep
|
|
199
193
|
_, states = self.lstm_cells(prev_symbol, states, **kwargs)
|
|
@@ -137,7 +137,7 @@ class ViTSTR(_ViTSTR, nn.Module):
|
|
|
137
137
|
# Input length : number of steps
|
|
138
138
|
input_len = model_output.shape[1]
|
|
139
139
|
# Add one for additional <eos> token (sos disappear in shift!)
|
|
140
|
-
seq_len = seq_len + 1
|
|
140
|
+
seq_len = seq_len + 1
|
|
141
141
|
# Compute loss: don't forget to shift gt! Otherwise the model learns to output the gt[t-1]!
|
|
142
142
|
# The "masked" first gt char is <sos>.
|
|
143
143
|
cce = F.cross_entropy(model_output.permute(0, 2, 1), gt[:, 1:], reduction="none")
|
doctr/models/recognition/zoo.py
CHANGED
|
@@ -45,7 +45,7 @@ def _predictor(arch: Any, pretrained: bool, **kwargs: Any) -> RecognitionPredict
|
|
|
45
45
|
|
|
46
46
|
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
47
47
|
kwargs["std"] = kwargs.get("std", _model.cfg["std"])
|
|
48
|
-
kwargs["batch_size"] = kwargs.get("batch_size",
|
|
48
|
+
kwargs["batch_size"] = kwargs.get("batch_size", 128)
|
|
49
49
|
input_shape = _model.cfg["input_shape"][:2] if is_tf_available() else _model.cfg["input_shape"][-2:]
|
|
50
50
|
predictor = RecognitionPredictor(PreProcessor(input_shape, preserve_aspect_ratio=True, **kwargs), _model)
|
|
51
51
|
|
doctr/models/zoo.py
CHANGED
|
@@ -61,7 +61,7 @@ def _predictor(
|
|
|
61
61
|
|
|
62
62
|
|
|
63
63
|
def ocr_predictor(
|
|
64
|
-
det_arch: Any = "
|
|
64
|
+
det_arch: Any = "fast_base",
|
|
65
65
|
reco_arch: Any = "crnn_vgg16_bn",
|
|
66
66
|
pretrained: bool = False,
|
|
67
67
|
pretrained_backbone: bool = True,
|
|
@@ -175,7 +175,7 @@ def _kie_predictor(
|
|
|
175
175
|
|
|
176
176
|
|
|
177
177
|
def kie_predictor(
|
|
178
|
-
det_arch: Any = "
|
|
178
|
+
det_arch: Any = "fast_base",
|
|
179
179
|
reco_arch: Any = "crnn_vgg16_bn",
|
|
180
180
|
pretrained: bool = False,
|
|
181
181
|
pretrained_backbone: bool = True,
|
doctr/py.typed
ADDED
|
File without changes
|
|
@@ -200,4 +200,4 @@ def create_shadow_mask(
|
|
|
200
200
|
mask: np.ndarray = np.zeros((*target_shape, 1), dtype=np.uint8)
|
|
201
201
|
mask = cv2.fillPoly(mask, [final_contour], (255,), lineType=cv2.LINE_AA)[..., 0]
|
|
202
202
|
|
|
203
|
-
return (mask / 255).astype(np.float32).clip(0, 1) * intensity_mask.astype(np.float32)
|
|
203
|
+
return (mask / 255).astype(np.float32).clip(0, 1) * intensity_mask.astype(np.float32)
|