python-doctr 1.0.0__py3-none-any.whl → 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +506 -0
- doctr/contrib/artefacts.py +1 -1
- doctr/contrib/base.py +1 -1
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +5 -3
- doctr/datasets/cord.py +3 -2
- doctr/datasets/datasets/base.py +13 -25
- doctr/datasets/datasets/pytorch.py +15 -5
- doctr/datasets/detection.py +3 -2
- doctr/datasets/doc_artefacts.py +3 -2
- doctr/datasets/funsd.py +3 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +4 -3
- doctr/datasets/ic13.py +5 -3
- doctr/datasets/iiit5k.py +3 -2
- doctr/datasets/iiithws.py +5 -3
- doctr/datasets/imgur5k.py +5 -3
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +5 -3
- doctr/datasets/ocr.py +3 -2
- doctr/datasets/orientation.py +3 -2
- doctr/datasets/recognition.py +3 -2
- doctr/datasets/sroie.py +3 -2
- doctr/datasets/svhn.py +3 -2
- doctr/datasets/svt.py +4 -3
- doctr/datasets/synthtext.py +3 -2
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +15 -6
- doctr/datasets/vocabs.py +3 -1
- doctr/datasets/wildreceipt.py +5 -3
- doctr/file_utils.py +4 -2
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +253 -261
- doctr/io/exporters.py +1275 -0
- doctr/io/html.py +1 -1
- doctr/io/image/base.py +4 -3
- doctr/io/image/pytorch.py +6 -4
- doctr/io/pdf.py +1 -1
- doctr/io/reader.py +1 -1
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +111 -25
- doctr/models/builder.py +533 -62
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +2 -2
- doctr/models/classification/mobilenet/pytorch.py +7 -7
- doctr/models/classification/predictor/pytorch.py +7 -3
- doctr/models/classification/resnet/pytorch.py +6 -6
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +7 -6
- doctr/models/classification/vgg/pytorch.py +4 -3
- doctr/models/classification/vip/layers/pytorch.py +5 -5
- doctr/models/classification/vip/pytorch.py +5 -5
- doctr/models/classification/vit/pytorch.py +4 -4
- 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 +4 -1
- doctr/models/core.py +1 -1
- doctr/models/detection/_utils/base.py +24 -8
- doctr/models/detection/_utils/pytorch.py +1 -1
- doctr/models/detection/core.py +34 -19
- doctr/models/detection/differentiable_binarization/base.py +7 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
- doctr/models/detection/fast/base.py +6 -2
- doctr/models/detection/fast/pytorch.py +4 -4
- doctr/models/detection/linknet/base.py +6 -2
- doctr/models/detection/linknet/pytorch.py +4 -4
- doctr/models/detection/predictor/pytorch.py +4 -3
- doctr/models/detection/zoo.py +3 -3
- doctr/models/factory/hub.py +72 -52
- doctr/models/kie_predictor/base.py +17 -2
- doctr/models/kie_predictor/pytorch.py +42 -11
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +140 -4
- doctr/models/modules/transformer/pytorch.py +1 -1
- doctr/models/modules/vision_transformer/pytorch.py +1 -1
- doctr/models/predictor/base.py +138 -16
- doctr/models/predictor/pytorch.py +151 -9
- doctr/models/preprocessor/pytorch.py +78 -23
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/core.py +1 -1
- doctr/models/recognition/crnn/pytorch.py +6 -8
- doctr/models/recognition/master/base.py +1 -1
- doctr/models/recognition/master/pytorch.py +7 -8
- doctr/models/recognition/parseq/base.py +1 -1
- doctr/models/recognition/parseq/pytorch.py +5 -5
- doctr/models/recognition/predictor/_utils.py +1 -1
- doctr/models/recognition/predictor/pytorch.py +2 -2
- doctr/models/recognition/sar/pytorch.py +2 -2
- doctr/models/recognition/utils.py +9 -11
- doctr/models/recognition/viptr/pytorch.py +4 -6
- doctr/models/recognition/vitstr/base.py +1 -1
- doctr/models/recognition/vitstr/pytorch.py +6 -6
- doctr/models/recognition/zoo.py +6 -7
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +316 -16
- doctr/models/zoo.py +91 -3
- doctr/transforms/functional/base.py +3 -2
- doctr/transforms/functional/pytorch.py +1 -1
- doctr/transforms/modules/base.py +248 -83
- doctr/transforms/modules/pytorch.py +213 -74
- doctr/utils/common_types.py +22 -2
- doctr/utils/data.py +5 -4
- doctr/utils/fonts.py +56 -17
- doctr/utils/geometry.py +136 -19
- doctr/utils/metrics.py +351 -19
- doctr/utils/multithreading.py +6 -3
- doctr/utils/reconstitution.py +697 -133
- doctr/utils/repr.py +1 -1
- doctr/utils/visualization.py +63 -4
- doctr/version.py +1 -1
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.0.dist-info/RECORD +0 -149
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|
|
@@ -0,0 +1,82 @@
|
|
|
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
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
from torch import nn
|
|
11
|
+
|
|
12
|
+
from doctr.models.detection._utils import _remove_padding
|
|
13
|
+
from doctr.models.preprocessor import PreProcessor
|
|
14
|
+
from doctr.models.utils import set_device_and_dtype
|
|
15
|
+
|
|
16
|
+
__all__ = ["LayoutPredictor"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class LayoutPredictor(nn.Module):
|
|
20
|
+
"""Implements an object able to localize layout elements in a document
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
pre_processor: transform inputs for easier batched model inference
|
|
24
|
+
model: core layout architecture
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
pre_processor: PreProcessor,
|
|
30
|
+
model: nn.Module,
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__()
|
|
33
|
+
self.pre_processor = pre_processor
|
|
34
|
+
self.model = model.eval()
|
|
35
|
+
|
|
36
|
+
@torch.inference_mode()
|
|
37
|
+
def forward(
|
|
38
|
+
self,
|
|
39
|
+
pages: list[np.ndarray],
|
|
40
|
+
**kwargs: Any,
|
|
41
|
+
) -> list[dict[str, np.ndarray]]:
|
|
42
|
+
# Extract parameters from the preprocessor
|
|
43
|
+
preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
|
|
44
|
+
symmetric_pad = self.pre_processor.resize.symmetric_pad
|
|
45
|
+
assume_straight_pages = self.model.assume_straight_pages
|
|
46
|
+
# This flag is needed to return the padding mask from the preprocessor
|
|
47
|
+
self.pre_processor.resize.return_padding_mask = True
|
|
48
|
+
|
|
49
|
+
# Dimension check
|
|
50
|
+
if any(page.ndim != 3 for page in pages):
|
|
51
|
+
raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
|
|
52
|
+
|
|
53
|
+
processed_batches = self.pre_processor(pages)
|
|
54
|
+
_params = next(self.model.parameters())
|
|
55
|
+
self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
|
|
56
|
+
self.model, processed_batches, _params.device, _params.dtype
|
|
57
|
+
)
|
|
58
|
+
predicted_batches = [
|
|
59
|
+
self.model(batch[0], batch[1], return_preds=True, return_model_output=True, **kwargs)
|
|
60
|
+
for batch in processed_batches
|
|
61
|
+
]
|
|
62
|
+
# remap idx to class names
|
|
63
|
+
class_names = [
|
|
64
|
+
[self.model.class_names[int(i)] for i in pred[0]] # type: ignore[index]
|
|
65
|
+
for batch in predicted_batches
|
|
66
|
+
for pred in batch["preds"]
|
|
67
|
+
]
|
|
68
|
+
boxes = [pred[1] for batch in predicted_batches for pred in batch["preds"]]
|
|
69
|
+
scores = [pred[2] for batch in predicted_batches for pred in batch["preds"]]
|
|
70
|
+
|
|
71
|
+
# Remove padding from loc predictions
|
|
72
|
+
preds = _remove_padding(
|
|
73
|
+
pages,
|
|
74
|
+
[{"pred": box} for box in boxes],
|
|
75
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
76
|
+
symmetric_pad=symmetric_pad,
|
|
77
|
+
assume_straight_pages=assume_straight_pages, # type: ignore[arg-type]
|
|
78
|
+
)
|
|
79
|
+
return [
|
|
80
|
+
{"class_names": class_name, "boxes": pred["pred"], "scores": score} # type: ignore[dict-item]
|
|
81
|
+
for class_name, pred, score in zip(class_names, preds, scores)
|
|
82
|
+
]
|
|
@@ -0,0 +1,90 @@
|
|
|
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
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from doctr.models.utils import _CompiledModule
|
|
9
|
+
|
|
10
|
+
from .. import layout
|
|
11
|
+
from ..preprocessor import PreProcessor
|
|
12
|
+
from .predictor import LayoutPredictor
|
|
13
|
+
|
|
14
|
+
__all__ = ["layout_predictor"]
|
|
15
|
+
|
|
16
|
+
ARCHS: list[str]
|
|
17
|
+
|
|
18
|
+
ARCHS = ["lw_detr_s", "lw_detr_m"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = True, **kwargs: Any) -> LayoutPredictor:
|
|
22
|
+
if isinstance(arch, str):
|
|
23
|
+
if arch not in ARCHS:
|
|
24
|
+
raise ValueError(f"unknown architecture '{arch}'")
|
|
25
|
+
|
|
26
|
+
_model = layout.__dict__[arch](
|
|
27
|
+
pretrained=pretrained,
|
|
28
|
+
assume_straight_pages=assume_straight_pages,
|
|
29
|
+
)
|
|
30
|
+
else:
|
|
31
|
+
# Adding the type for torch compiled models to the allowed architectures
|
|
32
|
+
allowed_archs = [layout.LWDETR, _CompiledModule]
|
|
33
|
+
|
|
34
|
+
if not isinstance(arch, tuple(allowed_archs)):
|
|
35
|
+
raise ValueError(f"unknown architecture: {type(arch)}")
|
|
36
|
+
_model = arch
|
|
37
|
+
_model.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
|
|
38
|
+
_model.postprocessor.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
|
|
39
|
+
|
|
40
|
+
kwargs.pop("pretrained_backbone", None)
|
|
41
|
+
|
|
42
|
+
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
43
|
+
kwargs["std"] = kwargs.get("std", _model.cfg["std"])
|
|
44
|
+
kwargs["batch_size"] = kwargs.get("batch_size", 2)
|
|
45
|
+
predictor = LayoutPredictor(
|
|
46
|
+
PreProcessor(_model.cfg["input_shape"][1:], **kwargs),
|
|
47
|
+
_model,
|
|
48
|
+
)
|
|
49
|
+
return predictor
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def layout_predictor(
|
|
53
|
+
arch: Any = "lw_detr_s",
|
|
54
|
+
pretrained: bool = False,
|
|
55
|
+
assume_straight_pages: bool = True,
|
|
56
|
+
preserve_aspect_ratio: bool = True,
|
|
57
|
+
symmetric_pad: bool = True,
|
|
58
|
+
batch_size: int = 2,
|
|
59
|
+
**kwargs: Any,
|
|
60
|
+
) -> LayoutPredictor:
|
|
61
|
+
"""Layout prediction architecture.
|
|
62
|
+
|
|
63
|
+
>>> import numpy as np
|
|
64
|
+
>>> from doctr.models import layout_predictor
|
|
65
|
+
>>> model = layout_predictor(arch='lw_detr_s', pretrained=True)
|
|
66
|
+
>>> input_page = (255 * np.random.rand(600, 800, 3)).astype(np.uint8)
|
|
67
|
+
>>> out = model([input_page])
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
arch: name of the architecture or model itself to use (e.g. 'lw_detr_s')
|
|
71
|
+
pretrained: If True, returns a model pre-trained on our layout prediction dataset
|
|
72
|
+
assume_straight_pages: If True, fit straight boxes to the page
|
|
73
|
+
preserve_aspect_ratio: If True, pad the input document image to preserve the aspect ratio before
|
|
74
|
+
running the detection model on it
|
|
75
|
+
symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
|
|
76
|
+
batch_size: number of samples the model processes in parallel
|
|
77
|
+
**kwargs: optional keyword arguments passed to the architecture
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
Layout predictor
|
|
81
|
+
"""
|
|
82
|
+
return _predictor(
|
|
83
|
+
arch=arch,
|
|
84
|
+
pretrained=pretrained,
|
|
85
|
+
assume_straight_pages=assume_straight_pages,
|
|
86
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
87
|
+
symmetric_pad=symmetric_pad,
|
|
88
|
+
batch_size=batch_size,
|
|
89
|
+
**kwargs,
|
|
90
|
+
)
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
2
|
|
|
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
|
-
|
|
7
6
|
import numpy as np
|
|
8
7
|
import torch
|
|
9
8
|
import torch.nn as nn
|
|
9
|
+
import torch.nn.functional as F
|
|
10
10
|
|
|
11
|
-
__all__ = ["FASTConvLayer", "DropPath", "AdaptiveAvgPool2d"]
|
|
11
|
+
__all__ = ["FASTConvLayer", "DropPath", "AdaptiveAvgPool2d", "ChannelLayerNorm", "DCNv2"]
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
class DropPath(nn.Module):
|
|
@@ -36,7 +36,6 @@ class DropPath(nn.Module):
|
|
|
36
36
|
class AdaptiveAvgPool2d(nn.Module):
|
|
37
37
|
"""
|
|
38
38
|
Custom AdaptiveAvgPool2d implementation which is ONNX and `torch.compile` compatible.
|
|
39
|
-
|
|
40
39
|
"""
|
|
41
40
|
|
|
42
41
|
def __init__(self, output_size):
|
|
@@ -59,6 +58,143 @@ class AdaptiveAvgPool2d(nn.Module):
|
|
|
59
58
|
return out
|
|
60
59
|
|
|
61
60
|
|
|
61
|
+
class ChannelLayerNorm(nn.Module):
|
|
62
|
+
"""
|
|
63
|
+
A LayerNorm variant, popularized by Transformers, that performs point-wise mean and
|
|
64
|
+
variance normalization over the channel dimension for inputs that have shape
|
|
65
|
+
(batch_size, channels, height, width).
|
|
66
|
+
https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(self, normalized_shape: int, eps: float = 1e-6):
|
|
70
|
+
super().__init__()
|
|
71
|
+
self.weight = nn.Parameter(torch.ones(normalized_shape))
|
|
72
|
+
self.bias = nn.Parameter(torch.zeros(normalized_shape))
|
|
73
|
+
self.eps = eps
|
|
74
|
+
self.normalized_shape = (normalized_shape,)
|
|
75
|
+
|
|
76
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
77
|
+
u = x.mean(1, keepdim=True)
|
|
78
|
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
|
79
|
+
x = (x - u) / torch.sqrt(s + self.eps)
|
|
80
|
+
x = self.weight[:, None, None] * x + self.bias[:, None, None]
|
|
81
|
+
return x
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _deform_conv2d(
|
|
85
|
+
x: torch.Tensor,
|
|
86
|
+
offset: torch.Tensor,
|
|
87
|
+
weight: torch.Tensor,
|
|
88
|
+
bias: torch.Tensor,
|
|
89
|
+
stride: tuple[int, int],
|
|
90
|
+
padding: tuple[int, int],
|
|
91
|
+
dilation: tuple[int, int],
|
|
92
|
+
mask: torch.Tensor,
|
|
93
|
+
) -> torch.Tensor:
|
|
94
|
+
"""Modulated deformable convolution (DCNv2).
|
|
95
|
+
|
|
96
|
+
Numerically equivalent to `torchvision.ops.deform_conv2d` (same offset/mask channel layout and bilinear
|
|
97
|
+
convention) but built only from `grid_sample` + `conv2d`, so the model is ONNX-exportable (the
|
|
98
|
+
`torchvision::deform_conv2d` operator has no ONNX symbolic). `offset` is laid out as torchvision
|
|
99
|
+
expects: for kernel position `k = kh * Kw + kw`, `offset[:, 2 * k]` is the vertical offset and
|
|
100
|
+
`offset[:, 2 * k + 1]` the horizontal one; `mask[:, k]` is the modulation.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
x: input feature map, shape (N, C, H, W)
|
|
104
|
+
offset: sampling offsets, shape (N, 2 * Kh * Kw, Ho, Wo)
|
|
105
|
+
weight: convolution weight, shape (Cout, C, Kh, Kw)
|
|
106
|
+
bias: convolution bias, shape (Cout,)
|
|
107
|
+
stride: convolution stride (sh, sw)
|
|
108
|
+
padding: convolution padding (ph, pw)
|
|
109
|
+
dilation: convolution dilation (dh, dw)
|
|
110
|
+
mask: modulation mask, shape (N, Kh * Kw, Ho, Wo)
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
the output feature map, shape (N, Cout, Ho, Wo)
|
|
114
|
+
"""
|
|
115
|
+
_, _, h, w = x.shape
|
|
116
|
+
cout, _, kh, kw = weight.shape
|
|
117
|
+
sh, sw = stride
|
|
118
|
+
ph, pw = padding
|
|
119
|
+
dh, dw = dilation
|
|
120
|
+
ho, wo = offset.shape[-2], offset.shape[-1]
|
|
121
|
+
|
|
122
|
+
# Base sampling location of each output position in the input plane (before kernel/dilation and offset)
|
|
123
|
+
base_y = (torch.arange(ho, device=x.device, dtype=x.dtype) * sh - ph).view(1, ho, 1)
|
|
124
|
+
base_x = (torch.arange(wo, device=x.device, dtype=x.dtype) * sw - pw).view(1, 1, wo)
|
|
125
|
+
norm_y, norm_x = max(h - 1, 1), max(w - 1, 1)
|
|
126
|
+
|
|
127
|
+
out = x.new_zeros((x.shape[0], cout, ho, wo))
|
|
128
|
+
for kh_i in range(kh):
|
|
129
|
+
for kw_i in range(kw):
|
|
130
|
+
k = kh_i * kw + kw_i
|
|
131
|
+
sample_y = base_y + kh_i * dh + offset[:, 2 * k, :, :]
|
|
132
|
+
sample_x = base_x + kw_i * dw + offset[:, 2 * k + 1, :, :]
|
|
133
|
+
# Normalize to [-1, 1] for grid_sample with align_corners=True (zero padding out of bounds)
|
|
134
|
+
grid = torch.stack((2.0 * sample_x / norm_x - 1.0, 2.0 * sample_y / norm_y - 1.0), dim=-1)
|
|
135
|
+
sampled = F.grid_sample(x, grid, mode="bilinear", padding_mode="zeros", align_corners=True)
|
|
136
|
+
sampled = sampled * mask[:, k : k + 1, :, :]
|
|
137
|
+
out = out + F.conv2d(sampled, weight[:, :, kh_i, kw_i].unsqueeze(-1).unsqueeze(-1))
|
|
138
|
+
return out + bias.view(1, -1, 1, 1)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class DCNv2(nn.Module):
|
|
142
|
+
"""Modulated deformable convolution (v2).
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
in_channels: number of channels in the input feature map
|
|
146
|
+
out_channels: number of channels produced by the convolution
|
|
147
|
+
kernel_size: size of the convolving kernel
|
|
148
|
+
stride: stride of the convolution
|
|
149
|
+
padding: zero-padding added to both sides of the input
|
|
150
|
+
dilation: spacing between kernel elements
|
|
151
|
+
deformable_groups: number of deformable group partitions
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(
|
|
155
|
+
self,
|
|
156
|
+
in_channels: int,
|
|
157
|
+
out_channels: int,
|
|
158
|
+
kernel_size: int | tuple[int, int],
|
|
159
|
+
stride: int,
|
|
160
|
+
padding: int,
|
|
161
|
+
dilation: int = 1,
|
|
162
|
+
deformable_groups: int = 1,
|
|
163
|
+
):
|
|
164
|
+
super().__init__()
|
|
165
|
+
self.stride = (stride, stride)
|
|
166
|
+
self.padding = (padding, padding)
|
|
167
|
+
self.dilation = (dilation, dilation)
|
|
168
|
+
if isinstance(kernel_size, int):
|
|
169
|
+
kernel_size = (kernel_size, kernel_size)
|
|
170
|
+
self.weight = nn.Parameter(torch.empty(out_channels, in_channels, *kernel_size))
|
|
171
|
+
self.bias = nn.Parameter(torch.empty(out_channels))
|
|
172
|
+
channels_ = deformable_groups * 3 * kernel_size[0] * kernel_size[1]
|
|
173
|
+
self.conv_offset_mask = nn.Conv2d(in_channels, channels_, kernel_size, stride, padding, bias=True)
|
|
174
|
+
self.reset_parameters()
|
|
175
|
+
|
|
176
|
+
def reset_parameters(self) -> None:
|
|
177
|
+
# Standard DCN initialization: the regular conv weight is initialized like a vanilla conv, while
|
|
178
|
+
# the offset/mask predictor is zero-initialized so the layer starts as a plain convolution
|
|
179
|
+
# (offsets = 0, modulation = 0.5). Without this, weight/bias keep their uninitialized
|
|
180
|
+
# torch.empty values, which makes the deformable conv explode and the loss diverge to NaN.
|
|
181
|
+
n = self.weight.shape[1]
|
|
182
|
+
for k in self.weight.shape[2:]:
|
|
183
|
+
n *= k
|
|
184
|
+
stdv = 1.0 / (n**0.5)
|
|
185
|
+
nn.init.uniform_(self.weight, -stdv, stdv)
|
|
186
|
+
nn.init.zeros_(self.bias)
|
|
187
|
+
nn.init.zeros_(self.conv_offset_mask.weight)
|
|
188
|
+
nn.init.zeros_(self.conv_offset_mask.bias) # type: ignore[arg-type]
|
|
189
|
+
|
|
190
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
191
|
+
out = self.conv_offset_mask(x)
|
|
192
|
+
o1, o2, mask = torch.chunk(out, 3, dim=1)
|
|
193
|
+
offset = torch.cat((o1, o2), dim=1)
|
|
194
|
+
mask = torch.sigmoid(mask)
|
|
195
|
+
return _deform_conv2d(x, offset, self.weight, self.bias, self.stride, self.padding, self.dilation, mask)
|
|
196
|
+
|
|
197
|
+
|
|
62
198
|
class FASTConvLayer(nn.Module):
|
|
63
199
|
"""Convolutional layer used in the TextNet and FAST architectures"""
|
|
64
200
|
|
doctr/models/predictor/base.py
CHANGED
|
@@ -1,17 +1,24 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
2
|
|
|
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 collections.abc import Callable
|
|
6
|
+
from collections.abc import Callable, Collection
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
9
|
import numpy as np
|
|
10
10
|
|
|
11
|
+
from doctr.io.elements import Document, KIEPage
|
|
11
12
|
from doctr.models.builder import DocumentBuilder
|
|
12
|
-
from doctr.utils.geometry import
|
|
13
|
+
from doctr.utils.geometry import (
|
|
14
|
+
extract_crops,
|
|
15
|
+
extract_rcrops,
|
|
16
|
+
remove_image_padding,
|
|
17
|
+
rotate_image,
|
|
18
|
+
straighten_page,
|
|
19
|
+
)
|
|
13
20
|
|
|
14
|
-
from .._utils import estimate_orientation, rectify_crops, rectify_loc_preds
|
|
21
|
+
from .._utils import estimate_orientation, mask_boxes, rectify_crops, rectify_loc_preds
|
|
15
22
|
from ..classification import crop_orientation_predictor, page_orientation_predictor
|
|
16
23
|
from ..classification.predictor import OrientationPredictor
|
|
17
24
|
|
|
@@ -31,6 +38,11 @@ class _OCRPredictor:
|
|
|
31
38
|
symmetric_pad: if True and preserve_aspect_ratio is True, pas the image symmetrically.
|
|
32
39
|
detect_orientation: if True, the estimated general page orientation will be added to the predictions for each
|
|
33
40
|
page. Doing so will slightly deteriorate the overall latency.
|
|
41
|
+
ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
|
|
42
|
+
layout model will be used to locate the regions of the specified classes, and these regions will
|
|
43
|
+
be masked out (filled with black) before passing the pages to the detection/recognition modules.
|
|
44
|
+
preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
|
|
45
|
+
original page coordinates. Useful for redaction and annotation.
|
|
34
46
|
**kwargs: keyword args of `DocumentBuilder`
|
|
35
47
|
"""
|
|
36
48
|
|
|
@@ -44,10 +56,13 @@ class _OCRPredictor:
|
|
|
44
56
|
preserve_aspect_ratio: bool = True,
|
|
45
57
|
symmetric_pad: bool = True,
|
|
46
58
|
detect_orientation: bool = False,
|
|
59
|
+
ignore_regions: Collection[str] | None = None,
|
|
60
|
+
preserve_original_coords: bool = False,
|
|
47
61
|
**kwargs: Any,
|
|
48
62
|
) -> None:
|
|
49
63
|
self.assume_straight_pages = assume_straight_pages
|
|
50
64
|
self.straighten_pages = straighten_pages
|
|
65
|
+
self.preserve_original_coords = preserve_original_coords
|
|
51
66
|
self._page_orientation_disabled = kwargs.pop("disable_page_orientation", False)
|
|
52
67
|
self._crop_orientation_disabled = kwargs.pop("disable_crop_orientation", False)
|
|
53
68
|
self.crop_orientation_predictor = (
|
|
@@ -61,8 +76,12 @@ class _OCRPredictor:
|
|
|
61
76
|
else None
|
|
62
77
|
)
|
|
63
78
|
self.doc_builder = DocumentBuilder(**kwargs)
|
|
79
|
+
|
|
64
80
|
self.preserve_aspect_ratio = preserve_aspect_ratio
|
|
65
81
|
self.symmetric_pad = symmetric_pad
|
|
82
|
+
|
|
83
|
+
self.ignore_regions = ignore_regions
|
|
84
|
+
|
|
66
85
|
self.hooks: list[Callable] = []
|
|
67
86
|
|
|
68
87
|
def _general_page_orientations(
|
|
@@ -88,13 +107,33 @@ class _OCRPredictor:
|
|
|
88
107
|
]
|
|
89
108
|
return general_pages_orientations, origin_page_orientations
|
|
90
109
|
|
|
110
|
+
def _mask_regions(
|
|
111
|
+
self,
|
|
112
|
+
pages: list[np.ndarray],
|
|
113
|
+
regions: list[dict[str, Any]] | None,
|
|
114
|
+
fill_value: int = 0,
|
|
115
|
+
) -> list[np.ndarray]:
|
|
116
|
+
if regions is None or not self.ignore_regions:
|
|
117
|
+
return pages
|
|
118
|
+
|
|
119
|
+
out_pages: list[np.ndarray] = []
|
|
120
|
+
for page, region in zip(pages, regions):
|
|
121
|
+
if region is None:
|
|
122
|
+
out_pages.append(page)
|
|
123
|
+
continue
|
|
124
|
+
boxes = np.asarray(region["boxes"], dtype=np.float32)
|
|
125
|
+
keep = np.array([name in self.ignore_regions for name in region["class_names"]], dtype=bool)
|
|
126
|
+
out_pages.append(mask_boxes(page, boxes[keep], fill_value=fill_value) if keep.any() else page)
|
|
127
|
+
|
|
128
|
+
return out_pages
|
|
129
|
+
|
|
91
130
|
def _straighten_pages(
|
|
92
131
|
self,
|
|
93
132
|
pages: list[np.ndarray],
|
|
94
133
|
seg_maps: list[np.ndarray],
|
|
95
134
|
general_pages_orientations: list[tuple[int, float]] | None = None,
|
|
96
135
|
origin_pages_orientations: list[int] | None = None,
|
|
97
|
-
) -> list[np.ndarray]:
|
|
136
|
+
) -> tuple[list[np.ndarray], list[np.ndarray]]:
|
|
98
137
|
general_pages_orientations = (
|
|
99
138
|
general_pages_orientations if general_pages_orientations else self._general_page_orientations(pages)
|
|
100
139
|
)
|
|
@@ -106,11 +145,20 @@ class _OCRPredictor:
|
|
|
106
145
|
for seq_map, general_orientation in zip(seg_maps, general_pages_orientations)
|
|
107
146
|
]
|
|
108
147
|
)
|
|
109
|
-
|
|
148
|
+
if not self.preserve_original_coords:
|
|
110
149
|
# expand if height and width are not equal, then remove the padding
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
150
|
+
return [
|
|
151
|
+
remove_image_padding(rotate_image(page, angle, expand=page.shape[0] != page.shape[1]))
|
|
152
|
+
for page, angle in zip(pages, origin_pages_orientations)
|
|
153
|
+
], []
|
|
154
|
+
|
|
155
|
+
m_invs = []
|
|
156
|
+
out = []
|
|
157
|
+
for page, angle in zip(pages, origin_pages_orientations):
|
|
158
|
+
straightened, m_inv = straighten_page(page, angle)
|
|
159
|
+
m_invs.append(m_inv)
|
|
160
|
+
out.append(straightened)
|
|
161
|
+
return out, m_invs
|
|
114
162
|
|
|
115
163
|
@staticmethod
|
|
116
164
|
def _generate_crops(
|
|
@@ -152,19 +200,18 @@ class _OCRPredictor:
|
|
|
152
200
|
crops: list[list[np.ndarray]],
|
|
153
201
|
loc_preds: list[np.ndarray],
|
|
154
202
|
) -> tuple[list[list[np.ndarray]], list[np.ndarray], list[tuple[int, float]]]:
|
|
155
|
-
|
|
156
|
-
|
|
203
|
+
page_counts = [len(page_crops) for page_crops in crops]
|
|
204
|
+
flat_crops = [crop for page_crops in crops for crop in page_crops]
|
|
205
|
+
flat_orientations, flat_classes, flat_probs = self.crop_orientation_predictor(flat_crops) # type: ignore[misc]
|
|
206
|
+
_bounds = np.cumsum([0, *page_counts])
|
|
207
|
+
orientations = [flat_orientations[start:end] for start, end in zip(_bounds[:-1], _bounds[1:])]
|
|
157
208
|
rect_crops = [rectify_crops(page_crops, orientation) for page_crops, orientation in zip(crops, orientations)]
|
|
158
209
|
rect_loc_preds = [
|
|
159
210
|
rectify_loc_preds(page_loc_preds, orientation) if len(page_loc_preds) > 0 else page_loc_preds
|
|
160
211
|
for page_loc_preds, orientation in zip(loc_preds, orientations)
|
|
161
212
|
]
|
|
162
213
|
# Flatten to list of tuples with (value, confidence)
|
|
163
|
-
crop_orientations = [
|
|
164
|
-
(orientation, prob)
|
|
165
|
-
for page_classes, page_probs in zip(classes, probs)
|
|
166
|
-
for orientation, prob in zip(page_classes, page_probs)
|
|
167
|
-
]
|
|
214
|
+
crop_orientations = [(orientation, prob) for orientation, prob in zip(flat_classes, flat_probs)]
|
|
168
215
|
return rect_crops, rect_loc_preds, crop_orientations # type: ignore[return-value]
|
|
169
216
|
|
|
170
217
|
@staticmethod
|
|
@@ -185,6 +232,81 @@ class _OCRPredictor:
|
|
|
185
232
|
|
|
186
233
|
return loc_preds, text_preds, crop_orientation_preds
|
|
187
234
|
|
|
235
|
+
@staticmethod
|
|
236
|
+
def _remap_geometry(obj: Any, m_inv: np.ndarray, sw: int, sh: int, oh: int, ow: int) -> None:
|
|
237
|
+
"""Remap a single geometry-bearing object from straightened to original coords."""
|
|
238
|
+
pts = np.asarray(obj.geometry, dtype=np.float64).reshape(-1, 2)
|
|
239
|
+
was_straight = pts.shape[0] == 2
|
|
240
|
+
if was_straight:
|
|
241
|
+
(x0, y0), (x1, y1) = pts
|
|
242
|
+
pts = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float64)
|
|
243
|
+
pts[:, 0] *= sw
|
|
244
|
+
pts[:, 1] *= sh
|
|
245
|
+
homo = np.column_stack([pts, np.ones(len(pts))])
|
|
246
|
+
orig = (homo @ m_inv.T)[:, :2]
|
|
247
|
+
orig[:, 0] = orig[:, 0].clip(0, ow - 1) / ow
|
|
248
|
+
orig[:, 1] = orig[:, 1].clip(0, oh - 1) / oh
|
|
249
|
+
if was_straight:
|
|
250
|
+
obj.geometry = (
|
|
251
|
+
(float(orig[:, 0].min()), float(orig[:, 1].min())),
|
|
252
|
+
(float(orig[:, 0].max()), float(orig[:, 1].max())),
|
|
253
|
+
)
|
|
254
|
+
else:
|
|
255
|
+
obj.geometry = tuple(tuple(r) for r in orig.tolist())
|
|
256
|
+
|
|
257
|
+
def _remap_to_original_coords(
|
|
258
|
+
self,
|
|
259
|
+
out: Document,
|
|
260
|
+
orig_shapes: list[tuple[int, int]],
|
|
261
|
+
straight_shapes: list[tuple[int, int]],
|
|
262
|
+
m_invs: list[np.ndarray],
|
|
263
|
+
orig_pages: list[np.ndarray] | None = None,
|
|
264
|
+
) -> Document:
|
|
265
|
+
"""Remap word geometries from straightened-page coordinates back to original page coordinates.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
out: the document returned by the builder
|
|
269
|
+
orig_shapes: original (pre-straightening) page shapes (H, W)
|
|
270
|
+
straight_shapes: straightened page shapes (H, W)
|
|
271
|
+
m_invs: inverse affine matrices from the straightening pipeline, one per page
|
|
272
|
+
orig_pages: optional list of original page images to restore on `page.page`
|
|
273
|
+
|
|
274
|
+
Returns:
|
|
275
|
+
the document with remapped word geometries
|
|
276
|
+
|
|
277
|
+
"""
|
|
278
|
+
for pidx, (page, m_inv) in enumerate(zip(out.pages, m_invs)):
|
|
279
|
+
sh, sw = straight_shapes[pidx] # straightened_height, straightened_width
|
|
280
|
+
oh, ow = orig_shapes[pidx] # original_height, original_width
|
|
281
|
+
|
|
282
|
+
if isinstance(page, KIEPage):
|
|
283
|
+
for preds in page.predictions.values():
|
|
284
|
+
for pred in preds:
|
|
285
|
+
self._remap_geometry(pred, m_inv, sw, sh, oh, ow)
|
|
286
|
+
for region in page.layout:
|
|
287
|
+
self._remap_geometry(region, m_inv, sw, sh, oh, ow)
|
|
288
|
+
else:
|
|
289
|
+
for block in page.blocks:
|
|
290
|
+
self._remap_geometry(block, m_inv, sw, sh, oh, ow)
|
|
291
|
+
for artefact in block.artefacts:
|
|
292
|
+
self._remap_geometry(artefact, m_inv, sw, sh, oh, ow)
|
|
293
|
+
for line in block.lines:
|
|
294
|
+
self._remap_geometry(line, m_inv, sw, sh, oh, ow)
|
|
295
|
+
for word in line.words:
|
|
296
|
+
self._remap_geometry(word, m_inv, sw, sh, oh, ow)
|
|
297
|
+
for region in page.layout:
|
|
298
|
+
self._remap_geometry(region, m_inv, sw, sh, oh, ow)
|
|
299
|
+
for table in page.tables:
|
|
300
|
+
self._remap_geometry(table, m_inv, sw, sh, oh, ow)
|
|
301
|
+
for cell in table.cells:
|
|
302
|
+
self._remap_geometry(cell, m_inv, sw, sh, oh, ow)
|
|
303
|
+
|
|
304
|
+
if orig_pages is not None:
|
|
305
|
+
out.pages[pidx].page = orig_pages[pidx]
|
|
306
|
+
out.pages[pidx].dimensions = orig_shapes[pidx]
|
|
307
|
+
|
|
308
|
+
return out
|
|
309
|
+
|
|
188
310
|
def add_hook(self, hook: Callable) -> None:
|
|
189
311
|
"""Add a hook to the predictor
|
|
190
312
|
|