Repository navigation
Prototype: [io] Lazy page sources & chunked/streaming predictors for long documents and large image collections - #2186
Draft
felixdittrich92 wants to merge 2 commits into
Draft
felixdittrich92 wants to merge 2 commits into
felixdittrich92 wants to merge 2 commits into
Conversation
…nts and large image collections
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2186 +/- ##
==========================================
- Coverage 97.74% 97.71% -0.03%
==========================================
Files 170 171 +1
Lines 10932 11241 +309
==========================================
+ Hits 10685 10984 +299
- Misses 247 257 +10
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1240 (ref.: #1111)
Summary
Long PDFs (1000+ pages) and large collections of images can now be processed in one call, with a memory footprint that no longer grows with the number of pages, and without any custom batching logic on the user side.
Before this PR, every page was decoded into a list up front. The predictor then ran every pipeline stage on all pages at once: for example, all pages were preprocessed for detection in a single step. A 300-page A4 PDF was enough to get the process killed by the OOM killer on a 7 GB machine.
This PR adds:
doctr.io.PDFSource,ImageSource,ConcatSource): a class API over generators, as proposed in [IO] Refactor io module from functional API to class API with generators #1240. They behave like a read-only list of pages, but a page is only decoded when it is accessed.OCRPredictor/KIEPredictorprocess any input longer thanpage_chunk_size(default: 32) chunk by chunk. The next chunk is decoded in a background thread while the models run on the current one.predictor.stream(...): yields the predicted pages one by one, as soon as they are processed.page.pagedecodes it again on access.Everything is opt-in and backward compatible:
DocumentFile.from_*still returns lists by default, andmodel(list_of_pages)returns the sameDocumentas before.Usage
A long PDF in a single call
Stream the results with a constant memory footprint
Folders, mixed inputs and huge image collections
The sources behave like lists
Tuning the chunk size, and any iterable as input
CLI
doctr-cli --input_path 1200_pages.pdf scans/*.png --output result.md --page_chunk_size 16Inputs are now opened lazily, and a per-page progress bar is shown.
Implementation notes
doctr/io/sources.py(new)PageSource(Sequence[np.ndarray])supportslen, indexing, slicing (lazy views), iteration,+,iter_batches,close()and use as a context manager.PDFSourceImageSourceConcatSourcelocate().DocumentFilefrom_pdf,from_imagesandfrom_urlgainlazy=False, with typed overloads.from_filesfor mixed inputs.read_pdfnow usesPDFSourceinternally, so there is a single rendering code path.forwardbody moved to_predict_pages.forwarddispatches through_run: short lists take the existing single-pass path, everything else goes throughstream().stream()makespage_idxglobal, which also keeps the figure file names of the exports unique.page_chunk_sizeis a new_OCRPredictorargument, also exposed in the CLI.Page.page/KIEPage.pagestraighten_pages=True) are kept losslessly PNG-compressed.doctr.utils.multithreading: newchunked()andprefetch()helpers. Prefetching is disabled whenDOCTR_MULTIPROCESSING_DISABLEis set.Benchmark
2 CPUs / 7 GB RAM, A4 pages,
db_mobilenet_v3_large+crnn_mobilenet_v3_small:mainmodel(doc)model.stream(doc)Most of the remaining peak is the working set of one 32-page chunk, and it decreases with a lower
page_chunk_size.Behaviour changes to be aware of
page_chunk_size. Each call receives the location predictions of that chunk's pages. This is documented in the hooks section.model(...)now also accepts generators and other iterables of pages.Tests & docs
tests/common/test_io_sources.py:DocumentFilelazy readers andfrom_files;chunked/prefetch.tests/pytorch/test_models_zoo_pt.py:straighten_pages.--page_chunk_size, lazy loading).stream.ruff check,ruff format --checkandmypy doctr/pass.