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/io/sources.py
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
|
+
|
|
3
|
+
# This program is licensed under the Apache License 2.0.
|
|
4
|
+
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
|
+
|
|
6
|
+
import atexit
|
|
7
|
+
import threading
|
|
8
|
+
import weakref
|
|
9
|
+
from bisect import bisect_right
|
|
10
|
+
from collections.abc import Generator, Iterable, Iterator, Sequence
|
|
11
|
+
from contextlib import AbstractContextManager, closing, contextmanager, nullcontext
|
|
12
|
+
from itertools import accumulate, groupby
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, overload
|
|
15
|
+
|
|
16
|
+
import cv2
|
|
17
|
+
import numpy as np
|
|
18
|
+
import pypdfium2 as pdfium
|
|
19
|
+
from PIL import Image
|
|
20
|
+
|
|
21
|
+
from doctr.utils.common_types import AbstractFile
|
|
22
|
+
|
|
23
|
+
from .image import read_img_as_numpy
|
|
24
|
+
|
|
25
|
+
__all__ = ["PageSource", "PDFSource", "ImageSource", "ConcatSource", "PageDecodeError", "IMAGE_EXTENSIONS"]
|
|
26
|
+
|
|
27
|
+
# File extensions recognized as images when a directory is expanded
|
|
28
|
+
IMAGE_EXTENSIONS: tuple[str, ...] = (
|
|
29
|
+
".jpg",
|
|
30
|
+
".jpeg",
|
|
31
|
+
".png",
|
|
32
|
+
".bmp",
|
|
33
|
+
".tif",
|
|
34
|
+
".tiff",
|
|
35
|
+
".webp",
|
|
36
|
+
".jp2",
|
|
37
|
+
".pbm",
|
|
38
|
+
".pgm",
|
|
39
|
+
".ppm",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# pdfium is not thread-safe, not even across different documents: every call into it is serialized,
|
|
43
|
+
# which makes it safe to render pages in a background thread (cf. `OCRPredictor.stream`)
|
|
44
|
+
_PDFIUM_LOCK = threading.RLock()
|
|
45
|
+
# Sources holding an open PDF: they are closed at exit, before pypdfium2 reports the documents left open
|
|
46
|
+
_OPEN_PDF_SOURCES: "weakref.WeakSet[PDFSource]" = weakref.WeakSet()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@atexit.register
|
|
50
|
+
def _close_pdf_sources() -> None: # pragma: no cover
|
|
51
|
+
for source in list(_OPEN_PDF_SOURCES):
|
|
52
|
+
source.close()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PageDecodeError(ValueError):
|
|
56
|
+
"""Raised when a page of a source cannot be decoded (e.g. an unreadable or corrupted image file, a PDF that
|
|
57
|
+
cannot be opened or rendered, or a web page that cannot be fetched). The message names the faulty file or URL.
|
|
58
|
+
|
|
59
|
+
It subclasses `ValueError`, so that code catching the errors of the eager readers keeps working.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _PDFError(PageDecodeError, pdfium.PdfiumError):
|
|
64
|
+
"""A PDF that cannot be opened or rendered: a `PageDecodeError` naming the file, which is still the
|
|
65
|
+
`pypdfium2.PdfiumError` raised by the eager readers so far"""
|
|
66
|
+
|
|
67
|
+
def __init__(self, msg: str, err_code: int | None = None) -> None:
|
|
68
|
+
super().__init__(msg)
|
|
69
|
+
self.err_code = err_code
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _err_code(error: pdfium.PdfiumError) -> int | None:
|
|
73
|
+
"""The pdfium error code of an error, if any (pypdfium2 only provides it as of version 5)"""
|
|
74
|
+
return getattr(error, "err_code", None)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Errors of a page that cannot be read: a corrupted file, or an input removed after the source was created. These are
|
|
78
|
+
# the errors that `on_error="skip"` skips (cf. `OCRPredictor.stream`, `DocumentFile.from_files`)
|
|
79
|
+
_PAGE_ERRORS: tuple[type[Exception], ...] = (PageDecodeError, FileNotFoundError)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _UnreadablePage:
|
|
83
|
+
"""Placeholder yielded instead of a page that cannot be read, when iterating with `skip_errors=True`"""
|
|
84
|
+
|
|
85
|
+
__slots__ = ("error",)
|
|
86
|
+
|
|
87
|
+
def __init__(self, error: Exception) -> None:
|
|
88
|
+
self.error = error
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _file_name(file: Any) -> str:
|
|
92
|
+
"""Name of an input in error messages"""
|
|
93
|
+
return str(file) if isinstance(file, (str, Path)) else "<bytes>"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _same_page(page: np.ndarray, value: Any) -> bool:
|
|
97
|
+
"""Whether a page equals a given image: same shape and pixel values"""
|
|
98
|
+
return isinstance(value, np.ndarray) and np.array_equal(page, value)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _is_page_sequence(other: Any) -> bool:
|
|
102
|
+
"""Whether an object can be concatenated with a page source: a sequence of pages, which excludes strings and
|
|
103
|
+
bytes (sequences of characters and integers)"""
|
|
104
|
+
return isinstance(other, Sequence) and not isinstance(other, (str, bytes, bytearray))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _check_image_header(path: Path) -> None:
|
|
108
|
+
"""Fail fast on files that are not images: only their header is read (a few microseconds per file), so that
|
|
109
|
+
an invalid file is reported when the source is created rather than after hours of processing. A file with a
|
|
110
|
+
valid header but a corrupted body is still only detected when it is decoded.
|
|
111
|
+
"""
|
|
112
|
+
if cv2.haveImageReader(str(path)):
|
|
113
|
+
return
|
|
114
|
+
# Formats read with Pillow by `read_img_as_numpy` (e.g. images with transparency)
|
|
115
|
+
try:
|
|
116
|
+
with Image.open(path):
|
|
117
|
+
return
|
|
118
|
+
except (OSError, ValueError, Image.DecompressionBombError):
|
|
119
|
+
pass
|
|
120
|
+
raise PageDecodeError(f"unable to read the image {path}: unknown or invalid image format")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class PageSource(Sequence[np.ndarray]):
|
|
124
|
+
"""Abstract lazy collection of pages: a page is only decoded when it is accessed.
|
|
125
|
+
|
|
126
|
+
A page source behaves like a read-only list of H x W x 3 numpy arrays (`len`, indexing, slicing, iteration),
|
|
127
|
+
but only keeps the encoded inputs in memory. It can be passed to the predictors as-is: they process it in
|
|
128
|
+
chunks, so that documents of any length are handled with a bounded memory footprint.
|
|
129
|
+
|
|
130
|
+
>>> from doctr.io import DocumentFile
|
|
131
|
+
>>> doc = DocumentFile.from_pdf("path/to/your/doc.pdf", lazy=True)
|
|
132
|
+
>>> len(doc), doc[0].shape
|
|
133
|
+
>>> for batch in doc.iter_batches(16):
|
|
134
|
+
... ...
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def __len__(self) -> int:
|
|
138
|
+
raise NotImplementedError
|
|
139
|
+
|
|
140
|
+
def _load(self, idx: int) -> np.ndarray:
|
|
141
|
+
"""Decode the page at a given (non-negative, in-range) index"""
|
|
142
|
+
raise NotImplementedError
|
|
143
|
+
|
|
144
|
+
@overload
|
|
145
|
+
def __getitem__(self, idx: int) -> np.ndarray: ...
|
|
146
|
+
|
|
147
|
+
@overload
|
|
148
|
+
def __getitem__(self, idx: slice) -> "PageSource": ...
|
|
149
|
+
|
|
150
|
+
def __getitem__(self, idx: int | slice) -> "np.ndarray | PageSource":
|
|
151
|
+
if isinstance(idx, slice):
|
|
152
|
+
return _PageView(self, range(len(self))[idx])
|
|
153
|
+
if not isinstance(idx, (int, np.integer)):
|
|
154
|
+
raise TypeError(f"page indices must be integers or slices, not {type(idx).__name__}")
|
|
155
|
+
num_pages = len(self)
|
|
156
|
+
_idx = int(idx) + num_pages if idx < 0 else int(idx)
|
|
157
|
+
if not 0 <= _idx < num_pages:
|
|
158
|
+
raise IndexError(f"page index {idx} is out of range for a document of {num_pages} page(s)")
|
|
159
|
+
return self._load(_idx)
|
|
160
|
+
|
|
161
|
+
def _page_ref(self, idx: int) -> "_SourcePage | None":
|
|
162
|
+
"""A reference decoding the page at a given (non-negative, in-range) index again on demand, kept by the
|
|
163
|
+
predictions instead of the page image.
|
|
164
|
+
|
|
165
|
+
It points to the input of the page only (e.g. its image file, rather than every file of a folder), so that
|
|
166
|
+
pickling or copying a prediction does not carry the whole document along.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
the reference, or None if the page is held in memory anyway (it is then kept as is)
|
|
170
|
+
"""
|
|
171
|
+
return _SourcePage(self, idx)
|
|
172
|
+
|
|
173
|
+
def _session(self) -> AbstractContextManager[Any]:
|
|
174
|
+
"""Context during which the resources needed to decode the pages (e.g. an open PDF) are kept.
|
|
175
|
+
|
|
176
|
+
Iterations run within one, so that the resources are acquired once for the whole pass. Outside of it, an
|
|
177
|
+
access to a single page (`source[idx]`) acquires them for that page only, and releases them right after.
|
|
178
|
+
"""
|
|
179
|
+
return nullcontext()
|
|
180
|
+
|
|
181
|
+
def _iter_indices(self, indices: Iterable[int], skip_errors: bool = False) -> Generator[Any, None, None]:
|
|
182
|
+
"""Decode the pages at the given (non-negative, in-range) indices, in this order
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
indices: the page indices
|
|
186
|
+
skip_errors: if True, a page that cannot be read (cf. `_PAGE_ERRORS`) is replaced by an `_UnreadablePage`
|
|
187
|
+
holding the error, and the iteration goes on. Otherwise the error is raised.
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
an iterator over the pages (and `_UnreadablePage` placeholders if `skip_errors` is True)
|
|
191
|
+
"""
|
|
192
|
+
with self._session():
|
|
193
|
+
for idx in indices:
|
|
194
|
+
if not skip_errors:
|
|
195
|
+
yield self._load(idx)
|
|
196
|
+
continue
|
|
197
|
+
try:
|
|
198
|
+
page = self._load(idx)
|
|
199
|
+
except _PAGE_ERRORS as e:
|
|
200
|
+
yield _UnreadablePage(e)
|
|
201
|
+
else:
|
|
202
|
+
yield page
|
|
203
|
+
|
|
204
|
+
def __iter__(self) -> Iterator[np.ndarray]:
|
|
205
|
+
return self._iter_indices(range(len(self)))
|
|
206
|
+
|
|
207
|
+
def __reversed__(self) -> Iterator[np.ndarray]:
|
|
208
|
+
# Within a single session, as an iteration (the default implementation would open a PDF once per page)
|
|
209
|
+
return self._iter_indices(range(len(self) - 1, -1, -1))
|
|
210
|
+
|
|
211
|
+
# The `Sequence` implementations compare pages with `==`, which is ambiguous for arrays: pages are compared by
|
|
212
|
+
# value instead. Each of these decodes the pages until a match is found.
|
|
213
|
+
|
|
214
|
+
def index(self, value: Any, start: int = 0, stop: int | None = None) -> int:
|
|
215
|
+
"""Index of the first page equal to a given image (same shape and pixel values)
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
value: the image to look for
|
|
219
|
+
start: the index to start searching from
|
|
220
|
+
stop: the index to stop searching at (excluded)
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
the index of the first matching page
|
|
224
|
+
"""
|
|
225
|
+
# Only an array can be a page: anything else is not found without decoding any page
|
|
226
|
+
if isinstance(value, np.ndarray):
|
|
227
|
+
indices = range(*slice(start, stop).indices(len(self)))
|
|
228
|
+
# Closed on a match, so that the resources of the iteration (e.g. an open PDF) are released right away
|
|
229
|
+
with closing(self._iter_indices(indices)) as pages:
|
|
230
|
+
for idx, page in zip(indices, pages):
|
|
231
|
+
if _same_page(page, value):
|
|
232
|
+
return idx
|
|
233
|
+
raise ValueError("the image is not a page of the source")
|
|
234
|
+
|
|
235
|
+
def count(self, value: Any) -> int:
|
|
236
|
+
"""Number of pages equal to a given image (same shape and pixel values)"""
|
|
237
|
+
if not isinstance(value, np.ndarray):
|
|
238
|
+
return 0
|
|
239
|
+
return sum(_same_page(page, value) for page in self)
|
|
240
|
+
|
|
241
|
+
def __contains__(self, value: object) -> bool:
|
|
242
|
+
try:
|
|
243
|
+
self.index(value)
|
|
244
|
+
except ValueError:
|
|
245
|
+
return False
|
|
246
|
+
return True
|
|
247
|
+
|
|
248
|
+
def __add__(self, other: Sequence[np.ndarray]) -> "ConcatSource":
|
|
249
|
+
if not _is_page_sequence(other):
|
|
250
|
+
return NotImplemented
|
|
251
|
+
return ConcatSource([self, other])
|
|
252
|
+
|
|
253
|
+
def __radd__(self, other: Sequence[np.ndarray]) -> "ConcatSource":
|
|
254
|
+
if not _is_page_sequence(other):
|
|
255
|
+
return NotImplemented
|
|
256
|
+
return ConcatSource([other, self])
|
|
257
|
+
|
|
258
|
+
def iter_batches(self, batch_size: int) -> Iterator[list[np.ndarray]]:
|
|
259
|
+
"""Iterate over the pages by batches, only `batch_size` pages being decoded at a time
|
|
260
|
+
|
|
261
|
+
Args:
|
|
262
|
+
batch_size: the number of pages per batch
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
an iterator of lists of pages
|
|
266
|
+
"""
|
|
267
|
+
if batch_size < 1:
|
|
268
|
+
raise ValueError("`batch_size` must be a positive integer")
|
|
269
|
+
batch: list[np.ndarray] = []
|
|
270
|
+
for page in self:
|
|
271
|
+
batch.append(page)
|
|
272
|
+
if len(batch) == batch_size:
|
|
273
|
+
yield batch
|
|
274
|
+
batch = []
|
|
275
|
+
if batch:
|
|
276
|
+
yield batch
|
|
277
|
+
|
|
278
|
+
def close(self) -> None:
|
|
279
|
+
"""Release the resources held by the source (e.g. open PDF handles). The source can still be used
|
|
280
|
+
afterwards: the resources are acquired again on demand.
|
|
281
|
+
|
|
282
|
+
Resources are only held during an iteration or a `with` block: accessing a single page outside of those
|
|
283
|
+
(e.g. `source[idx]`, or `page.page` on a prediction made from this source) releases them right after.
|
|
284
|
+
"""
|
|
285
|
+
|
|
286
|
+
def __enter__(self) -> "PageSource":
|
|
287
|
+
# Keep the resources for the whole block, e.g. for many random accesses to the pages of a PDF
|
|
288
|
+
session = self._session()
|
|
289
|
+
session.__enter__()
|
|
290
|
+
self.__dict__.setdefault("_entered", []).append(session)
|
|
291
|
+
return self
|
|
292
|
+
|
|
293
|
+
def __exit__(self, *args: Any) -> None:
|
|
294
|
+
entered = self.__dict__.get("_entered")
|
|
295
|
+
if entered:
|
|
296
|
+
entered.pop().__exit__(*args)
|
|
297
|
+
if not entered:
|
|
298
|
+
# Leaving the outermost block
|
|
299
|
+
self._release()
|
|
300
|
+
|
|
301
|
+
def _release(self) -> None:
|
|
302
|
+
"""Release the resources once the last `with` block on the source is left"""
|
|
303
|
+
self.close()
|
|
304
|
+
|
|
305
|
+
def __getstate__(self) -> dict[str, Any]:
|
|
306
|
+
# The resources held by a `with` block are not part of the source
|
|
307
|
+
state = self.__dict__.copy()
|
|
308
|
+
state.pop("_entered", None)
|
|
309
|
+
return state
|
|
310
|
+
|
|
311
|
+
def __repr__(self) -> str:
|
|
312
|
+
return f"{self.__class__.__name__}(num_pages={len(self)})"
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
class PDFSource(PageSource):
|
|
316
|
+
"""Lazy PDF document: pages are rasterized on access, so a 1000+ page PDF only costs the memory of
|
|
317
|
+
the pages being processed.
|
|
318
|
+
|
|
319
|
+
>>> from doctr.io import PDFSource
|
|
320
|
+
>>> doc = PDFSource("path/to/your/doc.pdf", scale=2)
|
|
321
|
+
>>> first_page = doc[0]
|
|
322
|
+
>>> with doc: # keep the document open for many random accesses
|
|
323
|
+
... pages = [doc[idx] for idx in (0, 10, 500)]
|
|
324
|
+
|
|
325
|
+
No file handle is held between accesses: an iteration opens the document once for the pass, and accessing a
|
|
326
|
+
single page outside of an iteration or a `with` block opens it for that page only.
|
|
327
|
+
|
|
328
|
+
Args:
|
|
329
|
+
file: the path to the PDF file or its content as bytes
|
|
330
|
+
scale: rendering scale (1 corresponds to 72dpi)
|
|
331
|
+
rgb_mode: if True, the output will be RGB, otherwise BGR
|
|
332
|
+
password: a password to unlock the document, if encrypted
|
|
333
|
+
**kwargs: additional parameters to :meth:`pypdfium2.PdfPage.render`
|
|
334
|
+
"""
|
|
335
|
+
|
|
336
|
+
def __init__(
|
|
337
|
+
self,
|
|
338
|
+
file: AbstractFile,
|
|
339
|
+
scale: float = 2,
|
|
340
|
+
rgb_mode: bool = True,
|
|
341
|
+
password: str | None = None,
|
|
342
|
+
**kwargs: Any,
|
|
343
|
+
) -> None:
|
|
344
|
+
self.file = file
|
|
345
|
+
self.scale = scale
|
|
346
|
+
self.rgb_mode = rgb_mode
|
|
347
|
+
self.password = password
|
|
348
|
+
self.render_kwargs = kwargs
|
|
349
|
+
self._pdf: pdfium.PdfDocument | None = None
|
|
350
|
+
# Number of sessions (iterations, `with` blocks) keeping the document open
|
|
351
|
+
self._holders = 0
|
|
352
|
+
# Open the document eagerly: invalid inputs fail here rather than in the middle of a prediction
|
|
353
|
+
with _PDFIUM_LOCK:
|
|
354
|
+
pdf = self._open()
|
|
355
|
+
self._num_pages = len(pdf)
|
|
356
|
+
# Do not hold a file handle per document: this matters when thousands of PDFs are concatenated
|
|
357
|
+
self.close()
|
|
358
|
+
|
|
359
|
+
def _open(self) -> pdfium.PdfDocument:
|
|
360
|
+
if self._pdf is None:
|
|
361
|
+
file = str(self.file) if isinstance(self.file, Path) else self.file
|
|
362
|
+
try:
|
|
363
|
+
self._pdf = pdfium.PdfDocument(file, password=self.password)
|
|
364
|
+
except pdfium.PdfiumError as e:
|
|
365
|
+
# e.g. a truncated, empty or password-protected file: point to it among possibly thousands of PDFs
|
|
366
|
+
raise _PDFError(f"unable to open the PDF {_file_name(self.file)}: {e}", _err_code(e)) from e
|
|
367
|
+
_OPEN_PDF_SOURCES.add(self)
|
|
368
|
+
return self._pdf
|
|
369
|
+
|
|
370
|
+
def __len__(self) -> int:
|
|
371
|
+
return self._num_pages
|
|
372
|
+
|
|
373
|
+
@contextmanager
|
|
374
|
+
def _session(self) -> Generator[None, None, None]:
|
|
375
|
+
with _PDFIUM_LOCK:
|
|
376
|
+
self._holders += 1
|
|
377
|
+
try:
|
|
378
|
+
yield
|
|
379
|
+
finally:
|
|
380
|
+
with _PDFIUM_LOCK:
|
|
381
|
+
self._holders -= 1
|
|
382
|
+
# Release the file handle once nobody reads the document anymore
|
|
383
|
+
if self._holders == 0:
|
|
384
|
+
self.close()
|
|
385
|
+
|
|
386
|
+
def _load(self, idx: int) -> np.ndarray:
|
|
387
|
+
with _PDFIUM_LOCK:
|
|
388
|
+
# Outside of any session (e.g. `source[idx]`, or the page image of a prediction accessed later on), the
|
|
389
|
+
# document is only opened for this page: no file handle is left behind. Within a session, it is kept open
|
|
390
|
+
# (and opened again if it was closed in the meantime).
|
|
391
|
+
transient = self._pdf is None and self._holders == 0
|
|
392
|
+
pdf = self._open()
|
|
393
|
+
try:
|
|
394
|
+
page = pdf[idx]
|
|
395
|
+
try:
|
|
396
|
+
bitmap = page.render(scale=self.scale, rev_byteorder=self.rgb_mode, **self.render_kwargs)
|
|
397
|
+
# By default, the bitmap buffer is allocated by Python: the array safely outlives the pdfium page,
|
|
398
|
+
# bitmap & document
|
|
399
|
+
pixels = bitmap.to_numpy()
|
|
400
|
+
# A bitmap of the caller's choice (`bitmap_maker`) may have a pdfium-owned buffer instead, freed
|
|
401
|
+
# with the bitmap (e.g. `PdfBitmap.new_foreign`): its pixels are copied
|
|
402
|
+
array = pixels.copy() if "bitmap_maker" in self.render_kwargs else pixels
|
|
403
|
+
# Release the pdfium bitmap here, under the lock: its finalizer runs as soon as the last reference
|
|
404
|
+
# is dropped, which would otherwise happen once the lock is released, possibly while another
|
|
405
|
+
# thread renders a page
|
|
406
|
+
del bitmap, pixels
|
|
407
|
+
return array
|
|
408
|
+
except pdfium.PdfiumError as e:
|
|
409
|
+
raise _PDFError(
|
|
410
|
+
f"unable to render page {idx + 1} of the PDF {_file_name(self.file)}: {e}", _err_code(e)
|
|
411
|
+
) from e
|
|
412
|
+
finally:
|
|
413
|
+
page.close()
|
|
414
|
+
finally:
|
|
415
|
+
if transient:
|
|
416
|
+
self.close()
|
|
417
|
+
|
|
418
|
+
def close(self) -> None:
|
|
419
|
+
with _PDFIUM_LOCK:
|
|
420
|
+
if self._pdf is not None:
|
|
421
|
+
self._pdf.close()
|
|
422
|
+
self._pdf = None
|
|
423
|
+
_OPEN_PDF_SOURCES.discard(self)
|
|
424
|
+
|
|
425
|
+
def _release(self) -> None:
|
|
426
|
+
# The document is closed by the last session releasing it: an iteration still running in another thread
|
|
427
|
+
# keeps it open
|
|
428
|
+
pass
|
|
429
|
+
|
|
430
|
+
def __getstate__(self) -> dict[str, Any]:
|
|
431
|
+
# pdfium handles cannot be pickled: the document is re-opened on demand
|
|
432
|
+
state = super().__getstate__()
|
|
433
|
+
state["_pdf"] = None
|
|
434
|
+
state["_holders"] = 0
|
|
435
|
+
return state
|
|
436
|
+
|
|
437
|
+
def __repr__(self) -> str:
|
|
438
|
+
return f"{self.__class__.__name__}({_file_name(self.file)}, num_pages={len(self)})"
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class ImageSource(PageSource):
|
|
442
|
+
"""Lazy collection of images: each image is only decoded when it is accessed, so that tens of thousands
|
|
443
|
+
of files can be processed in a single call.
|
|
444
|
+
|
|
445
|
+
>>> from doctr.io import ImageSource
|
|
446
|
+
>>> doc = ImageSource(["path/to/page1.png", "path/to/page2.png"])
|
|
447
|
+
>>> doc = ImageSource("path/to/a/folder") # every image of the folder, sorted by name
|
|
448
|
+
|
|
449
|
+
Missing files and files that are not images (checked from their header only) are reported when the source is
|
|
450
|
+
created. An image that still cannot be decoded raises a :class:`~doctr.io.PageDecodeError` naming the file
|
|
451
|
+
when it is accessed.
|
|
452
|
+
|
|
453
|
+
Args:
|
|
454
|
+
files: the path to an image file, to a directory of images, or an image as bytes, or a collection of those
|
|
455
|
+
**kwargs: additional parameters to :meth:`doctr.io.image.read_img_as_numpy`
|
|
456
|
+
"""
|
|
457
|
+
|
|
458
|
+
def __init__(self, files: Sequence[AbstractFile] | AbstractFile, **kwargs: Any) -> None:
|
|
459
|
+
self.files: list[AbstractFile] = []
|
|
460
|
+
for file in [files] if isinstance(files, (str, Path, bytes)) else files:
|
|
461
|
+
if isinstance(file, (str, Path)):
|
|
462
|
+
path = Path(file)
|
|
463
|
+
if path.is_dir():
|
|
464
|
+
for image_path in _list_files(path, IMAGE_EXTENSIONS):
|
|
465
|
+
_check_image_header(image_path)
|
|
466
|
+
self.files.append(image_path)
|
|
467
|
+
continue
|
|
468
|
+
if not path.is_file():
|
|
469
|
+
raise FileNotFoundError(f"unable to access {file}")
|
|
470
|
+
_check_image_header(path)
|
|
471
|
+
elif not isinstance(file, bytes):
|
|
472
|
+
raise TypeError(f"unsupported object type for an image file: {type(file).__name__}")
|
|
473
|
+
self.files.append(file)
|
|
474
|
+
self.read_kwargs = kwargs
|
|
475
|
+
|
|
476
|
+
def __len__(self) -> int:
|
|
477
|
+
return len(self.files)
|
|
478
|
+
|
|
479
|
+
def _load(self, idx: int) -> np.ndarray:
|
|
480
|
+
file = self.files[idx]
|
|
481
|
+
try:
|
|
482
|
+
return read_img_as_numpy(file, **self.read_kwargs)
|
|
483
|
+
except ValueError as e:
|
|
484
|
+
# Images are decoded lazily: point to the faulty file among possibly thousands of them
|
|
485
|
+
name = file if isinstance(file, (str, Path)) else f"<bytes #{idx}>"
|
|
486
|
+
raise PageDecodeError(f"unable to read the image {name!s}: {e}") from e
|
|
487
|
+
|
|
488
|
+
def _page_ref(self, idx: int) -> "_SourcePage":
|
|
489
|
+
# A source of this image only: the file was already checked, and the other files are left out
|
|
490
|
+
single = ImageSource.__new__(ImageSource)
|
|
491
|
+
single.files = [self.files[idx]]
|
|
492
|
+
single.read_kwargs = self.read_kwargs
|
|
493
|
+
return _SourcePage(single, 0)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
class ConcatSource(PageSource):
|
|
497
|
+
"""Concatenation of several page sources (or in-memory lists of pages) into a single lazy document.
|
|
498
|
+
|
|
499
|
+
>>> from doctr.io import ConcatSource, PDFSource, ImageSource
|
|
500
|
+
>>> doc = ConcatSource([PDFSource("report.pdf"), ImageSource("scans/")])
|
|
501
|
+
>>> source_idx, page_idx = doc.locate(42) # where does the 43rd page come from?
|
|
502
|
+
|
|
503
|
+
Args:
|
|
504
|
+
sources: the sequences of pages to concatenate
|
|
505
|
+
"""
|
|
506
|
+
|
|
507
|
+
def __init__(self, sources: Iterable[Sequence[np.ndarray]]) -> None:
|
|
508
|
+
self.sources: list[Sequence[np.ndarray]] = []
|
|
509
|
+
for source in sources:
|
|
510
|
+
# Flatten nested concatenations
|
|
511
|
+
self.sources.extend(source.sources if isinstance(source, ConcatSource) else [source])
|
|
512
|
+
self._offsets = [0, *accumulate(len(source) for source in self.sources)]
|
|
513
|
+
|
|
514
|
+
def __len__(self) -> int:
|
|
515
|
+
return self._offsets[-1]
|
|
516
|
+
|
|
517
|
+
def locate(self, idx: int) -> tuple[int, int]:
|
|
518
|
+
"""Map a page index of the concatenation to the index of its source and its page index in that source
|
|
519
|
+
|
|
520
|
+
Args:
|
|
521
|
+
idx: the page index in the concatenation
|
|
522
|
+
|
|
523
|
+
Returns:
|
|
524
|
+
a tuple (index of the source in `sources`, index of the page in that source)
|
|
525
|
+
"""
|
|
526
|
+
_idx = idx + len(self) if idx < 0 else idx
|
|
527
|
+
if not 0 <= _idx < len(self):
|
|
528
|
+
raise IndexError(f"page index {idx} is out of range for a document of {len(self)} page(s)")
|
|
529
|
+
source_idx = bisect_right(self._offsets, _idx) - 1
|
|
530
|
+
return source_idx, _idx - self._offsets[source_idx]
|
|
531
|
+
|
|
532
|
+
def _load(self, idx: int) -> np.ndarray:
|
|
533
|
+
# No state is shared between accesses, so that pages can be read from several threads at once (e.g. the
|
|
534
|
+
# page images of predictions while the predictor still iterates over the document in the background)
|
|
535
|
+
source_idx, page_idx = self.locate(idx)
|
|
536
|
+
return self.sources[source_idx][page_idx]
|
|
537
|
+
|
|
538
|
+
def _page_ref(self, idx: int) -> "_SourcePage | None":
|
|
539
|
+
# The reference of the page in its own input, not in the whole concatenation. The pages of an in-memory list
|
|
540
|
+
# are kept as is: they are in memory anyway
|
|
541
|
+
source_idx, page_idx = self.locate(idx)
|
|
542
|
+
source = self.sources[source_idx]
|
|
543
|
+
return source._page_ref(page_idx) if isinstance(source, PageSource) else None
|
|
544
|
+
|
|
545
|
+
def _iter_indices(self, indices: Iterable[int], skip_errors: bool = False) -> Generator[Any, None, None]:
|
|
546
|
+
# Consecutive pages of the same input are read within one session of that input: a PDF is opened once for
|
|
547
|
+
# them and closed before moving on, so that at most one underlying document is open at a time
|
|
548
|
+
for source_idx, run in groupby(indices, key=lambda idx: bisect_right(self._offsets, idx) - 1):
|
|
549
|
+
source, offset = self.sources[source_idx], self._offsets[source_idx]
|
|
550
|
+
if isinstance(source, PageSource):
|
|
551
|
+
yield from source._iter_indices((idx - offset for idx in run), skip_errors=skip_errors)
|
|
552
|
+
else:
|
|
553
|
+
yield from (source[idx - offset] for idx in run)
|
|
554
|
+
|
|
555
|
+
def close(self) -> None:
|
|
556
|
+
for source in self.sources:
|
|
557
|
+
if isinstance(source, PageSource):
|
|
558
|
+
source.close()
|
|
559
|
+
|
|
560
|
+
def __repr__(self) -> str:
|
|
561
|
+
return f"{self.__class__.__name__}(num_sources={len(self.sources)}, num_pages={len(self)})"
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
class _PageView(PageSource):
|
|
565
|
+
"""Lazy view on a subset of the pages of another source (returned when slicing a source)
|
|
566
|
+
|
|
567
|
+
A view holds no resources of its own: iterating over it holds those of its source for the pass only, and
|
|
568
|
+
closing it leaves its source (and the other views on it) untouched.
|
|
569
|
+
"""
|
|
570
|
+
|
|
571
|
+
def __init__(self, source: PageSource, indices: Sequence[int]) -> None:
|
|
572
|
+
self.source = source
|
|
573
|
+
self.indices = indices
|
|
574
|
+
|
|
575
|
+
def __len__(self) -> int:
|
|
576
|
+
return len(self.indices)
|
|
577
|
+
|
|
578
|
+
def _load(self, idx: int) -> np.ndarray:
|
|
579
|
+
return self.source[self.indices[idx]]
|
|
580
|
+
|
|
581
|
+
def _page_ref(self, idx: int) -> "_SourcePage | None":
|
|
582
|
+
# The reference of the page in the viewed source
|
|
583
|
+
return self.source._page_ref(self.indices[idx])
|
|
584
|
+
|
|
585
|
+
def _session(self) -> AbstractContextManager[Any]:
|
|
586
|
+
# `with view:` keeps the resources of the source for the block
|
|
587
|
+
return self.source._session()
|
|
588
|
+
|
|
589
|
+
def _iter_indices(self, indices: Iterable[int], skip_errors: bool = False) -> Generator[Any, None, None]:
|
|
590
|
+
return self.source._iter_indices((self.indices[idx] for idx in indices), skip_errors=skip_errors)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _list_files(folder: Path, extensions: Sequence[str]) -> list[Path]:
|
|
594
|
+
"""List the files of a directory (non-recursively) with one of the given extensions, sorted by name"""
|
|
595
|
+
return sorted(
|
|
596
|
+
(path for path in folder.iterdir() if path.is_file() and path.suffix.lower() in extensions),
|
|
597
|
+
key=lambda path: path.name,
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _is_pdf(file: AbstractFile) -> bool:
|
|
602
|
+
"""Whether a file (path or bytes) is a PDF: from its extension, or from its header for a path without a PDF or
|
|
603
|
+
an image extension (e.g. `scan` or `scan.bin`)"""
|
|
604
|
+
if isinstance(file, bytes):
|
|
605
|
+
return _has_pdf_header(file)
|
|
606
|
+
path = Path(file)
|
|
607
|
+
suffix = path.suffix.lower()
|
|
608
|
+
if suffix == ".pdf":
|
|
609
|
+
return True
|
|
610
|
+
if suffix in IMAGE_EXTENSIONS:
|
|
611
|
+
# No extra read for the files named as images, i.e. almost all of them
|
|
612
|
+
return False
|
|
613
|
+
try:
|
|
614
|
+
with open(path, "rb") as f:
|
|
615
|
+
return _has_pdf_header(f.read(1024))
|
|
616
|
+
except OSError:
|
|
617
|
+
# e.g. a missing file: reported as such by the image reader
|
|
618
|
+
return False
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _has_pdf_header(content: bytes) -> bool:
|
|
622
|
+
# Only look at the beginning of the content: stripping a whole document would copy it
|
|
623
|
+
return content[:1024].lstrip()[:5] == b"%PDF-"
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
class _SourcePage:
|
|
627
|
+
"""Picklable reference to a page of a source, decoded on demand (used to keep predictions lightweight)"""
|
|
628
|
+
|
|
629
|
+
__slots__ = ("source", "idx")
|
|
630
|
+
|
|
631
|
+
def __init__(self, source: PageSource, idx: int) -> None:
|
|
632
|
+
self.source = source
|
|
633
|
+
self.idx = idx
|
|
634
|
+
|
|
635
|
+
def __call__(self) -> np.ndarray:
|
|
636
|
+
return self.source[self.idx]
|