python-doctr 1.1.0__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/models/_utils.py
CHANGED
|
@@ -4,17 +4,21 @@
|
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
6
|
import heapq
|
|
7
|
-
from
|
|
7
|
+
from collections.abc import Callable, Iterable, Sequence
|
|
8
|
+
from math import ceil, floor, isnan
|
|
8
9
|
from statistics import median_low
|
|
9
|
-
from typing import Any
|
|
10
|
+
from typing import Any, Literal, TypeAlias, TypeVar
|
|
10
11
|
|
|
11
12
|
import cv2
|
|
12
13
|
import numpy as np
|
|
13
14
|
from langdetect import LangDetectException, detect_langs
|
|
14
15
|
|
|
15
16
|
from doctr.utils.geometry import rotate_image
|
|
17
|
+
from doctr.utils.multithreading import prefetch_chunks
|
|
16
18
|
|
|
17
19
|
__all__ = [
|
|
20
|
+
"ConfidenceAggregation",
|
|
21
|
+
"aggregate_confidence",
|
|
18
22
|
"estimate_orientation",
|
|
19
23
|
"get_language",
|
|
20
24
|
"invert_data_structure",
|
|
@@ -23,6 +27,84 @@ __all__ = [
|
|
|
23
27
|
"rectify_loc_preds",
|
|
24
28
|
]
|
|
25
29
|
|
|
30
|
+
ConfidenceAggregation: TypeAlias = (
|
|
31
|
+
Literal["mean", "min", "max", "median", "geometric_mean", "harmonic_mean"] | Callable[[np.ndarray], float]
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _geometric_mean(scores: np.ndarray) -> float:
|
|
36
|
+
# numerically stable form of prod(scores) ** (1 / N), a zero score yields 0
|
|
37
|
+
with np.errstate(divide="ignore"):
|
|
38
|
+
return float(np.exp(np.mean(np.log(scores, dtype=np.float64))))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _harmonic_mean(scores: np.ndarray) -> float:
|
|
42
|
+
# a zero score yields 0
|
|
43
|
+
with np.errstate(divide="ignore"):
|
|
44
|
+
return float(scores.size / np.sum(1.0 / scores.astype(np.float64)))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_CONFIDENCE_AGGREGATIONS: dict[str, Callable[[np.ndarray], Any]] = {
|
|
48
|
+
"mean": np.mean,
|
|
49
|
+
"min": np.min,
|
|
50
|
+
"max": np.max,
|
|
51
|
+
"median": np.median,
|
|
52
|
+
"geometric_mean": _geometric_mean,
|
|
53
|
+
"harmonic_mean": _harmonic_mean,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _resolve_confidence_aggregation(method: ConfidenceAggregation) -> Callable[[np.ndarray], Any]:
|
|
58
|
+
"""Return the function of a confidence aggregation method, raise a `ValueError` if it is unknown"""
|
|
59
|
+
if callable(method):
|
|
60
|
+
return method
|
|
61
|
+
# the type check comes first: an unhashable value (e.g. a list) can not be looked up
|
|
62
|
+
if not isinstance(method, str) or method not in _CONFIDENCE_AGGREGATIONS:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
f"Unknown confidence aggregation {method!r}, expected a callable or one of {list(_CONFIDENCE_AGGREGATIONS)}"
|
|
65
|
+
)
|
|
66
|
+
return _CONFIDENCE_AGGREGATIONS[method]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _confidence_aggregation_repr(method: ConfidenceAggregation) -> str:
|
|
70
|
+
"""Return the name of a confidence aggregation method to display it in a `repr`"""
|
|
71
|
+
return repr(method) if isinstance(method, str) else getattr(method, "__name__", type(method).__name__)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def aggregate_confidence(
|
|
75
|
+
scores: np.ndarray | Sequence[float],
|
|
76
|
+
method: ConfidenceAggregation = "mean",
|
|
77
|
+
) -> float:
|
|
78
|
+
"""Aggregate several scores (e.g. the character probabilities of a word) into a single confidence score
|
|
79
|
+
|
|
80
|
+
>>> from doctr.models._utils import aggregate_confidence
|
|
81
|
+
>>> aggregate_confidence([0.99, 0.98, 0.12, 0.99], "min")
|
|
82
|
+
0.12
|
|
83
|
+
|
|
84
|
+
Available methods:
|
|
85
|
+
- "mean": arithmetic mean, a single low score can be hidden by many high ones
|
|
86
|
+
- "min": the lowest score, a single low score is enough to lower the confidence
|
|
87
|
+
- "max": the highest score
|
|
88
|
+
- "median": the median score, robust to outliers
|
|
89
|
+
- "geometric_mean": `exp(mean(log(scores)))`, i.e. the exponential of the average log-probability
|
|
90
|
+
- "harmonic_mean": strongly penalizes low scores
|
|
91
|
+
- a Python callable taking the 1D array of scores and returning a float
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
scores: the scores to aggregate, expected in [0, 1]
|
|
95
|
+
method: the aggregation method
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
the aggregated confidence clipped to [0, 1], 0 if there is no score or if the aggregation is NaN (e.g. a
|
|
99
|
+
callable averaging an empty selection)
|
|
100
|
+
"""
|
|
101
|
+
aggregate = _resolve_confidence_aggregation(method)
|
|
102
|
+
scores = np.asarray(scores).ravel()
|
|
103
|
+
if scores.size == 0:
|
|
104
|
+
return 0.0
|
|
105
|
+
value = float(np.asarray(aggregate(scores)).squeeze())
|
|
106
|
+
return 0.0 if isnan(value) else min(max(value, 0.0), 1.0)
|
|
107
|
+
|
|
26
108
|
|
|
27
109
|
def get_max_width_length_ratio(contour: np.ndarray) -> float:
|
|
28
110
|
"""Get the maximum shape ratio of a contour.
|
|
@@ -51,7 +133,7 @@ def estimate_orientation(
|
|
|
51
133
|
lines of the document and the assumption that they should be horizontal.
|
|
52
134
|
|
|
53
135
|
Args:
|
|
54
|
-
img: the img or bitmap to analyze (H, W, C)
|
|
136
|
+
img: the img (in np.uint8, or as floats in [0, 1]) or bitmap to analyze (H, W, C)
|
|
55
137
|
general_page_orientation: the general orientation of the page (angle [0, 90, 180, 270 (-90)], confidence)
|
|
56
138
|
estimated by a model
|
|
57
139
|
n_ct: the number of contours used for the orientation estimation
|
|
@@ -66,6 +148,9 @@ def estimate_orientation(
|
|
|
66
148
|
|
|
67
149
|
# Convert image to grayscale if necessary
|
|
68
150
|
if img.shape[-1] == 3:
|
|
151
|
+
if np.issubdtype(img.dtype, np.floating):
|
|
152
|
+
# Otsu thresholding needs 8-bit values: a float image holds values in [0, 1]
|
|
153
|
+
img = (img * 255).round().clip(0, 255).astype(np.uint8)
|
|
69
154
|
gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
|
70
155
|
gray_img = cv2.medianBlur(gray_img, 5)
|
|
71
156
|
thresh = cv2.threshold(gray_img, thresh=0, maxval=255, type=cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
|
|
@@ -270,9 +355,69 @@ def invert_data_structure(
|
|
|
270
355
|
dictionary of list when x is a list of dictionaries or a list of dictionaries when x is dictionary of lists
|
|
271
356
|
"""
|
|
272
357
|
if isinstance(x, dict):
|
|
273
|
-
assert len({len(v) for v in x.values()})
|
|
358
|
+
assert len({len(v) for v in x.values()}) <= 1, "All the lists in the dictionary should have the same length."
|
|
274
359
|
return [dict(zip(x, t)) for t in zip(*x.values())]
|
|
275
360
|
elif isinstance(x, list):
|
|
276
|
-
return {k: [dic[k] for dic in x] for k in x[0]}
|
|
361
|
+
return {k: [dic[k] for dic in x] for k in x[0]} if x else {}
|
|
277
362
|
else:
|
|
278
363
|
raise TypeError(f"Expected input to be either a dict or a list, got {type(x)} instead.")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
_Output = TypeVar("_Output")
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def merge_items(outputs: list[list[Any]]) -> list[Any]:
|
|
370
|
+
"""Concatenate the outputs of several chunks, for predictors returning one item per input"""
|
|
371
|
+
return [item for output in outputs for item in output]
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def merge_columns(outputs: list[Any]) -> Any:
|
|
375
|
+
"""Concatenate the outputs of several chunks column by column, for predictors returning several aligned lists
|
|
376
|
+
(e.g. `[class_idxs, classes, probs]`, or `(preds, seg_maps)`): the container type is kept"""
|
|
377
|
+
columns = [merge_items([output[col] for output in outputs]) for col in range(len(outputs[0]))]
|
|
378
|
+
return tuple(columns) if isinstance(outputs[0], tuple) else columns
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def predict_by_chunks(
|
|
382
|
+
predict: Callable[[list[np.ndarray]], _Output],
|
|
383
|
+
inputs: Sequence[np.ndarray] | Iterable[np.ndarray],
|
|
384
|
+
chunk_size: int,
|
|
385
|
+
batch_size: int = 1,
|
|
386
|
+
merge: Callable[[list[_Output]], _Output] = merge_items, # type: ignore[assignment]
|
|
387
|
+
) -> _Output:
|
|
388
|
+
"""Run a predictor on inputs of any length: a lazy page source (cf. `DocumentFile.from_pdf(..., lazy=True)`), a
|
|
389
|
+
list, a tuple or any iterable of images
|
|
390
|
+
|
|
391
|
+
Lists and tuples of at most `chunk_size` images, as well as arrays (a batch already in memory), are processed at
|
|
392
|
+
once, exactly as before. Anything else is processed chunk by chunk, the next chunk of a lazy source being decoded
|
|
393
|
+
in a background thread, so that the memory footprint does not grow with the number of inputs.
|
|
394
|
+
|
|
395
|
+
The chunk size is rounded up to a multiple of `batch_size`: the model then processes the same batches as in a
|
|
396
|
+
single pass, so that chunking does not change the predictions (a predictor transforming its inputs before batching,
|
|
397
|
+
e.g. the recognition predictor splitting wide crops, does so within each chunk).
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
predict: the prediction function, taking a list of images
|
|
401
|
+
inputs: the images
|
|
402
|
+
chunk_size: the maximum number of images decoded and processed at once
|
|
403
|
+
batch_size: the batch size of the model
|
|
404
|
+
merge: the function concatenating the outputs of the chunks
|
|
405
|
+
|
|
406
|
+
Returns:
|
|
407
|
+
the output of `predict` on the whole input
|
|
408
|
+
"""
|
|
409
|
+
if isinstance(inputs, np.ndarray):
|
|
410
|
+
return predict(inputs) # type: ignore[arg-type]
|
|
411
|
+
if isinstance(inputs, (list, tuple)) and len(inputs) <= chunk_size:
|
|
412
|
+
return predict(list(inputs))
|
|
413
|
+
size = ceil(chunk_size / batch_size) * batch_size
|
|
414
|
+
outputs = []
|
|
415
|
+
chunks = prefetch_chunks(inputs, size)
|
|
416
|
+
try:
|
|
417
|
+
for chunk in chunks:
|
|
418
|
+
outputs.append(predict(chunk))
|
|
419
|
+
finally:
|
|
420
|
+
# Stop decoding ahead on error
|
|
421
|
+
chunks.close()
|
|
422
|
+
# An empty input yields no chunk: let the predictor return its empty output
|
|
423
|
+
return merge(outputs) if outputs else predict([])
|