Repository navigation
PI: Parse simple content stream tokens with one regular expression - #4501
Draft
MartinThoma wants to merge 1 commit into
Draft
MartinThoma wants to merge 1 commit into
MartinThoma wants to merge 1 commit into
Conversation
Text extraction of documents with large content streams spends most of
its time tokenizing them. Parsing stays O(n), n = bytes of the content
stream, but the cost per token drops: extracting the text of the
documents of py-pdf/benchmarks gets up to 2x faster.
## Problem
ContentStream._parse_content_stream() read every token through the
generic object parser, byte by byte from a BytesIO:
read_non_whitespace() to find the next token and seek back,
read_object() to dispatch on its first byte, peeking 20 bytes for
numbers and seeking back again, and read_until_regex() reading
operators in chunks. For 2201.00214.pdf, with 19.3 MB of page content,
1.4 million operators and 2.5 million operands, this meant 14.5 million
BytesIO.read() calls, 10.5 million BytesIO.seek() calls and 2.6 million
read_object() calls.
## Solution
Each token is first matched against one regular expression at the
current position of the stream data, which skips the whitespace and
reads a plain number, name or operator in one call. Tokens it does not
match are read by the previous code. As only valid numbers are
matched, they are created with float.__new__() and int.__new__()
directly, skipping the error handling of FloatObject() and
NumberObject(): 0.24 µs instead of 0.52 µs per number.
For 2201.00214.pdf, 3,909,504 of the 3.9 million tokens match; the
other 2,292 are strings, arrays and the like. 0.34 million read(),
0.21 million seek() and 84,000 read_object() calls are left. Reading
the stream data into one bytes object does not copy it, as
BytesIO.read() returns the bytes the BytesIO was created from.
## Benchmark
PdfReader() and extract_text() for every page, CPU time, best of 3
runs, CPython 3.13.3, Intel i7-6700HQ; "Content" is the decoded page
content:
| PDF | Pages | Content | main | this change | Speedup |
|------------------|------:|--------:|--------:|------------:|--------:|
| 2201.00214.pdf | 22 | 19.3 MB | 21.51 s | 10.94 s | 1.97x |
| 2201.00151.pdf | 12 | 6.1 MB | 6.14 s | 3.55 s | 1.73x |
| GeoTopo-book.pdf | 117 | 3.6 MB | 6.49 s | 4.29 s | 1.51x |
| 1707.09725.pdf | 134 | 1.2 MB | 3.61 s | 3.12 s | 1.16x |
Created via:
```python
import sys
import time
from pypdf import PdfReader
for path in sys.argv[1:]:
best = float("inf")
for _ in range(3):
start = time.process_time()
reader = PdfReader(path)
for page in reader.pages:
page.extract_text()
best = min(best, time.process_time() - start)
print(f"{path}\t{len(reader.pages)}\t{best:.2f}")
```
## Behavior
What stays the same:
* The operations, with the exact types and values of the operands, the
warnings and the exceptions. Each alternative of the regular
expression only matches tokens that the generic parsing reads the
same way, and leaves everything else to it: strings, arrays,
dictionaries, comments, inline images, names with # escapes or
non-ASCII bytes, numbers like "1,5" or "1.2.3" or with more than 18
digits, integers followed by what looks like an indirect reference,
and overlong operators and names.
* The limits: the parsing budget is decremented for every token as
before.
This was checked on the 445 PDFs the tests use (on main 9dec168: the
operations of all 13,070 pages, the extracted text, the warnings and
the exceptions), on 30,000 random token sequences, and by the new
test, which parses 16 snippets with tricky tokens with and without the
regular expression.
What changed:
* Nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #4501 +/- ##
=======================================
Coverage 99.40% 99.40%
=======================================
Files 59 59
Lines 12512 12531 +19
Branches 2391 2395 +4
=======================================
+ Hits 12437 12456 +19
Misses 27 27
Partials 48 48 ☔ 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.
Text extraction of documents with large content streams spends most of its time tokenizing them. Parsing stays O(n), n = bytes of the content stream, but the cost per token drops: extracting the text of the documents of py-pdf/benchmarks gets up to 2x faster.
Problem
ContentStream._parse_content_stream() read every token through the generic object parser, byte by byte from a BytesIO: read_non_whitespace() to find the next token and seek back, read_object() to dispatch on its first byte, peeking 20 bytes for numbers and seeking back again, and read_until_regex() reading operators in chunks. For 2201.00214.pdf, with 19.3 MB of page content, 1.4 million operators and 2.5 million operands, this meant 14.5 million BytesIO.read() calls, 10.5 million BytesIO.seek() calls and 2.6 million read_object() calls.
Solution
Each token is first matched against one regular expression at the current position of the stream data, which skips the whitespace and reads a plain number, name or operator in one call. Tokens it does not match are read by the previous code. As only valid numbers are matched, they are created with float.new() and int.new() directly, skipping the error handling of FloatObject() and NumberObject(): 0.24 µs instead of 0.52 µs per number.
For 2201.00214.pdf, 3,909,504 of the 3.9 million tokens match; the other 2,292 are strings, arrays and the like. 0.34 million read(), 0.21 million seek() and 84,000 read_object() calls are left. Reading the stream data into one bytes object does not copy it, as BytesIO.read() returns the bytes the BytesIO was created from.
Benchmark
PdfReader() and extract_text() for every page, CPU time, best of 3 runs, CPython 3.13.3, Intel i7-6700HQ; "Content" is the decoded page content:
Created via:
Behavior
What stays the same:
This was checked on the 445 PDFs the tests use (on main 9dec168: the operations of all 13,070 pages, the extracted text, the warnings and the exceptions), on 30,000 random token sequences, and by the new test, which parses 16 snippets with tricky tokens with and without the regular expression.
What changed: