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
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
# Copyright (C) 2021-2024, 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
|
+
# Credits: post-processing adapted from https://github.com/xuannianz/DifferentiableBinarization
|
|
7
|
+
|
|
8
|
+
from copy import deepcopy
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import tensorflow as tf
|
|
13
|
+
from tensorflow import keras
|
|
14
|
+
from tensorflow.keras import Sequential, layers
|
|
15
|
+
|
|
16
|
+
from doctr.file_utils import CLASS_NAME
|
|
17
|
+
from doctr.models.utils import IntermediateLayerGetter, _bf16_to_float32, load_pretrained_params
|
|
18
|
+
from doctr.utils.repr import NestedObject
|
|
19
|
+
|
|
20
|
+
from ...classification import textnet_base, textnet_small, textnet_tiny
|
|
21
|
+
from ...modules.layers import FASTConvLayer
|
|
22
|
+
from .base import _FAST, FASTPostProcessor
|
|
23
|
+
|
|
24
|
+
__all__ = ["FAST", "fast_tiny", "fast_small", "fast_base", "reparameterize"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
default_cfgs: Dict[str, Dict[str, Any]] = {
|
|
28
|
+
"fast_tiny": {
|
|
29
|
+
"input_shape": (1024, 1024, 3),
|
|
30
|
+
"mean": (0.798, 0.785, 0.772),
|
|
31
|
+
"std": (0.264, 0.2749, 0.287),
|
|
32
|
+
"url": "https://doctr-static.mindee.com/models?id=v0.8.1/fast_tiny-959daecb.zip&src=0",
|
|
33
|
+
},
|
|
34
|
+
"fast_small": {
|
|
35
|
+
"input_shape": (1024, 1024, 3),
|
|
36
|
+
"mean": (0.798, 0.785, 0.772),
|
|
37
|
+
"std": (0.264, 0.2749, 0.287),
|
|
38
|
+
"url": "https://doctr-static.mindee.com/models?id=v0.8.1/fast_small-f1617503.zip&src=0",
|
|
39
|
+
},
|
|
40
|
+
"fast_base": {
|
|
41
|
+
"input_shape": (1024, 1024, 3),
|
|
42
|
+
"mean": (0.798, 0.785, 0.772),
|
|
43
|
+
"std": (0.264, 0.2749, 0.287),
|
|
44
|
+
"url": "https://doctr-static.mindee.com/models?id=v0.8.1/fast_base-255e2ac3.zip&src=0",
|
|
45
|
+
},
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class FastNeck(layers.Layer, NestedObject):
|
|
50
|
+
"""Neck of the FAST architecture, composed of a series of 3x3 convolutions and upsampling layer.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
----
|
|
54
|
+
in_channels: number of input channels
|
|
55
|
+
out_channels: number of output channels
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
in_channels: int,
|
|
61
|
+
out_channels: int = 128,
|
|
62
|
+
) -> None:
|
|
63
|
+
super().__init__()
|
|
64
|
+
self.reduction = [FASTConvLayer(in_channels * scale, out_channels, kernel_size=3) for scale in [1, 2, 4, 8]]
|
|
65
|
+
|
|
66
|
+
def _upsample(self, x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:
|
|
67
|
+
return tf.image.resize(x, size=y.shape[1:3], method="bilinear")
|
|
68
|
+
|
|
69
|
+
def call(self, x: tf.Tensor, **kwargs: Any) -> tf.Tensor:
|
|
70
|
+
f1, f2, f3, f4 = x
|
|
71
|
+
f1, f2, f3, f4 = [reduction(f, **kwargs) for reduction, f in zip(self.reduction, (f1, f2, f3, f4))]
|
|
72
|
+
f2, f3, f4 = [self._upsample(f, f1) for f in (f2, f3, f4)]
|
|
73
|
+
f = tf.concat((f1, f2, f3, f4), axis=-1)
|
|
74
|
+
return f
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class FastHead(Sequential):
|
|
78
|
+
"""Head of the FAST architecture
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
----
|
|
82
|
+
in_channels: number of input channels
|
|
83
|
+
num_classes: number of output classes
|
|
84
|
+
out_channels: number of output channels
|
|
85
|
+
dropout: dropout probability
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
in_channels: int,
|
|
91
|
+
num_classes: int,
|
|
92
|
+
out_channels: int = 128,
|
|
93
|
+
dropout: float = 0.1,
|
|
94
|
+
) -> None:
|
|
95
|
+
_layers = [
|
|
96
|
+
FASTConvLayer(in_channels, out_channels, kernel_size=3),
|
|
97
|
+
layers.Dropout(dropout),
|
|
98
|
+
layers.Conv2D(num_classes, kernel_size=1, use_bias=False),
|
|
99
|
+
]
|
|
100
|
+
super().__init__(_layers)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class FAST(_FAST, keras.Model, NestedObject):
|
|
104
|
+
"""FAST as described in `"FAST: Faster Arbitrarily-Shaped Text Detector with Minimalist Kernel Representation"
|
|
105
|
+
<https://arxiv.org/pdf/2111.02394.pdf>`_.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
----
|
|
109
|
+
feature extractor: the backbone serving as feature extractor
|
|
110
|
+
bin_thresh: threshold for binarization
|
|
111
|
+
box_thresh: minimal objectness score to consider a box
|
|
112
|
+
dropout_prob: dropout probability
|
|
113
|
+
pooling_size: size of the pooling layer
|
|
114
|
+
assume_straight_pages: if True, fit straight bounding boxes only
|
|
115
|
+
exportable: onnx exportable returns only logits
|
|
116
|
+
cfg: the configuration dict of the model
|
|
117
|
+
class_names: list of class names
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
_children_names: List[str] = ["feat_extractor", "neck", "head", "postprocessor"]
|
|
121
|
+
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
feature_extractor: IntermediateLayerGetter,
|
|
125
|
+
bin_thresh: float = 0.1,
|
|
126
|
+
box_thresh: float = 0.1,
|
|
127
|
+
dropout_prob: float = 0.1,
|
|
128
|
+
pooling_size: int = 4, # different from paper performs better on close text-rich images
|
|
129
|
+
assume_straight_pages: bool = True,
|
|
130
|
+
exportable: bool = False,
|
|
131
|
+
cfg: Optional[Dict[str, Any]] = {},
|
|
132
|
+
class_names: List[str] = [CLASS_NAME],
|
|
133
|
+
) -> None:
|
|
134
|
+
super().__init__()
|
|
135
|
+
self.class_names = class_names
|
|
136
|
+
num_classes: int = len(self.class_names)
|
|
137
|
+
self.cfg = cfg
|
|
138
|
+
|
|
139
|
+
self.feat_extractor = feature_extractor
|
|
140
|
+
self.exportable = exportable
|
|
141
|
+
self.assume_straight_pages = assume_straight_pages
|
|
142
|
+
|
|
143
|
+
# Identify the number of channels for the neck & head initialization
|
|
144
|
+
feat_out_channels = [
|
|
145
|
+
layers.Input(shape=in_shape[1:]).shape[-1] for in_shape in self.feat_extractor.output_shape
|
|
146
|
+
]
|
|
147
|
+
# Initialize neck & head
|
|
148
|
+
self.neck = FastNeck(feat_out_channels[0], feat_out_channels[1])
|
|
149
|
+
self.head = FastHead(feat_out_channels[-1], num_classes, feat_out_channels[1], dropout_prob)
|
|
150
|
+
|
|
151
|
+
# NOTE: The post processing from the paper works not well for text-rich images
|
|
152
|
+
# so we use a modified version from DBNet
|
|
153
|
+
self.postprocessor = FASTPostProcessor(
|
|
154
|
+
assume_straight_pages=assume_straight_pages, bin_thresh=bin_thresh, box_thresh=box_thresh
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# Pooling layer as erosion reversal as described in the paper
|
|
158
|
+
self.pooling = layers.MaxPooling2D(pool_size=pooling_size // 2 + 1, strides=1, padding="same")
|
|
159
|
+
|
|
160
|
+
def compute_loss(
|
|
161
|
+
self,
|
|
162
|
+
out_map: tf.Tensor,
|
|
163
|
+
target: List[Dict[str, np.ndarray]],
|
|
164
|
+
eps: float = 1e-6,
|
|
165
|
+
) -> tf.Tensor:
|
|
166
|
+
"""Compute fast loss, 2 x Dice loss where the text kernel loss is scaled by 0.5.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
----
|
|
170
|
+
out_map: output feature map of the model of shape (N, num_classes, H, W)
|
|
171
|
+
target: list of dictionary where each dict has a `boxes` and a `flags` entry
|
|
172
|
+
eps: epsilon factor in dice loss
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
-------
|
|
176
|
+
A loss tensor
|
|
177
|
+
"""
|
|
178
|
+
targets = self.build_target(target, out_map.shape[1:], True)
|
|
179
|
+
|
|
180
|
+
seg_target = tf.convert_to_tensor(targets[0], dtype=out_map.dtype)
|
|
181
|
+
seg_mask = tf.convert_to_tensor(targets[1], dtype=out_map.dtype)
|
|
182
|
+
shrunken_kernel = tf.convert_to_tensor(targets[2], dtype=out_map.dtype)
|
|
183
|
+
|
|
184
|
+
def ohem(score: tf.Tensor, gt: tf.Tensor, mask: tf.Tensor) -> tf.Tensor:
|
|
185
|
+
pos_num = tf.reduce_sum(tf.cast(gt > 0.5, dtype=tf.int32)) - tf.reduce_sum(
|
|
186
|
+
tf.cast((gt > 0.5) & (mask <= 0.5), dtype=tf.int32)
|
|
187
|
+
)
|
|
188
|
+
neg_num = tf.reduce_sum(tf.cast(gt <= 0.5, dtype=tf.int32))
|
|
189
|
+
neg_num = tf.minimum(pos_num * 3, neg_num)
|
|
190
|
+
|
|
191
|
+
if neg_num == 0 or pos_num == 0:
|
|
192
|
+
return mask
|
|
193
|
+
|
|
194
|
+
neg_score_sorted, _ = tf.nn.top_k(-tf.boolean_mask(score, gt <= 0.5), k=neg_num)
|
|
195
|
+
threshold = -neg_score_sorted[-1]
|
|
196
|
+
|
|
197
|
+
selected_mask = tf.math.logical_and((score >= threshold) | (gt > 0.5), (mask > 0.5))
|
|
198
|
+
return tf.cast(selected_mask, dtype=tf.float32)
|
|
199
|
+
|
|
200
|
+
if len(self.class_names) > 1:
|
|
201
|
+
kernels = tf.nn.softmax(out_map, axis=-1)
|
|
202
|
+
prob_map = tf.nn.softmax(self.pooling(out_map), axis=-1)
|
|
203
|
+
else:
|
|
204
|
+
kernels = tf.sigmoid(out_map)
|
|
205
|
+
prob_map = tf.sigmoid(self.pooling(out_map))
|
|
206
|
+
|
|
207
|
+
# As described in the paper, we use the Dice loss for the text segmentation map and the Dice loss scaled by 0.5.
|
|
208
|
+
selected_masks = tf.stack(
|
|
209
|
+
[ohem(score, gt, mask) for score, gt, mask in zip(prob_map, seg_target, seg_mask)], axis=0
|
|
210
|
+
)
|
|
211
|
+
inter = tf.reduce_sum(selected_masks * prob_map * seg_target, axis=(0, 1, 2))
|
|
212
|
+
cardinality = tf.reduce_sum(selected_masks * (prob_map + seg_target), axis=(0, 1, 2))
|
|
213
|
+
text_loss = tf.reduce_mean((1 - 2 * inter / (cardinality + eps))) * 0.5
|
|
214
|
+
|
|
215
|
+
# As described in the paper, we use the Dice loss for the text kernel map.
|
|
216
|
+
selected_masks = seg_target * seg_mask
|
|
217
|
+
inter = tf.reduce_sum(selected_masks * kernels * shrunken_kernel, axis=(0, 1, 2))
|
|
218
|
+
cardinality = tf.reduce_sum(selected_masks * (kernels + shrunken_kernel), axis=(0, 1, 2))
|
|
219
|
+
kernel_loss = tf.reduce_mean((1 - 2 * inter / (cardinality + eps)))
|
|
220
|
+
|
|
221
|
+
return text_loss + kernel_loss
|
|
222
|
+
|
|
223
|
+
def call(
|
|
224
|
+
self,
|
|
225
|
+
x: tf.Tensor,
|
|
226
|
+
target: Optional[List[Dict[str, np.ndarray]]] = None,
|
|
227
|
+
return_model_output: bool = False,
|
|
228
|
+
return_preds: bool = False,
|
|
229
|
+
**kwargs: Any,
|
|
230
|
+
) -> Dict[str, Any]:
|
|
231
|
+
feat_maps = self.feat_extractor(x, **kwargs)
|
|
232
|
+
# Pass through the Neck & Head & Upsample
|
|
233
|
+
feat_concat = self.neck(feat_maps, **kwargs)
|
|
234
|
+
logits: tf.Tensor = self.head(feat_concat, **kwargs)
|
|
235
|
+
logits = layers.UpSampling2D(size=x.shape[-2] // logits.shape[-2], interpolation="bilinear")(logits, **kwargs)
|
|
236
|
+
|
|
237
|
+
out: Dict[str, tf.Tensor] = {}
|
|
238
|
+
if self.exportable:
|
|
239
|
+
out["logits"] = logits
|
|
240
|
+
return out
|
|
241
|
+
|
|
242
|
+
if return_model_output or target is None or return_preds:
|
|
243
|
+
prob_map = _bf16_to_float32(tf.math.sigmoid(self.pooling(logits, **kwargs)))
|
|
244
|
+
|
|
245
|
+
if return_model_output:
|
|
246
|
+
out["out_map"] = prob_map
|
|
247
|
+
|
|
248
|
+
if target is None or return_preds:
|
|
249
|
+
# Post-process boxes (keep only text predictions)
|
|
250
|
+
out["preds"] = [dict(zip(self.class_names, preds)) for preds in self.postprocessor(prob_map.numpy())]
|
|
251
|
+
|
|
252
|
+
if target is not None:
|
|
253
|
+
loss = self.compute_loss(logits, target)
|
|
254
|
+
out["loss"] = loss
|
|
255
|
+
|
|
256
|
+
return out
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def reparameterize(model: Union[FAST, layers.Layer]) -> FAST:
|
|
260
|
+
"""Fuse batchnorm and conv layers and reparameterize the model
|
|
261
|
+
|
|
262
|
+
args:
|
|
263
|
+
----
|
|
264
|
+
model: the FAST model to reparameterize
|
|
265
|
+
|
|
266
|
+
Returns:
|
|
267
|
+
-------
|
|
268
|
+
the reparameterized model
|
|
269
|
+
"""
|
|
270
|
+
last_conv = None
|
|
271
|
+
last_conv_idx = None
|
|
272
|
+
|
|
273
|
+
for idx, layer in enumerate(model.layers):
|
|
274
|
+
if hasattr(layer, "layers") or isinstance(
|
|
275
|
+
layer, (FASTConvLayer, FastNeck, FastHead, layers.BatchNormalization, layers.Conv2D)
|
|
276
|
+
):
|
|
277
|
+
if isinstance(layer, layers.BatchNormalization):
|
|
278
|
+
# fuse batchnorm only if it is followed by a conv layer
|
|
279
|
+
if last_conv is None:
|
|
280
|
+
continue
|
|
281
|
+
conv_w = last_conv.kernel
|
|
282
|
+
conv_b = last_conv.bias if last_conv.use_bias else tf.zeros_like(layer.moving_mean)
|
|
283
|
+
|
|
284
|
+
factor = layer.gamma / tf.sqrt(layer.moving_variance + layer.epsilon)
|
|
285
|
+
last_conv.kernel = conv_w * factor.numpy().reshape([1, 1, 1, -1])
|
|
286
|
+
if last_conv.use_bias:
|
|
287
|
+
last_conv.bias.assign((conv_b - layer.moving_mean) * factor + layer.beta)
|
|
288
|
+
model.layers[last_conv_idx] = last_conv # Replace the last conv layer with the fused version
|
|
289
|
+
model.layers[idx] = layers.Lambda(lambda x: x)
|
|
290
|
+
last_conv = None
|
|
291
|
+
elif isinstance(layer, layers.Conv2D):
|
|
292
|
+
last_conv = layer
|
|
293
|
+
last_conv_idx = idx
|
|
294
|
+
elif isinstance(layer, FASTConvLayer):
|
|
295
|
+
layer.reparameterize_layer()
|
|
296
|
+
elif isinstance(layer, FastNeck):
|
|
297
|
+
for reduction in layer.reduction:
|
|
298
|
+
reduction.reparameterize_layer()
|
|
299
|
+
elif isinstance(layer, FastHead):
|
|
300
|
+
reparameterize(layer)
|
|
301
|
+
else:
|
|
302
|
+
reparameterize(layer)
|
|
303
|
+
return model
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _fast(
|
|
307
|
+
arch: str,
|
|
308
|
+
pretrained: bool,
|
|
309
|
+
backbone_fn,
|
|
310
|
+
feat_layers: List[str],
|
|
311
|
+
pretrained_backbone: bool = True,
|
|
312
|
+
input_shape: Optional[Tuple[int, int, int]] = None,
|
|
313
|
+
**kwargs: Any,
|
|
314
|
+
) -> FAST:
|
|
315
|
+
pretrained_backbone = pretrained_backbone and not pretrained
|
|
316
|
+
|
|
317
|
+
# Patch the config
|
|
318
|
+
_cfg = deepcopy(default_cfgs[arch])
|
|
319
|
+
_cfg["input_shape"] = input_shape or _cfg["input_shape"]
|
|
320
|
+
if not kwargs.get("class_names", None):
|
|
321
|
+
kwargs["class_names"] = _cfg.get("class_names", [CLASS_NAME])
|
|
322
|
+
else:
|
|
323
|
+
kwargs["class_names"] = sorted(kwargs["class_names"])
|
|
324
|
+
|
|
325
|
+
# Feature extractor
|
|
326
|
+
feat_extractor = IntermediateLayerGetter(
|
|
327
|
+
backbone_fn(
|
|
328
|
+
input_shape=_cfg["input_shape"],
|
|
329
|
+
include_top=False,
|
|
330
|
+
pretrained=pretrained_backbone,
|
|
331
|
+
),
|
|
332
|
+
feat_layers,
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
# Build the model
|
|
336
|
+
model = FAST(feat_extractor, cfg=_cfg, **kwargs)
|
|
337
|
+
# Load pretrained parameters
|
|
338
|
+
if pretrained:
|
|
339
|
+
load_pretrained_params(model, _cfg["url"])
|
|
340
|
+
|
|
341
|
+
# Build the model for reparameterization to access the layers
|
|
342
|
+
_ = model(tf.random.uniform(shape=[1, *_cfg["input_shape"]], maxval=1, dtype=tf.float32), training=False)
|
|
343
|
+
|
|
344
|
+
return model
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def fast_tiny(pretrained: bool = False, **kwargs: Any) -> FAST:
|
|
348
|
+
"""FAST as described in `"FAST: Faster Arbitrarily-Shaped Text Detector with Minimalist Kernel Representation"
|
|
349
|
+
<https://arxiv.org/pdf/2111.02394.pdf>`_, using a tiny TextNet backbone.
|
|
350
|
+
|
|
351
|
+
>>> import tensorflow as tf
|
|
352
|
+
>>> from doctr.models import fast_tiny
|
|
353
|
+
>>> model = fast_tiny(pretrained=True)
|
|
354
|
+
>>> input_tensor = tf.random.uniform(shape=[1, 1024, 1024, 3], maxval=1, dtype=tf.float32)
|
|
355
|
+
>>> out = model(input_tensor)
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
----
|
|
359
|
+
pretrained (bool): If True, returns a model pre-trained on our text detection dataset
|
|
360
|
+
**kwargs: keyword arguments of the DBNet architecture
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
-------
|
|
364
|
+
text detection architecture
|
|
365
|
+
"""
|
|
366
|
+
return _fast(
|
|
367
|
+
"fast_tiny",
|
|
368
|
+
pretrained,
|
|
369
|
+
textnet_tiny,
|
|
370
|
+
["stage_0", "stage_1", "stage_2", "stage_3"],
|
|
371
|
+
**kwargs,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def fast_small(pretrained: bool = False, **kwargs: Any) -> FAST:
|
|
376
|
+
"""FAST as described in `"FAST: Faster Arbitrarily-Shaped Text Detector with Minimalist Kernel Representation"
|
|
377
|
+
<https://arxiv.org/pdf/2111.02394.pdf>`_, using a small TextNet backbone.
|
|
378
|
+
|
|
379
|
+
>>> import tensorflow as tf
|
|
380
|
+
>>> from doctr.models import fast_small
|
|
381
|
+
>>> model = fast_small(pretrained=True)
|
|
382
|
+
>>> input_tensor = tf.random.uniform(shape=[1, 1024, 1024, 3], maxval=1, dtype=tf.float32)
|
|
383
|
+
>>> out = model(input_tensor)
|
|
384
|
+
|
|
385
|
+
Args:
|
|
386
|
+
----
|
|
387
|
+
pretrained (bool): If True, returns a model pre-trained on our text detection dataset
|
|
388
|
+
**kwargs: keyword arguments of the DBNet architecture
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
-------
|
|
392
|
+
text detection architecture
|
|
393
|
+
"""
|
|
394
|
+
return _fast(
|
|
395
|
+
"fast_small",
|
|
396
|
+
pretrained,
|
|
397
|
+
textnet_small,
|
|
398
|
+
["stage_0", "stage_1", "stage_2", "stage_3"],
|
|
399
|
+
**kwargs,
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def fast_base(pretrained: bool = False, **kwargs: Any) -> FAST:
|
|
404
|
+
"""FAST as described in `"FAST: Faster Arbitrarily-Shaped Text Detector with Minimalist Kernel Representation"
|
|
405
|
+
<https://arxiv.org/pdf/2111.02394.pdf>`_, using a base TextNet backbone.
|
|
406
|
+
|
|
407
|
+
>>> import tensorflow as tf
|
|
408
|
+
>>> from doctr.models import fast_base
|
|
409
|
+
>>> model = fast_base(pretrained=True)
|
|
410
|
+
>>> input_tensor = tf.random.uniform(shape=[1, 1024, 1024, 3], maxval=1, dtype=tf.float32)
|
|
411
|
+
>>> out = model(input_tensor)
|
|
412
|
+
|
|
413
|
+
Args:
|
|
414
|
+
----
|
|
415
|
+
pretrained (bool): If True, returns a model pre-trained on our text detection dataset
|
|
416
|
+
**kwargs: keyword arguments of the DBNet architecture
|
|
417
|
+
|
|
418
|
+
Returns:
|
|
419
|
+
-------
|
|
420
|
+
text detection architecture
|
|
421
|
+
"""
|
|
422
|
+
return _fast(
|
|
423
|
+
"fast_base",
|
|
424
|
+
pretrained,
|
|
425
|
+
textnet_base,
|
|
426
|
+
["stage_0", "stage_1", "stage_2", "stage_3"],
|
|
427
|
+
**kwargs,
|
|
428
|
+
)
|
|
@@ -111,7 +111,7 @@ class LinkNetPostProcessor(DetectionPostProcessor):
|
|
|
111
111
|
contours, _ = cv2.findContours(bitmap.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
|
112
112
|
for contour in contours:
|
|
113
113
|
# Check whether smallest enclosing bounding box is not too small
|
|
114
|
-
if np.any(contour[:, 0].max(axis=0) - contour[:, 0].min(axis=0) < 2):
|
|
114
|
+
if np.any(contour[:, 0].max(axis=0) - contour[:, 0].min(axis=0) < 2): # type: ignore[index]
|
|
115
115
|
continue
|
|
116
116
|
# Compute objectness
|
|
117
117
|
if self.assume_straight_pages:
|
|
@@ -138,10 +138,11 @@ class LinkNetPostProcessor(DetectionPostProcessor):
|
|
|
138
138
|
# compute relative box to get rid of img shape
|
|
139
139
|
_box[:, 0] /= width
|
|
140
140
|
_box[:, 1] /= height
|
|
141
|
-
|
|
141
|
+
# Add score to box as (0, score)
|
|
142
|
+
boxes.append(np.vstack([_box, np.array([0.0, score])]))
|
|
142
143
|
|
|
143
144
|
if not self.assume_straight_pages:
|
|
144
|
-
return np.clip(np.asarray(boxes), 0, 1) if len(boxes) > 0 else np.zeros((0,
|
|
145
|
+
return np.clip(np.asarray(boxes), 0, 1) if len(boxes) > 0 else np.zeros((0, 5, 2), dtype=pred.dtype)
|
|
145
146
|
else:
|
|
146
147
|
return np.clip(np.asarray(boxes), 0, 1) if len(boxes) > 0 else np.zeros((0, 5), dtype=pred.dtype)
|
|
147
148
|
|
|
@@ -9,6 +9,7 @@ import numpy as np
|
|
|
9
9
|
import torch
|
|
10
10
|
from torch import nn
|
|
11
11
|
|
|
12
|
+
from doctr.models.detection._utils import _remove_padding
|
|
12
13
|
from doctr.models.preprocessor import PreProcessor
|
|
13
14
|
from doctr.models.utils import set_device_and_dtype
|
|
14
15
|
|
|
@@ -40,6 +41,11 @@ class DetectionPredictor(nn.Module):
|
|
|
40
41
|
return_maps: bool = False,
|
|
41
42
|
**kwargs: Any,
|
|
42
43
|
) -> Union[List[Dict[str, np.ndarray]], Tuple[List[Dict[str, np.ndarray]], List[np.ndarray]]]:
|
|
44
|
+
# Extract parameters from the preprocessor
|
|
45
|
+
preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
|
|
46
|
+
symmetric_pad = self.pre_processor.resize.symmetric_pad
|
|
47
|
+
assume_straight_pages = self.model.assume_straight_pages
|
|
48
|
+
|
|
43
49
|
# Dimension check
|
|
44
50
|
if any(page.ndim != 3 for page in pages):
|
|
45
51
|
raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
|
|
@@ -52,7 +58,15 @@ class DetectionPredictor(nn.Module):
|
|
|
52
58
|
predicted_batches = [
|
|
53
59
|
self.model(batch, return_preds=True, return_model_output=True, **kwargs) for batch in processed_batches
|
|
54
60
|
]
|
|
55
|
-
|
|
61
|
+
# Remove padding from loc predictions
|
|
62
|
+
preds = _remove_padding(
|
|
63
|
+
pages, # type: ignore[arg-type]
|
|
64
|
+
[pred for batch in predicted_batches for pred in batch["preds"]],
|
|
65
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
66
|
+
symmetric_pad=symmetric_pad,
|
|
67
|
+
assume_straight_pages=assume_straight_pages,
|
|
68
|
+
)
|
|
69
|
+
|
|
56
70
|
if return_maps:
|
|
57
71
|
seg_maps = [
|
|
58
72
|
pred.permute(1, 2, 0).detach().cpu().numpy() for batch in predicted_batches for pred in batch["out_map"]
|
|
@@ -9,6 +9,7 @@ import numpy as np
|
|
|
9
9
|
import tensorflow as tf
|
|
10
10
|
from tensorflow import keras
|
|
11
11
|
|
|
12
|
+
from doctr.models.detection._utils import _remove_padding
|
|
12
13
|
from doctr.models.preprocessor import PreProcessor
|
|
13
14
|
from doctr.utils.repr import NestedObject
|
|
14
15
|
|
|
@@ -40,6 +41,11 @@ class DetectionPredictor(NestedObject):
|
|
|
40
41
|
return_maps: bool = False,
|
|
41
42
|
**kwargs: Any,
|
|
42
43
|
) -> Union[List[Dict[str, np.ndarray]], Tuple[List[Dict[str, np.ndarray]], List[np.ndarray]]]:
|
|
44
|
+
# Extract parameters from the preprocessor
|
|
45
|
+
preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
|
|
46
|
+
symmetric_pad = self.pre_processor.resize.symmetric_pad
|
|
47
|
+
assume_straight_pages = self.model.assume_straight_pages
|
|
48
|
+
|
|
43
49
|
# Dimension check
|
|
44
50
|
if any(page.ndim != 3 for page in pages):
|
|
45
51
|
raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
|
|
@@ -50,7 +56,15 @@ class DetectionPredictor(NestedObject):
|
|
|
50
56
|
for batch in processed_batches
|
|
51
57
|
]
|
|
52
58
|
|
|
53
|
-
|
|
59
|
+
# Remove padding from loc predictions
|
|
60
|
+
preds = _remove_padding(
|
|
61
|
+
pages,
|
|
62
|
+
[pred for batch in predicted_batches for pred in batch["preds"]],
|
|
63
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
64
|
+
symmetric_pad=symmetric_pad,
|
|
65
|
+
assume_straight_pages=assume_straight_pages,
|
|
66
|
+
)
|
|
67
|
+
|
|
54
68
|
if return_maps:
|
|
55
69
|
seg_maps = [pred.numpy() for batch in predicted_batches for pred in batch["out_map"]]
|
|
56
70
|
return preds, seg_maps
|
doctr/models/detection/zoo.py
CHANGED
|
@@ -8,6 +8,7 @@ from typing import Any, List
|
|
|
8
8
|
from doctr.file_utils import is_tf_available, is_torch_available
|
|
9
9
|
|
|
10
10
|
from .. import detection
|
|
11
|
+
from ..detection.fast import reparameterize
|
|
11
12
|
from ..preprocessor import PreProcessor
|
|
12
13
|
from .predictor import DetectionPredictor
|
|
13
14
|
|
|
@@ -17,7 +18,16 @@ ARCHS: List[str]
|
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
if is_tf_available():
|
|
20
|
-
ARCHS = [
|
|
21
|
+
ARCHS = [
|
|
22
|
+
"db_resnet50",
|
|
23
|
+
"db_mobilenet_v3_large",
|
|
24
|
+
"linknet_resnet18",
|
|
25
|
+
"linknet_resnet34",
|
|
26
|
+
"linknet_resnet50",
|
|
27
|
+
"fast_tiny",
|
|
28
|
+
"fast_small",
|
|
29
|
+
"fast_base",
|
|
30
|
+
]
|
|
21
31
|
elif is_torch_available():
|
|
22
32
|
ARCHS = [
|
|
23
33
|
"db_resnet34",
|
|
@@ -26,6 +36,9 @@ elif is_torch_available():
|
|
|
26
36
|
"linknet_resnet18",
|
|
27
37
|
"linknet_resnet34",
|
|
28
38
|
"linknet_resnet50",
|
|
39
|
+
"fast_tiny",
|
|
40
|
+
"fast_small",
|
|
41
|
+
"fast_base",
|
|
29
42
|
]
|
|
30
43
|
|
|
31
44
|
|
|
@@ -39,18 +52,22 @@ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = True,
|
|
|
39
52
|
pretrained_backbone=kwargs.get("pretrained_backbone", True),
|
|
40
53
|
assume_straight_pages=assume_straight_pages,
|
|
41
54
|
)
|
|
55
|
+
# Reparameterize FAST models by default to lower inference latency and memory usage
|
|
56
|
+
if isinstance(_model, detection.FAST):
|
|
57
|
+
_model = reparameterize(_model)
|
|
42
58
|
else:
|
|
43
|
-
if not isinstance(arch, (detection.DBNet, detection.LinkNet)):
|
|
59
|
+
if not isinstance(arch, (detection.DBNet, detection.LinkNet, detection.FAST)):
|
|
44
60
|
raise ValueError(f"unknown architecture: {type(arch)}")
|
|
45
61
|
|
|
46
62
|
_model = arch
|
|
47
63
|
_model.assume_straight_pages = assume_straight_pages
|
|
64
|
+
_model.postprocessor.assume_straight_pages = assume_straight_pages
|
|
48
65
|
|
|
49
66
|
kwargs.pop("pretrained_backbone", None)
|
|
50
67
|
|
|
51
68
|
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
52
69
|
kwargs["std"] = kwargs.get("std", _model.cfg["std"])
|
|
53
|
-
kwargs["batch_size"] = kwargs.get("batch_size",
|
|
70
|
+
kwargs["batch_size"] = kwargs.get("batch_size", 2)
|
|
54
71
|
predictor = DetectionPredictor(
|
|
55
72
|
PreProcessor(_model.cfg["input_shape"][:-1] if is_tf_available() else _model.cfg["input_shape"][1:], **kwargs),
|
|
56
73
|
_model,
|
|
@@ -59,7 +76,7 @@ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = True,
|
|
|
59
76
|
|
|
60
77
|
|
|
61
78
|
def detection_predictor(
|
|
62
|
-
arch: Any = "
|
|
79
|
+
arch: Any = "fast_base",
|
|
63
80
|
pretrained: bool = False,
|
|
64
81
|
assume_straight_pages: bool = True,
|
|
65
82
|
**kwargs: Any,
|
doctr/models/factory/hub.py
CHANGED
|
@@ -36,7 +36,6 @@ AVAILABLE_ARCHS = {
|
|
|
36
36
|
"classification": models.classification.zoo.ARCHS,
|
|
37
37
|
"detection": models.detection.zoo.ARCHS,
|
|
38
38
|
"recognition": models.recognition.zoo.ARCHS,
|
|
39
|
-
"obj_detection": ["fasterrcnn_mobilenet_v3_large_fpn"] if is_torch_available() else None,
|
|
40
39
|
}
|
|
41
40
|
|
|
42
41
|
|
|
@@ -110,8 +109,8 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
|
|
|
110
109
|
|
|
111
110
|
if run_config is None and arch is None:
|
|
112
111
|
raise ValueError("run_config or arch must be specified")
|
|
113
|
-
if task not in ["classification", "detection", "recognition"
|
|
114
|
-
raise ValueError("task must be one of classification, detection, recognition
|
|
112
|
+
if task not in ["classification", "detection", "recognition"]:
|
|
113
|
+
raise ValueError("task must be one of classification, detection, recognition")
|
|
115
114
|
|
|
116
115
|
# default readme
|
|
117
116
|
readme = textwrap.dedent(
|
|
@@ -165,7 +164,7 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
|
|
|
165
164
|
\n{json.dumps(vars(run_config), indent=2, ensure_ascii=False)}"""
|
|
166
165
|
)
|
|
167
166
|
|
|
168
|
-
if arch not in AVAILABLE_ARCHS[task]:
|
|
167
|
+
if arch not in AVAILABLE_ARCHS[task]:
|
|
169
168
|
raise ValueError(
|
|
170
169
|
f"Architecture: {arch} for task: {task} not found.\
|
|
171
170
|
\nAvailable architectures: {AVAILABLE_ARCHS}"
|
|
@@ -217,14 +216,6 @@ def from_hub(repo_id: str, **kwargs: Any):
|
|
|
217
216
|
model = models.detection.__dict__[arch](pretrained=False)
|
|
218
217
|
elif task == "recognition":
|
|
219
218
|
model = models.recognition.__dict__[arch](pretrained=False, input_shape=cfg["input_shape"], vocab=cfg["vocab"])
|
|
220
|
-
elif task == "obj_detection" and is_torch_available():
|
|
221
|
-
model = models.obj_detection.__dict__[arch](
|
|
222
|
-
pretrained=False,
|
|
223
|
-
image_mean=cfg["mean"],
|
|
224
|
-
image_std=cfg["std"],
|
|
225
|
-
max_size=cfg["input_shape"][-1],
|
|
226
|
-
num_classes=len(cfg["classes"]),
|
|
227
|
-
)
|
|
228
219
|
|
|
229
220
|
# update model cfg
|
|
230
221
|
model.cfg = cfg
|
|
@@ -7,7 +7,7 @@ from typing import Any, Optional
|
|
|
7
7
|
|
|
8
8
|
from doctr.models.builder import KIEDocumentBuilder
|
|
9
9
|
|
|
10
|
-
from ..classification.predictor import
|
|
10
|
+
from ..classification.predictor import OrientationPredictor
|
|
11
11
|
from ..predictor.base import _OCRPredictor
|
|
12
12
|
|
|
13
13
|
__all__ = ["_KIEPredictor"]
|
|
@@ -25,10 +25,13 @@ class _KIEPredictor(_OCRPredictor):
|
|
|
25
25
|
accordingly. Doing so will improve performances for documents with page-uniform rotations.
|
|
26
26
|
preserve_aspect_ratio: if True, resize preserving the aspect ratio (with padding)
|
|
27
27
|
symmetric_pad: if True and preserve_aspect_ratio is True, pas the image symmetrically.
|
|
28
|
+
detect_orientation: if True, the estimated general page orientation will be added to the predictions for each
|
|
29
|
+
page. Doing so will slightly deteriorate the overall latency.
|
|
28
30
|
kwargs: keyword args of `DocumentBuilder`
|
|
29
31
|
"""
|
|
30
32
|
|
|
31
|
-
crop_orientation_predictor: Optional[
|
|
33
|
+
crop_orientation_predictor: Optional[OrientationPredictor]
|
|
34
|
+
page_orientation_predictor: Optional[OrientationPredictor]
|
|
32
35
|
|
|
33
36
|
def __init__(
|
|
34
37
|
self,
|
|
@@ -36,8 +39,11 @@ class _KIEPredictor(_OCRPredictor):
|
|
|
36
39
|
straighten_pages: bool = False,
|
|
37
40
|
preserve_aspect_ratio: bool = True,
|
|
38
41
|
symmetric_pad: bool = True,
|
|
42
|
+
detect_orientation: bool = False,
|
|
39
43
|
**kwargs: Any,
|
|
40
44
|
) -> None:
|
|
41
|
-
super().__init__(
|
|
45
|
+
super().__init__(
|
|
46
|
+
assume_straight_pages, straighten_pages, preserve_aspect_ratio, symmetric_pad, detect_orientation, **kwargs
|
|
47
|
+
)
|
|
42
48
|
|
|
43
49
|
self.doc_builder: KIEDocumentBuilder = KIEDocumentBuilder(**kwargs)
|