pdftext 0.1.0__tar.gz
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.
- pdftext-0.1.0/LICENSE +200 -0
- pdftext-0.1.0/PKG-INFO +155 -0
- pdftext-0.1.0/README.md +132 -0
- pdftext-0.1.0/extract_text.py +31 -0
- pdftext-0.1.0/models/dt.joblib +0 -0
- pdftext-0.1.0/pdftext/extraction.py +59 -0
- pdftext-0.1.0/pdftext/inference.py +152 -0
- pdftext-0.1.0/pdftext/model.py +7 -0
- pdftext-0.1.0/pdftext/pdf/chars.py +79 -0
- pdftext-0.1.0/pdftext/pdf/utils.py +97 -0
- pdftext-0.1.0/pdftext/postprocessing.py +72 -0
- pdftext-0.1.0/pdftext/settings.py +19 -0
- pdftext-0.1.0/pyproject.toml +38 -0
pdftext-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
Version 2.0, January 2004
|
|
2
|
+
http://www.apache.org/licenses/
|
|
3
|
+
|
|
4
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
5
|
+
|
|
6
|
+
1. Definitions.
|
|
7
|
+
|
|
8
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
9
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
12
|
+
the copyright owner that is granting the License.
|
|
13
|
+
|
|
14
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
15
|
+
other entities that control, are controlled by, or are under common
|
|
16
|
+
control with that entity. For the purposes of this definition,
|
|
17
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
18
|
+
direction or management of such entity, whether by contract or
|
|
19
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
20
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
21
|
+
|
|
22
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
23
|
+
exercising permissions granted by this License.
|
|
24
|
+
|
|
25
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
26
|
+
including but not limited to software source code, documentation
|
|
27
|
+
source, and configuration files.
|
|
28
|
+
|
|
29
|
+
"Object" form shall mean any form resulting from mechanical
|
|
30
|
+
transformation or translation of a Source form, including but
|
|
31
|
+
not limited to compiled object code, generated documentation,
|
|
32
|
+
and conversions to other media types.
|
|
33
|
+
|
|
34
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
35
|
+
Object form, made available under the License, as indicated by a
|
|
36
|
+
copyright notice that is included in or attached to the work
|
|
37
|
+
(an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean any work of authorship, including
|
|
48
|
+
the original version of the Work and any modifications or additions
|
|
49
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
50
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
51
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
52
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
53
|
+
means any form of electronic, verbal, or written communication sent
|
|
54
|
+
to the Licensor or its representatives, including but not limited to
|
|
55
|
+
communication on electronic mailing lists, source code control systems,
|
|
56
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
57
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
58
|
+
excluding communication that is conspicuously marked or otherwise
|
|
59
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
60
|
+
|
|
61
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
62
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
63
|
+
subsequently incorporated within the Work.
|
|
64
|
+
|
|
65
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
66
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
67
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
68
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
69
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
70
|
+
Work and such Derivative Works in Source or Object form.
|
|
71
|
+
|
|
72
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
73
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
74
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
75
|
+
(except as stated in this section) patent license to make, have made,
|
|
76
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
77
|
+
where such license applies only to those patent claims licensable
|
|
78
|
+
by such Contributor that are necessarily infringed by their
|
|
79
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
80
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
81
|
+
institute patent litigation against any entity (including a
|
|
82
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
83
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
84
|
+
or contributory patent infringement, then any patent licenses
|
|
85
|
+
granted to You under this License for that Work shall terminate
|
|
86
|
+
as of the date such litigation is filed.
|
|
87
|
+
|
|
88
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
89
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
90
|
+
modifications, and in Source or Object form, provided that You
|
|
91
|
+
meet the following conditions:
|
|
92
|
+
|
|
93
|
+
(a) You must give any other recipients of the Work or
|
|
94
|
+
Derivative Works a copy of this License; and
|
|
95
|
+
|
|
96
|
+
(b) You must cause any modified files to carry prominent notices
|
|
97
|
+
stating that You changed the files; and
|
|
98
|
+
|
|
99
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
100
|
+
that You distribute, all copyright, patent, trademark, and
|
|
101
|
+
attribution notices from the Source form of the Work,
|
|
102
|
+
excluding those notices that do not pertain to any part of
|
|
103
|
+
the Derivative Works; and
|
|
104
|
+
|
|
105
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
106
|
+
distribution, then any Derivative Works that You distribute must
|
|
107
|
+
include a readable copy of the attribution notices contained
|
|
108
|
+
within such NOTICE file, excluding those notices that do not
|
|
109
|
+
pertain to any part of the Derivative Works, in at least one
|
|
110
|
+
of the following places: within a NOTICE text file distributed
|
|
111
|
+
as part of the Derivative Works; within the Source form or
|
|
112
|
+
documentation, if provided along with the Derivative Works; or,
|
|
113
|
+
within a display generated by the Derivative Works, if and
|
|
114
|
+
wherever such third-party notices normally appear. The contents
|
|
115
|
+
of the NOTICE file are for informational purposes only and
|
|
116
|
+
do not modify the License. You may add Your own attribution
|
|
117
|
+
notices within Derivative Works that You distribute, alongside
|
|
118
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
119
|
+
that such additional attribution notices cannot be construed
|
|
120
|
+
as modifying the License.
|
|
121
|
+
|
|
122
|
+
You may add Your own copyright statement to Your modifications and
|
|
123
|
+
may provide additional or different license terms and conditions
|
|
124
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
125
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
126
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
127
|
+
the conditions stated in this License.
|
|
128
|
+
|
|
129
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
130
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
131
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
132
|
+
this License, without any additional terms or conditions.
|
|
133
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
134
|
+
the terms of any separate license agreement you may have executed
|
|
135
|
+
with Licensor regarding such Contributions.
|
|
136
|
+
|
|
137
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
138
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
139
|
+
except as required for reasonable and customary use in describing the
|
|
140
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
141
|
+
|
|
142
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
143
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
144
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
145
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
146
|
+
implied, including, without limitation, any warranties or conditions
|
|
147
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
148
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
149
|
+
appropriateness of using or redistributing the Work and assume any
|
|
150
|
+
risks associated with Your exercise of permissions under this License.
|
|
151
|
+
|
|
152
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
153
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
154
|
+
unless required by applicable law (such as deliberate and grossly
|
|
155
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
156
|
+
liable to You for damages, including any direct, indirect, special,
|
|
157
|
+
incidental, or consequential damages of any character arising as a
|
|
158
|
+
result of this License or out of the use or inability to use the
|
|
159
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
160
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
161
|
+
other commercial damages or losses), even if such Contributor
|
|
162
|
+
has been advised of the possibility of such damages.
|
|
163
|
+
|
|
164
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
165
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
166
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
167
|
+
or other liability obligations and/or rights consistent with this
|
|
168
|
+
License. However, in accepting such obligations, You may act only
|
|
169
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
170
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
171
|
+
defend, and hold each Contributor harmless for any liability
|
|
172
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
173
|
+
of your accepting any such warranty or additional liability.
|
|
174
|
+
|
|
175
|
+
END OF TERMS AND CONDITIONS
|
|
176
|
+
|
|
177
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
178
|
+
|
|
179
|
+
To apply the Apache License to your work, attach the following
|
|
180
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
181
|
+
replaced with your own identifying information. (Don't include
|
|
182
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
183
|
+
comment syntax for the file format. We also recommend that a
|
|
184
|
+
file or class name and description of purpose be included on the
|
|
185
|
+
same "printed page" as the copyright notice for easier
|
|
186
|
+
identification within third-party archives.
|
|
187
|
+
|
|
188
|
+
Copyright 2024 Vikas Paruchuri
|
|
189
|
+
|
|
190
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
191
|
+
you may not use this file except in compliance with the License.
|
|
192
|
+
You may obtain a copy of the License at
|
|
193
|
+
|
|
194
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
195
|
+
|
|
196
|
+
Unless required by applicable law or agreed to in writing, software
|
|
197
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
198
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
199
|
+
See the License for the specific language governing permissions and
|
|
200
|
+
limitations under the License.
|
pdftext-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: pdftext
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Extract structured text from pdfs quickly
|
|
5
|
+
Home-page: https://github.com/VikParuchuri/pdftext
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Keywords: pdf,text,extraction
|
|
8
|
+
Author: Vik Paruchuri
|
|
9
|
+
Author-email: vik.paruchuri@gmail.com
|
|
10
|
+
Requires-Python: >=3.9, !=2.7.*, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.*, !=3.8.*
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Requires-Dist: pydantic (>=2.7.1,<3.0.0)
|
|
18
|
+
Requires-Dist: pydantic-settings (>=2.2.1,<3.0.0)
|
|
19
|
+
Requires-Dist: pypdfium2 (>=4.29.0,<5.0.0)
|
|
20
|
+
Requires-Dist: scikit-learn (>=1.4.2,<2.0.0)
|
|
21
|
+
Project-URL: Repository, https://github.com/VikParuchuri/pdftext
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# PDFText
|
|
25
|
+
|
|
26
|
+
Text extraction like [PyMuPDF]((https://github.com/pymupdf/PyMuPDF), but without the AGPL license. PDFText extracts plain text or structured blocks and lines. It's built on [pypdfium2](https://github.com/pypdfium2-team/pypdfium2), so it's [fast, accurate](#benchmarks), and Apache licensed.
|
|
27
|
+
|
|
28
|
+
# Installation
|
|
29
|
+
|
|
30
|
+
You'll need python 3.9+ first. Then run `pip install pdftext`.
|
|
31
|
+
|
|
32
|
+
# Usage
|
|
33
|
+
|
|
34
|
+
- Inspect the settings in `pdftext/settings.py`. You can override any settings with environment variables.
|
|
35
|
+
|
|
36
|
+
## Plain text
|
|
37
|
+
|
|
38
|
+
This command will write out a text file with the extracted plain text.
|
|
39
|
+
|
|
40
|
+
```shell
|
|
41
|
+
pdftext PDF_PATH --out_path output.txt
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
- `PDF_PATH` must be a single pdf file.
|
|
45
|
+
- `--out_path` path to the output txt file. If not specified, will write to stdout.
|
|
46
|
+
- `--sort` will attempt to sort in reading order if specified.
|
|
47
|
+
|
|
48
|
+
## JSON
|
|
49
|
+
|
|
50
|
+
This command outputs structured blocks and lines with font and other information.
|
|
51
|
+
|
|
52
|
+
```shell
|
|
53
|
+
pdftext PDF_PATH --out_path output.txt --output_type json
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
- `PDF_PATH` must be a single pdf file.
|
|
57
|
+
- `--out_path` path to the output txt file. If not specified, will write to stdout.
|
|
58
|
+
- `--output_type` specifies whether to write out plain text (default) or json
|
|
59
|
+
- `--sort` will attempt to sort in reading order if specified.
|
|
60
|
+
|
|
61
|
+
The output will be a json list, with each item in the list corresponding to a single page in the input pdf (in order). Each page will include the following keys:
|
|
62
|
+
|
|
63
|
+
- `bbox` - the page bbox, in `[x1, y1, x2, y2]` format
|
|
64
|
+
- `rotation` - how much the page is rotated, in degrees (`0`, `90`, `180`, or `270`)
|
|
65
|
+
- `page_idx` - the index of the page
|
|
66
|
+
- `blocks` - the blocks that make up the text in the pdf. Approximately equal to a paragraph.
|
|
67
|
+
- `bbox` - the block bbox, in `[x1, y1, x2, y2]` format
|
|
68
|
+
- `lines` - the lines inside the block
|
|
69
|
+
- `bbox` - the line bbox, in `[x1, y1, x2, y2]` format
|
|
70
|
+
- `chars` - the individual characters in the line
|
|
71
|
+
- `char` - the actual character, encoded in utf-8
|
|
72
|
+
- `rotation` - how much the character is rotated, in degrees
|
|
73
|
+
- `bbox` - the character bbox, in `[x1, y1, x2, y2]` format
|
|
74
|
+
- `char_idx` - the index of the character on the page (from `0` to number of characters, in original pdf order)
|
|
75
|
+
- `font` this is font info straight from the pdf, see [this pdfium code](https://pdfium.googlesource.com/pdfium/+/refs/heads/main/public/fpdf_text.h)
|
|
76
|
+
- `size` - the size of the font used for the character
|
|
77
|
+
- `weight` - font weight
|
|
78
|
+
- `name` - font name, may be None
|
|
79
|
+
- `flags` - font flags, in the format of the `PDF spec 1.7 Section 5.7.1 Font Descriptor Flags`
|
|
80
|
+
|
|
81
|
+
# Programmatic usage
|
|
82
|
+
|
|
83
|
+
Extract plain text:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from pdftext.extraction import plain_text_output
|
|
87
|
+
|
|
88
|
+
text = plain_text_output(PDF_PATH, sort=False)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Extract structured blocks and lines:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from pdftext.extraction import dictionary_output
|
|
95
|
+
|
|
96
|
+
text = dictionary_output(PDF_PATH)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
If you want more customization, check out the `pdftext.extraction._get_pages` function for a starting point to dig deeper. pdftext is a pretty thin wrapper around [pypdfium2](https://pypdfium2.readthedocs.io/en/stable/), so you might want to look at the documentation for that as well.
|
|
100
|
+
|
|
101
|
+
# Benchmarks
|
|
102
|
+
|
|
103
|
+
I benchmarked extraction speed and accuracy of [pymupdf](https://pymupdf.readthedocs.io/en/latest/), [pdfplumber](https://github.com/jsvine/pdfplumber), and pdftext. I chose pymupdf because it extracts blocks and lines. Pdfplumber extracts words and bboxes. I did not benchmark pypdf, even though it is a great library, because it doesn't provide individual words/lines and bbox information.
|
|
104
|
+
|
|
105
|
+
Here are the scores:
|
|
106
|
+
|
|
107
|
+
+------------+-------------------+-----------------------------------------+
|
|
108
|
+
| Library | Time (s per page) | Alignment Score (% accuracy vs pymupdf) |
|
|
109
|
+
+------------+-------------------+-----------------------------------------+
|
|
110
|
+
| pymupdf | 0.31 | -- |
|
|
111
|
+
| pdftext | 1.45 | 95.64 |
|
|
112
|
+
| pdfplumber | 2.97 | 89.88 |
|
|
113
|
+
+------------+-------------------+-----------------------------------------+
|
|
114
|
+
|
|
115
|
+
pdftext is approximately 2x slower than using pypdfium2 alone (if you were to extract all the same information).
|
|
116
|
+
|
|
117
|
+
There are additional benchmarks for pypdfium2 and other tools [here](https://github.com/py-pdf/benchmarks).
|
|
118
|
+
|
|
119
|
+
## Methodology
|
|
120
|
+
|
|
121
|
+
I used a benchmark set of 200 pdfs extracted from [common crawl](https://huggingface.co/datasets/pixparse/pdfa-eng-wds), then processed by a team at HuggingFace.
|
|
122
|
+
|
|
123
|
+
For each library, I used a detailed extraction method, to pull out font information, as well as just the words. This ensured we were comparing similar performance numbers.
|
|
124
|
+
|
|
125
|
+
For the alignment score, I extracted the text, then used the rapidfuzz library to find the alignment percentage. I used the text extracted by pymupdf as the pseudo-ground truth.
|
|
126
|
+
|
|
127
|
+
## Running benchmarks
|
|
128
|
+
|
|
129
|
+
You can run the benchmarks yourself. To do so, you have to first install pdftext manually. The install assumes you have poetry and Python 3.9+ installed.
|
|
130
|
+
|
|
131
|
+
```shell
|
|
132
|
+
git clone https://github.com/VikParuchuri/pdftext.git
|
|
133
|
+
cd pdftext
|
|
134
|
+
poetry install
|
|
135
|
+
python benchmark.py # Will download the benchmark pdfs automatically
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The benchmark script has a few options:
|
|
139
|
+
|
|
140
|
+
- `--max` this controls the maximum number of pdfs to benchmark
|
|
141
|
+
- `--result_path` a folder to save the results. A file called `results.json` will be created in the folder.
|
|
142
|
+
|
|
143
|
+
# How it works
|
|
144
|
+
|
|
145
|
+
PDFText is a very light wrapper around pypdfium2. It first uses pypdfium2 to extract characters in order, along with font and other information. Then it uses a simple decision tree algorithm to group characters into lines and blocks. It then done some simple postprocessing to clean up the text.
|
|
146
|
+
|
|
147
|
+
# Credits
|
|
148
|
+
|
|
149
|
+
This is built on some amazing open source work, including:
|
|
150
|
+
|
|
151
|
+
- [pypdfium2](https://github.com/pypdfium2-team/pypdfium2)
|
|
152
|
+
- [scikit-learn](https://scikit-learn.org/stable/index.html)
|
|
153
|
+
- [pypdf2](https://github.com/py-pdf/benchmarks) for very thorough and fair benchmarks
|
|
154
|
+
|
|
155
|
+
Thank you to the [pymupdf](https://github.com/pymupdf/PyMuPDF) devs for creating such a great library - I just wish it had a simpler license!
|
pdftext-0.1.0/README.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# PDFText
|
|
2
|
+
|
|
3
|
+
Text extraction like [PyMuPDF]((https://github.com/pymupdf/PyMuPDF), but without the AGPL license. PDFText extracts plain text or structured blocks and lines. It's built on [pypdfium2](https://github.com/pypdfium2-team/pypdfium2), so it's [fast, accurate](#benchmarks), and Apache licensed.
|
|
4
|
+
|
|
5
|
+
# Installation
|
|
6
|
+
|
|
7
|
+
You'll need python 3.9+ first. Then run `pip install pdftext`.
|
|
8
|
+
|
|
9
|
+
# Usage
|
|
10
|
+
|
|
11
|
+
- Inspect the settings in `pdftext/settings.py`. You can override any settings with environment variables.
|
|
12
|
+
|
|
13
|
+
## Plain text
|
|
14
|
+
|
|
15
|
+
This command will write out a text file with the extracted plain text.
|
|
16
|
+
|
|
17
|
+
```shell
|
|
18
|
+
pdftext PDF_PATH --out_path output.txt
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- `PDF_PATH` must be a single pdf file.
|
|
22
|
+
- `--out_path` path to the output txt file. If not specified, will write to stdout.
|
|
23
|
+
- `--sort` will attempt to sort in reading order if specified.
|
|
24
|
+
|
|
25
|
+
## JSON
|
|
26
|
+
|
|
27
|
+
This command outputs structured blocks and lines with font and other information.
|
|
28
|
+
|
|
29
|
+
```shell
|
|
30
|
+
pdftext PDF_PATH --out_path output.txt --output_type json
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- `PDF_PATH` must be a single pdf file.
|
|
34
|
+
- `--out_path` path to the output txt file. If not specified, will write to stdout.
|
|
35
|
+
- `--output_type` specifies whether to write out plain text (default) or json
|
|
36
|
+
- `--sort` will attempt to sort in reading order if specified.
|
|
37
|
+
|
|
38
|
+
The output will be a json list, with each item in the list corresponding to a single page in the input pdf (in order). Each page will include the following keys:
|
|
39
|
+
|
|
40
|
+
- `bbox` - the page bbox, in `[x1, y1, x2, y2]` format
|
|
41
|
+
- `rotation` - how much the page is rotated, in degrees (`0`, `90`, `180`, or `270`)
|
|
42
|
+
- `page_idx` - the index of the page
|
|
43
|
+
- `blocks` - the blocks that make up the text in the pdf. Approximately equal to a paragraph.
|
|
44
|
+
- `bbox` - the block bbox, in `[x1, y1, x2, y2]` format
|
|
45
|
+
- `lines` - the lines inside the block
|
|
46
|
+
- `bbox` - the line bbox, in `[x1, y1, x2, y2]` format
|
|
47
|
+
- `chars` - the individual characters in the line
|
|
48
|
+
- `char` - the actual character, encoded in utf-8
|
|
49
|
+
- `rotation` - how much the character is rotated, in degrees
|
|
50
|
+
- `bbox` - the character bbox, in `[x1, y1, x2, y2]` format
|
|
51
|
+
- `char_idx` - the index of the character on the page (from `0` to number of characters, in original pdf order)
|
|
52
|
+
- `font` this is font info straight from the pdf, see [this pdfium code](https://pdfium.googlesource.com/pdfium/+/refs/heads/main/public/fpdf_text.h)
|
|
53
|
+
- `size` - the size of the font used for the character
|
|
54
|
+
- `weight` - font weight
|
|
55
|
+
- `name` - font name, may be None
|
|
56
|
+
- `flags` - font flags, in the format of the `PDF spec 1.7 Section 5.7.1 Font Descriptor Flags`
|
|
57
|
+
|
|
58
|
+
# Programmatic usage
|
|
59
|
+
|
|
60
|
+
Extract plain text:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from pdftext.extraction import plain_text_output
|
|
64
|
+
|
|
65
|
+
text = plain_text_output(PDF_PATH, sort=False)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Extract structured blocks and lines:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from pdftext.extraction import dictionary_output
|
|
72
|
+
|
|
73
|
+
text = dictionary_output(PDF_PATH)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
If you want more customization, check out the `pdftext.extraction._get_pages` function for a starting point to dig deeper. pdftext is a pretty thin wrapper around [pypdfium2](https://pypdfium2.readthedocs.io/en/stable/), so you might want to look at the documentation for that as well.
|
|
77
|
+
|
|
78
|
+
# Benchmarks
|
|
79
|
+
|
|
80
|
+
I benchmarked extraction speed and accuracy of [pymupdf](https://pymupdf.readthedocs.io/en/latest/), [pdfplumber](https://github.com/jsvine/pdfplumber), and pdftext. I chose pymupdf because it extracts blocks and lines. Pdfplumber extracts words and bboxes. I did not benchmark pypdf, even though it is a great library, because it doesn't provide individual words/lines and bbox information.
|
|
81
|
+
|
|
82
|
+
Here are the scores:
|
|
83
|
+
|
|
84
|
+
+------------+-------------------+-----------------------------------------+
|
|
85
|
+
| Library | Time (s per page) | Alignment Score (% accuracy vs pymupdf) |
|
|
86
|
+
+------------+-------------------+-----------------------------------------+
|
|
87
|
+
| pymupdf | 0.31 | -- |
|
|
88
|
+
| pdftext | 1.45 | 95.64 |
|
|
89
|
+
| pdfplumber | 2.97 | 89.88 |
|
|
90
|
+
+------------+-------------------+-----------------------------------------+
|
|
91
|
+
|
|
92
|
+
pdftext is approximately 2x slower than using pypdfium2 alone (if you were to extract all the same information).
|
|
93
|
+
|
|
94
|
+
There are additional benchmarks for pypdfium2 and other tools [here](https://github.com/py-pdf/benchmarks).
|
|
95
|
+
|
|
96
|
+
## Methodology
|
|
97
|
+
|
|
98
|
+
I used a benchmark set of 200 pdfs extracted from [common crawl](https://huggingface.co/datasets/pixparse/pdfa-eng-wds), then processed by a team at HuggingFace.
|
|
99
|
+
|
|
100
|
+
For each library, I used a detailed extraction method, to pull out font information, as well as just the words. This ensured we were comparing similar performance numbers.
|
|
101
|
+
|
|
102
|
+
For the alignment score, I extracted the text, then used the rapidfuzz library to find the alignment percentage. I used the text extracted by pymupdf as the pseudo-ground truth.
|
|
103
|
+
|
|
104
|
+
## Running benchmarks
|
|
105
|
+
|
|
106
|
+
You can run the benchmarks yourself. To do so, you have to first install pdftext manually. The install assumes you have poetry and Python 3.9+ installed.
|
|
107
|
+
|
|
108
|
+
```shell
|
|
109
|
+
git clone https://github.com/VikParuchuri/pdftext.git
|
|
110
|
+
cd pdftext
|
|
111
|
+
poetry install
|
|
112
|
+
python benchmark.py # Will download the benchmark pdfs automatically
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The benchmark script has a few options:
|
|
116
|
+
|
|
117
|
+
- `--max` this controls the maximum number of pdfs to benchmark
|
|
118
|
+
- `--result_path` a folder to save the results. A file called `results.json` will be created in the folder.
|
|
119
|
+
|
|
120
|
+
# How it works
|
|
121
|
+
|
|
122
|
+
PDFText is a very light wrapper around pypdfium2. It first uses pypdfium2 to extract characters in order, along with font and other information. Then it uses a simple decision tree algorithm to group characters into lines and blocks. It then done some simple postprocessing to clean up the text.
|
|
123
|
+
|
|
124
|
+
# Credits
|
|
125
|
+
|
|
126
|
+
This is built on some amazing open source work, including:
|
|
127
|
+
|
|
128
|
+
- [pypdfium2](https://github.com/pypdfium2-team/pypdfium2)
|
|
129
|
+
- [scikit-learn](https://scikit-learn.org/stable/index.html)
|
|
130
|
+
- [pypdf2](https://github.com/py-pdf/benchmarks) for very thorough and fair benchmarks
|
|
131
|
+
|
|
132
|
+
Thank you to the [pymupdf](https://github.com/pymupdf/PyMuPDF) devs for creating such a great library - I just wish it had a simpler license!
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
from pdftext.extraction import plain_text_output, dictionary_output
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main():
|
|
8
|
+
parser = argparse.ArgumentParser(description="Extract plain text from PDF. Not guaranteed to be in order.")
|
|
9
|
+
parser.add_argument("pdf_path", type=str, help="Path to the PDF file")
|
|
10
|
+
parser.add_argument("--out_path", type=str, help="Path to the output text file, defaults to stdout", default=None)
|
|
11
|
+
parser.add_argument("--output_type", type=str, help="Type of output to generate", default="plain_text")
|
|
12
|
+
parser.add_argument("--sort", action="store_true", help="Attempt to sort the text by reading order", default=False)
|
|
13
|
+
args = parser.parse_args()
|
|
14
|
+
|
|
15
|
+
assert args.output_type in ["plain_text", "json"], "Invalid output type, must be 'plain_text' or 'json'"
|
|
16
|
+
|
|
17
|
+
if args.output_type == "plain_text":
|
|
18
|
+
text = plain_text_output(args.pdf_path, sort=args.sort)
|
|
19
|
+
elif args.output_type == "json":
|
|
20
|
+
text = dictionary_output(args.pdf_path, sort=args.sort)
|
|
21
|
+
text = json.dumps(text)
|
|
22
|
+
|
|
23
|
+
if args.out_path is None:
|
|
24
|
+
print(text)
|
|
25
|
+
else:
|
|
26
|
+
with open(args.out_path, "w+") as f:
|
|
27
|
+
f.write(text)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
if __name__ == "__main__":
|
|
31
|
+
main()
|
|
Binary file
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
|
|
3
|
+
from pdftext.inference import inference
|
|
4
|
+
from pdftext.model import get_model
|
|
5
|
+
from pdftext.pdf.chars import get_pdfium_chars
|
|
6
|
+
from pdftext.pdf.utils import unnormalize_bbox
|
|
7
|
+
from pdftext.postprocessing import merge_text, sort_blocks, postprocess_text
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _get_pages(pdf_path, model=None):
|
|
11
|
+
if model is None:
|
|
12
|
+
model = get_model()
|
|
13
|
+
text_chars = get_pdfium_chars(pdf_path)
|
|
14
|
+
pages = inference(text_chars, model)
|
|
15
|
+
return pages
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def plain_text_output(pdf_path, sort=False, model=None) -> str:
|
|
19
|
+
text = paginated_plain_text_output(pdf_path, sort=sort, model=model)
|
|
20
|
+
return "\n".join(text)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def paginated_plain_text_output(pdf_path, sort=False, model=None) -> List[str]:
|
|
24
|
+
pages = _get_pages(pdf_path, model)
|
|
25
|
+
text = []
|
|
26
|
+
for page in pages:
|
|
27
|
+
text.append(merge_text(page, sort=sort).strip())
|
|
28
|
+
return text
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def dictionary_output(pdf_path, sort=False, model=None):
|
|
32
|
+
pages = _get_pages(pdf_path, model)
|
|
33
|
+
for page in pages:
|
|
34
|
+
for block in page["blocks"]:
|
|
35
|
+
bad_keys = [key for key in block.keys() if key not in ["lines", "bbox"]]
|
|
36
|
+
for key in bad_keys:
|
|
37
|
+
del block[key]
|
|
38
|
+
for line in block["lines"]:
|
|
39
|
+
line_box = None
|
|
40
|
+
bad_keys = [key for key in line.keys() if key not in ["chars", "bbox"]]
|
|
41
|
+
for key in bad_keys:
|
|
42
|
+
del line[key]
|
|
43
|
+
for char in line["chars"]:
|
|
44
|
+
char["bbox"] = unnormalize_bbox(char["bbox"], page["bbox"])
|
|
45
|
+
char["char"] = postprocess_text(char["char"])
|
|
46
|
+
if line_box is None:
|
|
47
|
+
line_box = char["bbox"]
|
|
48
|
+
else:
|
|
49
|
+
line_box = [
|
|
50
|
+
min(line_box[0], char["bbox"][0]),
|
|
51
|
+
min(line_box[1], char["bbox"][1]),
|
|
52
|
+
max(line_box[2], char["bbox"][2]),
|
|
53
|
+
max(line_box[3], char["bbox"][3]),
|
|
54
|
+
]
|
|
55
|
+
line["bbox"] = line_box
|
|
56
|
+
block["bbox"] = unnormalize_bbox(block["bbox"], page["bbox"])
|
|
57
|
+
if sort:
|
|
58
|
+
page["blocks"] = sort_blocks(page["blocks"])
|
|
59
|
+
return pages
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from itertools import chain
|
|
2
|
+
|
|
3
|
+
from pdftext.pdf.utils import LINE_BREAKS, TABS, SPACES
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def update_current(current, new_char):
|
|
7
|
+
bbox = new_char["bbox"]
|
|
8
|
+
if "bbox" not in current:
|
|
9
|
+
current_bbox = bbox
|
|
10
|
+
current["bbox"] = current_bbox
|
|
11
|
+
else:
|
|
12
|
+
current_bbox = current["bbox"]
|
|
13
|
+
current_bbox[0] = min(bbox[0], current_bbox[0])
|
|
14
|
+
current_bbox[1] = min(bbox[1], current_bbox[1])
|
|
15
|
+
current_bbox[2] = max(bbox[2], current_bbox[2])
|
|
16
|
+
current_bbox[3] = max(bbox[3], current_bbox[3])
|
|
17
|
+
current["center_x"] = (current_bbox[0] + current_bbox[2]) / 2
|
|
18
|
+
current["center_y"] = (current_bbox[1] + current_bbox[3]) / 2
|
|
19
|
+
return current
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def create_training_row(char_info, prev_char, currblock):
|
|
23
|
+
char = char_info["char"]
|
|
24
|
+
char_center_x = (char_info["bbox"][2] + char_info["bbox"][0]) / 2
|
|
25
|
+
char_center_y = (char_info["bbox"][3] + char_info["bbox"][1]) / 2
|
|
26
|
+
x_gap = char_info["bbox"][0] - prev_char["bbox"][2]
|
|
27
|
+
y_gap = char_info["bbox"][1] - prev_char["bbox"][3]
|
|
28
|
+
font_match = all(
|
|
29
|
+
[char_info["font"][key] == prev_char["font"][key] for key in ["name", "size", "weight", "flags"]] +
|
|
30
|
+
[char_info["rotation"] == prev_char["rotation"]]
|
|
31
|
+
)
|
|
32
|
+
is_space = any([
|
|
33
|
+
char in SPACES,
|
|
34
|
+
char in TABS,
|
|
35
|
+
])
|
|
36
|
+
|
|
37
|
+
training_row = {
|
|
38
|
+
"is_newline": char in LINE_BREAKS,
|
|
39
|
+
"is_space": is_space,
|
|
40
|
+
"x_gap": x_gap,
|
|
41
|
+
"y_gap": y_gap,
|
|
42
|
+
"font_match": font_match,
|
|
43
|
+
"x_outer_gap": char_info["bbox"][2] - prev_char["bbox"][0],
|
|
44
|
+
"y_outer_gap": char_info["bbox"][3] - prev_char["bbox"][1],
|
|
45
|
+
"block_x_center_gap": char_center_x - currblock["center_x"],
|
|
46
|
+
"block_y_center_gap": char_center_y - currblock["center_y"],
|
|
47
|
+
"block_x_gap": char_info["bbox"][0] - currblock["bbox"][2],
|
|
48
|
+
"block_y_gap": char_info["bbox"][1] - currblock["bbox"][3]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return training_row
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def update_span(line, span):
|
|
55
|
+
line["spans"].append(span)
|
|
56
|
+
span = {"chars": []}
|
|
57
|
+
return span
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def update_line(block, line):
|
|
61
|
+
line["chars"] = list(chain.from_iterable(s["chars"] for s in line["spans"]))
|
|
62
|
+
del line["spans"]
|
|
63
|
+
block["lines"].append(line)
|
|
64
|
+
line = {"spans": []}
|
|
65
|
+
return line
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def update_block(blocks, block):
|
|
69
|
+
blocks["blocks"].append(block)
|
|
70
|
+
block = {"lines": []}
|
|
71
|
+
return block
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def infer_single_page(text_chars):
|
|
75
|
+
prev_char = None
|
|
76
|
+
|
|
77
|
+
blocks = {"blocks": []}
|
|
78
|
+
block = {"lines": []}
|
|
79
|
+
line = {"spans": []}
|
|
80
|
+
span = {"chars": []}
|
|
81
|
+
for i, char_info in enumerate(text_chars["chars"]):
|
|
82
|
+
if prev_char:
|
|
83
|
+
training_row = create_training_row(char_info, prev_char, block)
|
|
84
|
+
training_row = [v for _, v in sorted(training_row.items())]
|
|
85
|
+
|
|
86
|
+
prediction = yield training_row
|
|
87
|
+
if prediction == 0:
|
|
88
|
+
pass
|
|
89
|
+
elif prediction == 1:
|
|
90
|
+
span = update_span(line, span)
|
|
91
|
+
elif prediction == 2:
|
|
92
|
+
span = update_span(line, span)
|
|
93
|
+
line = update_line(block, line)
|
|
94
|
+
else:
|
|
95
|
+
span = update_span(line, span)
|
|
96
|
+
line = update_line(block, line)
|
|
97
|
+
block = update_block(blocks, block)
|
|
98
|
+
|
|
99
|
+
span["chars"].append(char_info)
|
|
100
|
+
block = update_current(block, char_info)
|
|
101
|
+
|
|
102
|
+
prev_char = char_info
|
|
103
|
+
if len(span["chars"]) > 0:
|
|
104
|
+
update_span(line, span)
|
|
105
|
+
if len(line["spans"]) > 0:
|
|
106
|
+
update_line(block, line)
|
|
107
|
+
if len(block["lines"]) > 0:
|
|
108
|
+
update_block(blocks, block)
|
|
109
|
+
|
|
110
|
+
blocks["page"] = text_chars["page"]
|
|
111
|
+
blocks["rotation"] = text_chars["rotation"]
|
|
112
|
+
blocks["bbox"] = text_chars["bbox"]
|
|
113
|
+
return blocks
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def inference(text_chars, model):
|
|
117
|
+
# Create generators and get first training row from each
|
|
118
|
+
generators = [infer_single_page(text_page) for text_page in text_chars]
|
|
119
|
+
next_prediction = {}
|
|
120
|
+
|
|
121
|
+
page_blocks = {}
|
|
122
|
+
while len(page_blocks) < len(generators):
|
|
123
|
+
training_data = {}
|
|
124
|
+
for page_idx, page_generator in enumerate(generators):
|
|
125
|
+
if page_idx in page_blocks:
|
|
126
|
+
continue
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
if page_idx not in next_prediction:
|
|
130
|
+
training_row = next(page_generator)
|
|
131
|
+
else:
|
|
132
|
+
training_row = page_generator.send(next_prediction[page_idx])
|
|
133
|
+
del next_prediction[page_idx]
|
|
134
|
+
training_data[page_idx] = training_row
|
|
135
|
+
except StopIteration as e:
|
|
136
|
+
blocks = e.value
|
|
137
|
+
page_blocks[page_idx] = blocks
|
|
138
|
+
|
|
139
|
+
if len(page_blocks) == len(generators):
|
|
140
|
+
break
|
|
141
|
+
|
|
142
|
+
training_list = sorted(training_data.items())
|
|
143
|
+
training_rows = [tl[1] for tl in training_list]
|
|
144
|
+
training_idxs = [tl[0] for tl in training_list]
|
|
145
|
+
|
|
146
|
+
predictions = model.predict(training_rows)
|
|
147
|
+
for pred, page_idx in zip(predictions, training_idxs):
|
|
148
|
+
next_prediction[page_idx] = pred
|
|
149
|
+
page_blocks = sorted(page_blocks.items())
|
|
150
|
+
page_blocks = [p[1] for p in page_blocks]
|
|
151
|
+
assert len(page_blocks) == len(text_chars)
|
|
152
|
+
return page_blocks
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import decimal
|
|
2
|
+
import math
|
|
3
|
+
from typing import Dict
|
|
4
|
+
|
|
5
|
+
import pypdfium2 as pdfium
|
|
6
|
+
import pypdfium2.raw as pdfium_c
|
|
7
|
+
|
|
8
|
+
from pdftext.pdf.utils import get_fontname, pdfium_page_bbox_to_device_bbox, page_bbox_to_device_bbox
|
|
9
|
+
from pdftext.settings import settings
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def update_previous_fonts(text_chars: Dict, i: int, fontname: str, fontflags: int, prev_fontname: str, text_page, fontname_sample_freq: int):
|
|
13
|
+
min_update = max(0, i - fontname_sample_freq + 1) # Minimum index to update
|
|
14
|
+
regather_font_info = fontname != prev_fontname
|
|
15
|
+
for j in range(min_update, i): # Goes from min_update to i - 1
|
|
16
|
+
if regather_font_info:
|
|
17
|
+
fontname, fontflags = get_fontname(text_page, j)
|
|
18
|
+
|
|
19
|
+
# If we hit the region with the previous fontname, we can bail out
|
|
20
|
+
if fontname == prev_fontname:
|
|
21
|
+
break
|
|
22
|
+
text_chars["chars"][j]["font"]["name"] = fontname
|
|
23
|
+
text_chars["chars"][j]["font"]["flags"] = fontflags
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_pdfium_chars(pdf_path, fontname_sample_freq=settings.FONTNAME_SAMPLE_FREQ):
|
|
27
|
+
pdf = pdfium.PdfDocument(pdf_path)
|
|
28
|
+
blocks = []
|
|
29
|
+
|
|
30
|
+
for page_idx in range(len(pdf)):
|
|
31
|
+
page = pdf.get_page(page_idx)
|
|
32
|
+
text_page = page.get_textpage()
|
|
33
|
+
|
|
34
|
+
bbox = page.get_bbox()
|
|
35
|
+
page_width = math.ceil(bbox[2] - bbox[0])
|
|
36
|
+
page_height = math.ceil(abs(bbox[1] - bbox[3]))
|
|
37
|
+
|
|
38
|
+
text_chars = {
|
|
39
|
+
"chars": [],
|
|
40
|
+
"page": page_idx,
|
|
41
|
+
"rotation": page.get_rotation(),
|
|
42
|
+
"bbox": pdfium_page_bbox_to_device_bbox(page, bbox, page_width, page_height)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
fontname = None
|
|
46
|
+
fontflags = None
|
|
47
|
+
total_chars = text_page.count_chars()
|
|
48
|
+
for i in range(total_chars):
|
|
49
|
+
char = pdfium_c.FPDFText_GetUnicode(text_page, i)
|
|
50
|
+
char = chr(char)
|
|
51
|
+
fontsize = round(pdfium_c.FPDFText_GetFontSize(text_page, i), 1)
|
|
52
|
+
fontweight = round(pdfium_c.FPDFText_GetFontWeight(text_page, i), 1)
|
|
53
|
+
if fontname is None or i % fontname_sample_freq == 0:
|
|
54
|
+
prev_fontname = fontname
|
|
55
|
+
fontname, fontflags = get_fontname(text_page, i)
|
|
56
|
+
update_previous_fonts(text_chars, i, fontname, fontflags, prev_fontname, text_page, fontname_sample_freq)
|
|
57
|
+
|
|
58
|
+
rotation = pdfium_c.FPDFText_GetCharAngle(text_page, i)
|
|
59
|
+
rotation = rotation * 180 / math.pi # convert from radians to degrees
|
|
60
|
+
coords = text_page.get_charbox(i, loose=True)
|
|
61
|
+
device_coords = page_bbox_to_device_bbox(page, coords, page_width, page_height, normalize=True)
|
|
62
|
+
|
|
63
|
+
char_info = {
|
|
64
|
+
"font": {
|
|
65
|
+
"size": fontsize,
|
|
66
|
+
"weight": fontweight,
|
|
67
|
+
"name": fontname,
|
|
68
|
+
"flags": fontflags
|
|
69
|
+
},
|
|
70
|
+
"rotation": rotation,
|
|
71
|
+
"char": char,
|
|
72
|
+
"bbox": device_coords,
|
|
73
|
+
"char_idx": i
|
|
74
|
+
}
|
|
75
|
+
text_chars["chars"].append(char_info)
|
|
76
|
+
|
|
77
|
+
text_chars["total_chars"] = total_chars
|
|
78
|
+
blocks.append(text_chars)
|
|
79
|
+
return blocks
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import pypdfium2.raw as pdfium_c
|
|
2
|
+
import ctypes
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from pdftext.settings import settings
|
|
6
|
+
|
|
7
|
+
LINE_BREAKS = ["\n", "\u000D", "\u000A", "\u000C"]
|
|
8
|
+
TABS = ["\t", "\u0009"]
|
|
9
|
+
SPACES = [" ", "\ufffe", "\uFEFF", "\xa0"]
|
|
10
|
+
HYPHEN = "-"
|
|
11
|
+
WHITESPACE_CHARS = ["\n", "\r", "\f", "\t", " "]
|
|
12
|
+
LIGATURES = {
|
|
13
|
+
"ff": "ff",
|
|
14
|
+
"ffi": "ffi",
|
|
15
|
+
"ffl": "ffl",
|
|
16
|
+
"fi": "fi",
|
|
17
|
+
"fl": "fl",
|
|
18
|
+
"st": "st",
|
|
19
|
+
"ſt": "st",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def char_count(textpage, *rect):
|
|
24
|
+
args = (textpage, *rect)
|
|
25
|
+
n_chars = pdfium_c.FPDFText_GetBoundedText(*args, None, 0)
|
|
26
|
+
if n_chars <= 0:
|
|
27
|
+
return 0
|
|
28
|
+
return n_chars
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def normalize_bbox(bbox, page_bound):
|
|
32
|
+
x1, y1, x2, y2 = bbox
|
|
33
|
+
x1 = x1 / page_bound[2]
|
|
34
|
+
y1 = y1 / page_bound[3]
|
|
35
|
+
x2 = x2 / page_bound[2]
|
|
36
|
+
y2 = y2 / page_bound[3]
|
|
37
|
+
return x1, y1, x2, y2
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def unnormalize_bbox(bbox, page_bound):
|
|
41
|
+
x1, y1, x2, y2 = bbox
|
|
42
|
+
x1 = round(x1 * page_bound[2], 1)
|
|
43
|
+
y1 = round(y1 * page_bound[3], 1)
|
|
44
|
+
x2 = round(x2 * page_bound[2], 1)
|
|
45
|
+
y2 = round(y2 * page_bound[3], 1)
|
|
46
|
+
return x1, y1, x2, y2
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def get_fontname(textpage, char_index):
|
|
50
|
+
n_bytes = settings.FONT_BUFFER_SIZE
|
|
51
|
+
buffer = ctypes.create_string_buffer(n_bytes)
|
|
52
|
+
# Re-interpret the type from char to unsigned short as required by the function
|
|
53
|
+
buffer_ptr = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ushort))
|
|
54
|
+
flag_buffer = ctypes.c_int()
|
|
55
|
+
flag_ptr = ctypes.pointer(flag_buffer)
|
|
56
|
+
font_info = pdfium_c.FPDFText_GetFontInfo(textpage, char_index, buffer_ptr, n_bytes, flag_ptr)
|
|
57
|
+
if font_info == 0:
|
|
58
|
+
return None, None
|
|
59
|
+
try:
|
|
60
|
+
decoded = buffer.value.decode("utf-8")
|
|
61
|
+
except Exception as e:
|
|
62
|
+
return None, None
|
|
63
|
+
return decoded, flag_buffer.value
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def page_to_device(page, x, y, page_width, page_height):
|
|
67
|
+
device_x = ctypes.c_int()
|
|
68
|
+
device_y = ctypes.c_int()
|
|
69
|
+
device_x_ptr = ctypes.pointer(device_x)
|
|
70
|
+
device_y_ptr = ctypes.pointer(device_y)
|
|
71
|
+
rotation = pdfium_c.FPDFPage_GetRotation(page)
|
|
72
|
+
width = math.ceil(page_width)
|
|
73
|
+
height = math.ceil(page_height)
|
|
74
|
+
pdfium_c.FPDF_PageToDevice(page, 0, 0, width, height, rotation, x, y, device_x_ptr, device_y_ptr)
|
|
75
|
+
x = device_x.value
|
|
76
|
+
y = device_y.value
|
|
77
|
+
return x, y
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def pdfium_page_bbox_to_device_bbox(page, bbox, page_width, page_height, normalize=False):
|
|
81
|
+
bbox_width = bbox[2] - bbox[0]
|
|
82
|
+
bbox_height = bbox[3] - bbox[1]
|
|
83
|
+
left_bottom = page_to_device(page, *bbox[:2], page_width, page_height)
|
|
84
|
+
|
|
85
|
+
dev_bbox = [left_bottom[0], left_bottom[1] - bbox_height, left_bottom[0] + bbox_width, left_bottom[1]] # Convert to ltrb
|
|
86
|
+
if normalize:
|
|
87
|
+
dev_bbox = [dev_bbox[0] / page_width, dev_bbox[1] / page_height, dev_bbox[2] / page_width, dev_bbox[3] / page_height]
|
|
88
|
+
return dev_bbox
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def page_bbox_to_device_bbox(page, bbox, page_width, page_height, normalize=False):
|
|
92
|
+
left, bottom, right, top = bbox
|
|
93
|
+
|
|
94
|
+
dev_bbox = [left, page_height-top, right, page_height-bottom]
|
|
95
|
+
if normalize:
|
|
96
|
+
dev_bbox = [dev_bbox[0] / page_width, dev_bbox[1] / page_height, dev_bbox[2] / page_width, dev_bbox[3] / page_height]
|
|
97
|
+
return dev_bbox
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
from typing import List, Dict
|
|
2
|
+
import unicodedata
|
|
3
|
+
|
|
4
|
+
from pdftext.pdf.utils import SPACES, LINE_BREAKS, TABS, WHITESPACE_CHARS, LIGATURES
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def postprocess_text(text: str) -> str:
|
|
8
|
+
text = replace_special_chars(text)
|
|
9
|
+
text = replace_control_chars(text)
|
|
10
|
+
text = replace_ligatures(text)
|
|
11
|
+
return text
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def replace_special_chars(text: str) -> str:
|
|
15
|
+
for item in SPACES:
|
|
16
|
+
text = text.replace(item, " ")
|
|
17
|
+
for item in LINE_BREAKS:
|
|
18
|
+
text = text.replace(item, "\n")
|
|
19
|
+
for item in TABS:
|
|
20
|
+
text = text.replace(item, "\t")
|
|
21
|
+
return text
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def replace_control_chars(text: str) -> str:
|
|
25
|
+
return "".join(char for char in text if unicodedata.category(char)[0] != "C" or char in WHITESPACE_CHARS)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def replace_ligatures(text: str) -> str:
|
|
29
|
+
for ligature, replacement in LIGATURES.items():
|
|
30
|
+
text = text.replace(ligature, replacement)
|
|
31
|
+
return text
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def sort_blocks(blocks: List, tolerance=1.25) -> List:
|
|
35
|
+
# Sort blocks into best guess reading order
|
|
36
|
+
vertical_groups = {}
|
|
37
|
+
for block in blocks:
|
|
38
|
+
bbox = block["bbox"]
|
|
39
|
+
group_key = round(bbox[1] / tolerance) * tolerance
|
|
40
|
+
if group_key not in vertical_groups:
|
|
41
|
+
vertical_groups[group_key] = []
|
|
42
|
+
vertical_groups[group_key].append(block)
|
|
43
|
+
|
|
44
|
+
# Sort each group horizontally and flatten the groups into a single list
|
|
45
|
+
sorted_page_blocks = []
|
|
46
|
+
for _, group in sorted(vertical_groups.items()):
|
|
47
|
+
sorted_group = sorted(group, key=lambda x: x["bbox"][0])
|
|
48
|
+
sorted_page_blocks.extend(sorted_group)
|
|
49
|
+
|
|
50
|
+
return sorted_page_blocks
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def merge_text(page: Dict, sort=False) -> str:
|
|
54
|
+
text = ""
|
|
55
|
+
if sort:
|
|
56
|
+
page["blocks"] = sort_blocks(page["blocks"])
|
|
57
|
+
|
|
58
|
+
for block in page["blocks"]:
|
|
59
|
+
block_text = ""
|
|
60
|
+
for line in block["lines"]:
|
|
61
|
+
line_text = ""
|
|
62
|
+
for char in line["chars"]:
|
|
63
|
+
line_text += char["char"]
|
|
64
|
+
line_text = postprocess_text(line_text)
|
|
65
|
+
if line_text.endswith("\n"):
|
|
66
|
+
line_text = line_text[:-1].strip() + " "
|
|
67
|
+
|
|
68
|
+
block_text += line_text
|
|
69
|
+
if not block_text.endswith("\n"):
|
|
70
|
+
block_text += "\n\n"
|
|
71
|
+
text += block_text
|
|
72
|
+
return text
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import os.path
|
|
2
|
+
|
|
3
|
+
from pydantic_settings import BaseSettings
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Settings(BaseSettings):
|
|
7
|
+
BASE_PATH: str = os.path.dirname(os.path.dirname(__file__))
|
|
8
|
+
MODEL_PATH: str = os.path.join(BASE_PATH, "models", "dt.joblib")
|
|
9
|
+
|
|
10
|
+
# How many characters to buffer when reading a font name
|
|
11
|
+
FONT_BUFFER_SIZE: int = 1024
|
|
12
|
+
FONTNAME_SAMPLE_FREQ: int = 10
|
|
13
|
+
|
|
14
|
+
# Benchmark
|
|
15
|
+
RESULTS_FOLDER: str = "results"
|
|
16
|
+
BENCH_DATASET_NAME: str = "vikp/pdf_bench"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
settings = Settings()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "pdftext"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Extract structured text from pdfs quickly"
|
|
5
|
+
authors = ["Vik Paruchuri <vik.paruchuri@gmail.com>"]
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
repository = "https://github.com/VikParuchuri/pdftext"
|
|
9
|
+
keywords = ["pdf", "text", "extraction"]
|
|
10
|
+
packages = [
|
|
11
|
+
{include = "pdftext"}
|
|
12
|
+
]
|
|
13
|
+
include = [
|
|
14
|
+
"extract_text.py",
|
|
15
|
+
"models/dt.joblib"
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[tool.poetry.dependencies]
|
|
19
|
+
python = ">=3.9,<3.13,!=3.9.7"
|
|
20
|
+
pypdfium2 = "^4.29.0"
|
|
21
|
+
scikit-learn = "^1.4.2"
|
|
22
|
+
pydantic = "^2.7.1"
|
|
23
|
+
pydantic-settings = "^2.2.1"
|
|
24
|
+
|
|
25
|
+
[tool.poetry.group.dev.dependencies]
|
|
26
|
+
pymupdf = "^1.24.2"
|
|
27
|
+
datasets = "^2.19.0"
|
|
28
|
+
pdfplumber = "^0.11.0"
|
|
29
|
+
pillow = "^10.3.0"
|
|
30
|
+
rapidfuzz = "^3.8.1"
|
|
31
|
+
tabulate = "^0.9.0"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["poetry-core"]
|
|
35
|
+
build-backend = "poetry.core.masonry.api"
|
|
36
|
+
|
|
37
|
+
[tool.poetry.scripts]
|
|
38
|
+
pdftext = "extract_text:main"
|