quire 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.
- quire-0.1.0/LICENSE +202 -0
- quire-0.1.0/NOTICE +9 -0
- quire-0.1.0/PKG-INFO +173 -0
- quire-0.1.0/README.md +144 -0
- quire-0.1.0/THIRD_PARTY_LICENSES.md +32 -0
- quire-0.1.0/pyproject.toml +70 -0
- quire-0.1.0/src/quire/__init__.py +46 -0
- quire-0.1.0/src/quire/cli.py +183 -0
- quire-0.1.0/src/quire/ocr.py +254 -0
- quire-0.1.0/src/quire/outline.py +253 -0
quire-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
quire-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
quire
|
|
2
|
+
Copyright 2026 Shariq Farooqui
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Shariq Farooqui
|
|
5
|
+
(https://github.com/shariq-farooqui/quire).
|
|
6
|
+
|
|
7
|
+
This product bundles and depends on PaddleOCR, PaddleOCR-VL and PaddlePaddle,
|
|
8
|
+
developed by the PaddlePaddle Authors and licensed under the Apache License,
|
|
9
|
+
Version 2.0. See THIRD_PARTY_LICENSES.md for details.
|
quire-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quire
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: PDF to clean markdown, powered by PaddleOCR-VL
|
|
5
|
+
Keywords: ocr,pdf,markdown,paddleocr,document-parsing
|
|
6
|
+
Author: Shariq Farooqui
|
|
7
|
+
Author-email: Shariq Farooqui <shariq.farooqui@outlook.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
License-File: NOTICE
|
|
11
|
+
License-File: THIRD_PARTY_LICENSES.md
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
21
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
22
|
+
Requires-Dist: paddleocr[doc-parser]==3.4.0
|
|
23
|
+
Requires-Dist: paddlepaddle==3.2.0
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Project-URL: Homepage, https://github.com/shariq-farooqui/quire
|
|
26
|
+
Project-URL: Repository, https://github.com/shariq-farooqui/quire
|
|
27
|
+
Project-URL: Issues, https://github.com/shariq-farooqui/quire/issues
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# quire
|
|
31
|
+
|
|
32
|
+
[](https://pypi.org/project/quire/)
|
|
33
|
+
[](https://pypi.org/project/quire/)
|
|
34
|
+
[](https://github.com/shariq-farooqui/quire/blob/main/LICENSE)
|
|
35
|
+
[](https://github.com/astral-sh/ruff)
|
|
36
|
+
|
|
37
|
+
OCR a PDF into clean markdown, powered by PaddleOCR-VL. Runs locally.
|
|
38
|
+
No server, no containers, no signup.
|
|
39
|
+
|
|
40
|
+
quire is built to be used through [uvx](https://docs.astral.sh/uv/guides/tools/),
|
|
41
|
+
so there is nothing to install and nothing to clone. If you have
|
|
42
|
+
[uv](https://docs.astral.sh/uv/getting-started/installation/) on your
|
|
43
|
+
machine, you can OCR a PDF in one line.
|
|
44
|
+
|
|
45
|
+
## Quick start
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
uvx quire document.pdf
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
That prints the cleaned markdown straight to stdout. The first run on
|
|
52
|
+
a machine is slow because `uvx` installs quire's dependencies and
|
|
53
|
+
PaddleOCR-VL downloads its model weights. After that it is cached and
|
|
54
|
+
subsequent runs are fast.
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
# markdown to stdout
|
|
60
|
+
uvx quire document.pdf
|
|
61
|
+
|
|
62
|
+
# save markdown and the full structured json to a directory
|
|
63
|
+
uvx quire document.pdf -o output/
|
|
64
|
+
|
|
65
|
+
# print the full structured OCR result as json
|
|
66
|
+
uvx quire document.pdf --json
|
|
67
|
+
|
|
68
|
+
# suppress progress and timing output on stderr
|
|
69
|
+
uvx quire document.pdf -q
|
|
70
|
+
|
|
71
|
+
# show the version
|
|
72
|
+
uvx quire --version
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`-o output/` writes two files:
|
|
76
|
+
|
|
77
|
+
- `document.md`, the cleaned markdown (same content as stdout)
|
|
78
|
+
- `document_ocr.json`, a structured view with per-page blocks, bounding
|
|
79
|
+
boxes and block labels
|
|
80
|
+
|
|
81
|
+
If you end up using quire often and want to drop the `uvx` prefix, you
|
|
82
|
+
can install it once into a persistent uv tool environment:
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
uv tool install quire
|
|
86
|
+
quire document.pdf
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Output format
|
|
90
|
+
|
|
91
|
+
The json shape is:
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
{
|
|
95
|
+
"page_count": 42,
|
|
96
|
+
"page_width": 1191,
|
|
97
|
+
"page_height": 1684,
|
|
98
|
+
"markdown": "# Document title\n\n...",
|
|
99
|
+
"pages": [
|
|
100
|
+
{
|
|
101
|
+
"page_index": 0,
|
|
102
|
+
"blocks": [
|
|
103
|
+
{
|
|
104
|
+
"block_label": "doc_title",
|
|
105
|
+
"block_content": "Document title",
|
|
106
|
+
"block_bbox": [211, 179, 780, 225],
|
|
107
|
+
"block_id": 0
|
|
108
|
+
}
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
]
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Block labels include `doc_title`, `paragraph_title`, `text`, `table`,
|
|
116
|
+
`header` and `image`.
|
|
117
|
+
|
|
118
|
+
HTML tables produced by PaddleOCR are converted to pipe tables in both
|
|
119
|
+
the markdown and inside table blocks in the json, so the output is
|
|
120
|
+
ready to use without a second cleanup pass.
|
|
121
|
+
|
|
122
|
+
## Why CPU only
|
|
123
|
+
|
|
124
|
+
quire ships with the CPU build of PaddlePaddle and runs inference on
|
|
125
|
+
the CPU. This is an intentional limitation of the tool, not an
|
|
126
|
+
oversight.
|
|
127
|
+
|
|
128
|
+
The Paddle ecosystem publishes its CPU and CUDA builds as two separate
|
|
129
|
+
PyPI packages (`paddlepaddle` and `paddlepaddle-gpu`), each with its
|
|
130
|
+
own wheel index. They share the same `paddle` Python namespace and
|
|
131
|
+
cannot be installed side by side, and Python packaging has no way to
|
|
132
|
+
pick one based on the user's hardware. That means there is no honest
|
|
133
|
+
way for a single uvx command to transparently use the GPU when one is
|
|
134
|
+
available and the CPU when one is not.
|
|
135
|
+
|
|
136
|
+
The whole point of quire is that `uvx quire document.pdf` just works on
|
|
137
|
+
any machine without compiling or configuring anything. CPU is the only
|
|
138
|
+
path that delivers that. If you need GPU throughput, reach for
|
|
139
|
+
PaddleOCR directly; quire is a zero-setup wrapper, not a performance
|
|
140
|
+
tool.
|
|
141
|
+
|
|
142
|
+
## Outline helper for regulatory documents
|
|
143
|
+
|
|
144
|
+
If you work with regulatory or legal PDFs that use Article, Annex,
|
|
145
|
+
Chapter, Part and Section headings, quire ships a second command that
|
|
146
|
+
extracts a quick outline from an existing OCR json:
|
|
147
|
+
|
|
148
|
+
```
|
|
149
|
+
uvx quire document.pdf -o output/
|
|
150
|
+
uvx quire-outline output/document_ocr.json
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
It prints the title, reference code, and a list of sections with page
|
|
154
|
+
ranges and word counts. Pass `--json` for a structured version. This
|
|
155
|
+
is a niche helper; ignore it if your PDFs do not use those heading
|
|
156
|
+
conventions.
|
|
157
|
+
|
|
158
|
+
## Requirements
|
|
159
|
+
|
|
160
|
+
- Python 3.11 or newer
|
|
161
|
+
- Around 4 GB of free disk for PaddleOCR-VL model weights on first run
|
|
162
|
+
- Linux x86_64 is the smoothest path. macOS and Windows should work as
|
|
163
|
+
long as PaddlePaddle ships a wheel for your platform.
|
|
164
|
+
|
|
165
|
+
## Licence
|
|
166
|
+
|
|
167
|
+
quire is licensed under the Apache License 2.0. It wraps PaddleOCR and
|
|
168
|
+
the PaddleOCR-VL model weights, both developed by the PaddlePaddle
|
|
169
|
+
Authors and distributed under Apache 2.0. See `LICENSE`, `NOTICE` and
|
|
170
|
+
`THIRD_PARTY_LICENSES.md` for details.
|
|
171
|
+
|
|
172
|
+
quire is an independent community wrapper. It is not affiliated with or
|
|
173
|
+
endorsed by the PaddlePaddle project.
|
quire-0.1.0/README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# quire
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/quire/)
|
|
4
|
+
[](https://pypi.org/project/quire/)
|
|
5
|
+
[](https://github.com/shariq-farooqui/quire/blob/main/LICENSE)
|
|
6
|
+
[](https://github.com/astral-sh/ruff)
|
|
7
|
+
|
|
8
|
+
OCR a PDF into clean markdown, powered by PaddleOCR-VL. Runs locally.
|
|
9
|
+
No server, no containers, no signup.
|
|
10
|
+
|
|
11
|
+
quire is built to be used through [uvx](https://docs.astral.sh/uv/guides/tools/),
|
|
12
|
+
so there is nothing to install and nothing to clone. If you have
|
|
13
|
+
[uv](https://docs.astral.sh/uv/getting-started/installation/) on your
|
|
14
|
+
machine, you can OCR a PDF in one line.
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
uvx quire document.pdf
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
That prints the cleaned markdown straight to stdout. The first run on
|
|
23
|
+
a machine is slow because `uvx` installs quire's dependencies and
|
|
24
|
+
PaddleOCR-VL downloads its model weights. After that it is cached and
|
|
25
|
+
subsequent runs are fast.
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
# markdown to stdout
|
|
31
|
+
uvx quire document.pdf
|
|
32
|
+
|
|
33
|
+
# save markdown and the full structured json to a directory
|
|
34
|
+
uvx quire document.pdf -o output/
|
|
35
|
+
|
|
36
|
+
# print the full structured OCR result as json
|
|
37
|
+
uvx quire document.pdf --json
|
|
38
|
+
|
|
39
|
+
# suppress progress and timing output on stderr
|
|
40
|
+
uvx quire document.pdf -q
|
|
41
|
+
|
|
42
|
+
# show the version
|
|
43
|
+
uvx quire --version
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`-o output/` writes two files:
|
|
47
|
+
|
|
48
|
+
- `document.md`, the cleaned markdown (same content as stdout)
|
|
49
|
+
- `document_ocr.json`, a structured view with per-page blocks, bounding
|
|
50
|
+
boxes and block labels
|
|
51
|
+
|
|
52
|
+
If you end up using quire often and want to drop the `uvx` prefix, you
|
|
53
|
+
can install it once into a persistent uv tool environment:
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
uv tool install quire
|
|
57
|
+
quire document.pdf
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Output format
|
|
61
|
+
|
|
62
|
+
The json shape is:
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
{
|
|
66
|
+
"page_count": 42,
|
|
67
|
+
"page_width": 1191,
|
|
68
|
+
"page_height": 1684,
|
|
69
|
+
"markdown": "# Document title\n\n...",
|
|
70
|
+
"pages": [
|
|
71
|
+
{
|
|
72
|
+
"page_index": 0,
|
|
73
|
+
"blocks": [
|
|
74
|
+
{
|
|
75
|
+
"block_label": "doc_title",
|
|
76
|
+
"block_content": "Document title",
|
|
77
|
+
"block_bbox": [211, 179, 780, 225],
|
|
78
|
+
"block_id": 0
|
|
79
|
+
}
|
|
80
|
+
]
|
|
81
|
+
}
|
|
82
|
+
]
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Block labels include `doc_title`, `paragraph_title`, `text`, `table`,
|
|
87
|
+
`header` and `image`.
|
|
88
|
+
|
|
89
|
+
HTML tables produced by PaddleOCR are converted to pipe tables in both
|
|
90
|
+
the markdown and inside table blocks in the json, so the output is
|
|
91
|
+
ready to use without a second cleanup pass.
|
|
92
|
+
|
|
93
|
+
## Why CPU only
|
|
94
|
+
|
|
95
|
+
quire ships with the CPU build of PaddlePaddle and runs inference on
|
|
96
|
+
the CPU. This is an intentional limitation of the tool, not an
|
|
97
|
+
oversight.
|
|
98
|
+
|
|
99
|
+
The Paddle ecosystem publishes its CPU and CUDA builds as two separate
|
|
100
|
+
PyPI packages (`paddlepaddle` and `paddlepaddle-gpu`), each with its
|
|
101
|
+
own wheel index. They share the same `paddle` Python namespace and
|
|
102
|
+
cannot be installed side by side, and Python packaging has no way to
|
|
103
|
+
pick one based on the user's hardware. That means there is no honest
|
|
104
|
+
way for a single uvx command to transparently use the GPU when one is
|
|
105
|
+
available and the CPU when one is not.
|
|
106
|
+
|
|
107
|
+
The whole point of quire is that `uvx quire document.pdf` just works on
|
|
108
|
+
any machine without compiling or configuring anything. CPU is the only
|
|
109
|
+
path that delivers that. If you need GPU throughput, reach for
|
|
110
|
+
PaddleOCR directly; quire is a zero-setup wrapper, not a performance
|
|
111
|
+
tool.
|
|
112
|
+
|
|
113
|
+
## Outline helper for regulatory documents
|
|
114
|
+
|
|
115
|
+
If you work with regulatory or legal PDFs that use Article, Annex,
|
|
116
|
+
Chapter, Part and Section headings, quire ships a second command that
|
|
117
|
+
extracts a quick outline from an existing OCR json:
|
|
118
|
+
|
|
119
|
+
```
|
|
120
|
+
uvx quire document.pdf -o output/
|
|
121
|
+
uvx quire-outline output/document_ocr.json
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
It prints the title, reference code, and a list of sections with page
|
|
125
|
+
ranges and word counts. Pass `--json` for a structured version. This
|
|
126
|
+
is a niche helper; ignore it if your PDFs do not use those heading
|
|
127
|
+
conventions.
|
|
128
|
+
|
|
129
|
+
## Requirements
|
|
130
|
+
|
|
131
|
+
- Python 3.11 or newer
|
|
132
|
+
- Around 4 GB of free disk for PaddleOCR-VL model weights on first run
|
|
133
|
+
- Linux x86_64 is the smoothest path. macOS and Windows should work as
|
|
134
|
+
long as PaddlePaddle ships a wheel for your platform.
|
|
135
|
+
|
|
136
|
+
## Licence
|
|
137
|
+
|
|
138
|
+
quire is licensed under the Apache License 2.0. It wraps PaddleOCR and
|
|
139
|
+
the PaddleOCR-VL model weights, both developed by the PaddlePaddle
|
|
140
|
+
Authors and distributed under Apache 2.0. See `LICENSE`, `NOTICE` and
|
|
141
|
+
`THIRD_PARTY_LICENSES.md` for details.
|
|
142
|
+
|
|
143
|
+
quire is an independent community wrapper. It is not affiliated with or
|
|
144
|
+
endorsed by the PaddlePaddle project.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Third-party licenses
|
|
2
|
+
|
|
3
|
+
quire depends on the following third-party projects. At runtime it loads
|
|
4
|
+
PaddleOCR-VL model weights and calls into PaddleOCR and PaddlePaddle. All
|
|
5
|
+
three are distributed under the Apache License, Version 2.0.
|
|
6
|
+
|
|
7
|
+
## PaddleOCR
|
|
8
|
+
|
|
9
|
+
- Project: https://github.com/PaddlePaddle/PaddleOCR
|
|
10
|
+
- Copyright: The PaddlePaddle Authors
|
|
11
|
+
- License: Apache License 2.0
|
|
12
|
+
- License text: https://github.com/PaddlePaddle/PaddleOCR/blob/main/LICENSE
|
|
13
|
+
|
|
14
|
+
## PaddleOCR-VL (model weights)
|
|
15
|
+
|
|
16
|
+
- Project: https://huggingface.co/PaddlePaddle/PaddleOCR-VL
|
|
17
|
+
- Copyright: The PaddlePaddle Authors
|
|
18
|
+
- License: Apache License 2.0
|
|
19
|
+
- License text: https://huggingface.co/PaddlePaddle/PaddleOCR-VL/blob/main/LICENSE
|
|
20
|
+
|
|
21
|
+
## PaddlePaddle
|
|
22
|
+
|
|
23
|
+
- Project: https://github.com/PaddlePaddle/Paddle
|
|
24
|
+
- Copyright: The PaddlePaddle Authors
|
|
25
|
+
- License: Apache License 2.0
|
|
26
|
+
- License text: https://github.com/PaddlePaddle/Paddle/blob/develop/LICENSE
|
|
27
|
+
|
|
28
|
+
## The Apache License 2.0
|
|
29
|
+
|
|
30
|
+
The full text of the Apache License 2.0 is in the LICENSE file at the root
|
|
31
|
+
of this repository and applies to quire itself as well as to each of the
|
|
32
|
+
bundled third-party projects listed above.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "quire"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "PDF to clean markdown, powered by PaddleOCR-VL"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE", "NOTICE", "THIRD_PARTY_LICENSES.md"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Shariq Farooqui", email = "shariq.farooqui@outlook.com" },
|
|
10
|
+
]
|
|
11
|
+
keywords = ["ocr", "pdf", "markdown", "paddleocr", "document-parsing"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 4 - Beta",
|
|
14
|
+
"Environment :: Console",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Operating System :: POSIX :: Linux",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Image Recognition",
|
|
22
|
+
"Topic :: Text Processing :: Markup :: Markdown",
|
|
23
|
+
]
|
|
24
|
+
requires-python = ">=3.11"
|
|
25
|
+
dependencies = [
|
|
26
|
+
"paddleocr[doc-parser]==3.4.0",
|
|
27
|
+
"paddlepaddle==3.2.0",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/shariq-farooqui/quire"
|
|
32
|
+
Repository = "https://github.com/shariq-farooqui/quire"
|
|
33
|
+
Issues = "https://github.com/shariq-farooqui/quire/issues"
|
|
34
|
+
|
|
35
|
+
[project.scripts]
|
|
36
|
+
quire = "quire.cli:main"
|
|
37
|
+
quire-outline = "quire.cli:outline_main"
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["uv_build>=0.11.3,<0.12.0"]
|
|
41
|
+
build-backend = "uv_build"
|
|
42
|
+
|
|
43
|
+
[[tool.uv.index]]
|
|
44
|
+
name = "paddlepaddle"
|
|
45
|
+
url = "https://www.paddlepaddle.org.cn/packages/stable/cpu/"
|
|
46
|
+
explicit = true
|
|
47
|
+
|
|
48
|
+
[tool.uv.sources]
|
|
49
|
+
paddlepaddle = { index = "paddlepaddle" }
|
|
50
|
+
|
|
51
|
+
[tool.uv]
|
|
52
|
+
index-strategy = "unsafe-best-match"
|
|
53
|
+
|
|
54
|
+
[tool.ruff]
|
|
55
|
+
line-length = 100
|
|
56
|
+
target-version = "py311"
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
60
|
+
|
|
61
|
+
[tool.pytest.ini_options]
|
|
62
|
+
minversion = "8.0"
|
|
63
|
+
testpaths = ["tests"]
|
|
64
|
+
pythonpath = ["src"]
|
|
65
|
+
addopts = ["-ra", "--strict-config", "--strict-markers"]
|
|
66
|
+
|
|
67
|
+
[dependency-groups]
|
|
68
|
+
dev = [
|
|
69
|
+
"pytest==9.0.3",
|
|
70
|
+
]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""quire: PDF to clean markdown, powered by PaddleOCR-VL.
|
|
2
|
+
|
|
3
|
+
Public API:
|
|
4
|
+
|
|
5
|
+
- `run_ocr(pdf_path)` runs PaddleOCR-VL on a PDF and returns a
|
|
6
|
+
structured result.
|
|
7
|
+
- `store_result`, `load_result` round-trip an OCR result through disk.
|
|
8
|
+
- `build_outline` extracts a flat regulatory-style outline from an
|
|
9
|
+
existing OCR result (mostly useful for legal documents).
|
|
10
|
+
|
|
11
|
+
Two console scripts are installed by the package: `quire` (the main
|
|
12
|
+
OCR command) and `quire-outline` (the niche outline helper). Both run
|
|
13
|
+
happily under `uvx`.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from quire.ocr import (
|
|
17
|
+
OcrBlock,
|
|
18
|
+
OcrPageResult,
|
|
19
|
+
OcrResult,
|
|
20
|
+
load_result,
|
|
21
|
+
run_ocr,
|
|
22
|
+
store_result,
|
|
23
|
+
)
|
|
24
|
+
from quire.outline import (
|
|
25
|
+
Outline,
|
|
26
|
+
OutlineSection,
|
|
27
|
+
build_outline,
|
|
28
|
+
get_pages_text,
|
|
29
|
+
get_section_text,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"OcrBlock",
|
|
34
|
+
"OcrPageResult",
|
|
35
|
+
"OcrResult",
|
|
36
|
+
"Outline",
|
|
37
|
+
"OutlineSection",
|
|
38
|
+
"build_outline",
|
|
39
|
+
"get_pages_text",
|
|
40
|
+
"get_section_text",
|
|
41
|
+
"load_result",
|
|
42
|
+
"run_ocr",
|
|
43
|
+
"store_result",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Command line interfaces for the `quire` and `quire-outline` tools."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from quire import __version__
|
|
11
|
+
from quire.ocr import load_result, run_ocr, store_result
|
|
12
|
+
from quire.outline import build_outline
|
|
13
|
+
|
|
14
|
+
log = logging.getLogger("quire")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _setup_logging(quiet: bool) -> None:
|
|
18
|
+
level = logging.WARNING if quiet else logging.INFO
|
|
19
|
+
logging.basicConfig(level=level, format="%(message)s", stream=sys.stderr)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _file_size_str(path: Path) -> str:
|
|
23
|
+
size = path.stat().st_size
|
|
24
|
+
if size < 1024:
|
|
25
|
+
return f"{size} B"
|
|
26
|
+
if size < 1024 * 1024:
|
|
27
|
+
return f"{size / 1024:.1f} KB"
|
|
28
|
+
return f"{size / (1024 * 1024):.1f} MB"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _ocr_pdf(pdf: Path) -> dict:
|
|
32
|
+
t0 = time.time()
|
|
33
|
+
result = run_ocr(pdf)
|
|
34
|
+
elapsed = time.time() - t0
|
|
35
|
+
log.info(
|
|
36
|
+
"OCR done in %.1fs: %d pages, %d blocks",
|
|
37
|
+
elapsed,
|
|
38
|
+
result["page_count"],
|
|
39
|
+
sum(len(p["blocks"]) for p in result["pages"]),
|
|
40
|
+
)
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def main(argv: list[str] | None = None) -> int:
|
|
45
|
+
"""Entry point for the `quire` command.
|
|
46
|
+
|
|
47
|
+
Parses arguments, runs the PaddleOCR-VL pipeline on the given PDF,
|
|
48
|
+
and either prints the result to stdout or writes it to a directory
|
|
49
|
+
depending on the flags. Returns a process exit code.
|
|
50
|
+
"""
|
|
51
|
+
parser = argparse.ArgumentParser(
|
|
52
|
+
prog="quire",
|
|
53
|
+
description="PDF to clean markdown, powered by PaddleOCR-VL.",
|
|
54
|
+
)
|
|
55
|
+
parser.add_argument("pdf", type=Path, help="Path to a PDF file")
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"-o",
|
|
58
|
+
"--output-dir",
|
|
59
|
+
type=Path,
|
|
60
|
+
default=None,
|
|
61
|
+
help="Write <stem>.md and <stem>_ocr.json to this directory",
|
|
62
|
+
)
|
|
63
|
+
parser.add_argument(
|
|
64
|
+
"--json",
|
|
65
|
+
action="store_true",
|
|
66
|
+
help="Print the full OCR result as JSON to stdout instead of markdown",
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"-q",
|
|
70
|
+
"--quiet",
|
|
71
|
+
action="store_true",
|
|
72
|
+
help="Suppress progress and timing output on stderr",
|
|
73
|
+
)
|
|
74
|
+
parser.add_argument(
|
|
75
|
+
"--version",
|
|
76
|
+
action="version",
|
|
77
|
+
version=f"quire {__version__}",
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
args = parser.parse_args(argv)
|
|
81
|
+
_setup_logging(args.quiet)
|
|
82
|
+
|
|
83
|
+
if not args.pdf.exists():
|
|
84
|
+
log.error("File not found: %s", args.pdf)
|
|
85
|
+
return 1
|
|
86
|
+
if not args.pdf.is_file():
|
|
87
|
+
log.error("Not a file: %s", args.pdf)
|
|
88
|
+
return 1
|
|
89
|
+
|
|
90
|
+
if args.output_dir is not None and args.json:
|
|
91
|
+
log.error("--json and --output-dir cannot be combined")
|
|
92
|
+
return 2
|
|
93
|
+
|
|
94
|
+
result = _ocr_pdf(args.pdf)
|
|
95
|
+
|
|
96
|
+
if args.output_dir is not None:
|
|
97
|
+
json_path, md_path = store_result(result, args.output_dir, args.pdf.stem)
|
|
98
|
+
log.info(" %s (%s)", md_path, _file_size_str(md_path))
|
|
99
|
+
log.info(" %s (%s)", json_path, _file_size_str(json_path))
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
if args.json:
|
|
103
|
+
json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
|
|
104
|
+
sys.stdout.write("\n")
|
|
105
|
+
else:
|
|
106
|
+
sys.stdout.write(result["markdown"])
|
|
107
|
+
if not result["markdown"].endswith("\n"):
|
|
108
|
+
sys.stdout.write("\n")
|
|
109
|
+
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def outline_main(argv: list[str] | None = None) -> int:
|
|
114
|
+
"""Entry point for the `quire-outline` command.
|
|
115
|
+
|
|
116
|
+
Loads an OCR json produced by `quire`, builds an outline from it and
|
|
117
|
+
prints it either as a plain text summary or as json. Returns a
|
|
118
|
+
process exit code.
|
|
119
|
+
"""
|
|
120
|
+
parser = argparse.ArgumentParser(
|
|
121
|
+
prog="quire-outline",
|
|
122
|
+
description=(
|
|
123
|
+
"Extract an outline from an OCR JSON produced by quire. "
|
|
124
|
+
"Looks for Article, Annex, Chapter, Part and Section headings, "
|
|
125
|
+
"so it is most useful on regulatory or legal documents."
|
|
126
|
+
),
|
|
127
|
+
)
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"json_path",
|
|
130
|
+
type=Path,
|
|
131
|
+
metavar="OCR_JSON",
|
|
132
|
+
help="Path to an OCR JSON file produced by 'quire <pdf> -o <dir>'",
|
|
133
|
+
)
|
|
134
|
+
parser.add_argument(
|
|
135
|
+
"--json",
|
|
136
|
+
action="store_true",
|
|
137
|
+
dest="json_output",
|
|
138
|
+
help="Print the outline as JSON instead of plain text",
|
|
139
|
+
)
|
|
140
|
+
parser.add_argument(
|
|
141
|
+
"--version",
|
|
142
|
+
action="version",
|
|
143
|
+
version=f"quire {__version__}",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
args = parser.parse_args(argv)
|
|
147
|
+
_setup_logging(quiet=False)
|
|
148
|
+
|
|
149
|
+
if not args.json_path.exists():
|
|
150
|
+
log.error("File not found: %s", args.json_path)
|
|
151
|
+
return 1
|
|
152
|
+
|
|
153
|
+
ocr_result = load_result(args.json_path)
|
|
154
|
+
outline = build_outline(ocr_result)
|
|
155
|
+
|
|
156
|
+
if args.json_output:
|
|
157
|
+
json.dump(outline, sys.stdout, ensure_ascii=False, indent=2)
|
|
158
|
+
sys.stdout.write("\n")
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
print(f"Title: {outline['title'] or '(none)'}")
|
|
162
|
+
print(f"Reference: {outline['reference_code'] or '(none)'}")
|
|
163
|
+
print(f"Pages: {outline['page_count']}")
|
|
164
|
+
print(f"Words: {outline['total_words']:,}")
|
|
165
|
+
print(f"Blocks: {outline['total_blocks']}")
|
|
166
|
+
types = ", ".join(f"{k}({v})" for k, v in outline["block_type_summary"].items())
|
|
167
|
+
print(f"Types: {types}")
|
|
168
|
+
|
|
169
|
+
sections = outline["sections"]
|
|
170
|
+
if sections:
|
|
171
|
+
print(f"\nSections ({len(sections)}):")
|
|
172
|
+
for s in sections:
|
|
173
|
+
title_part = f" {s['title']}" if s["title"] else ""
|
|
174
|
+
print(
|
|
175
|
+
f" {s['reference']:<20s} (p.{s['start_page']}-{s['end_page']})"
|
|
176
|
+
f"{title_part} {s['word_count']:,} words"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
sys.exit(main())
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""PaddleOCR-VL pipeline wrapper and result helpers."""
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import threading
|
|
9
|
+
from html.parser import HTMLParser
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TypedDict
|
|
12
|
+
|
|
13
|
+
os.environ.setdefault("PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK", "True")
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
_pipeline = None
|
|
18
|
+
_pipeline_lock = threading.Lock()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class OcrBlock(TypedDict):
|
|
22
|
+
"""A single layout block detected on a page.
|
|
23
|
+
|
|
24
|
+
`block_bbox` is `[x_min, y_min, x_max, y_max]` in the source page's
|
|
25
|
+
pixel coordinates. `block_label` is one of PaddleOCR-VL's layout
|
|
26
|
+
categories, for example `doc_title`, `paragraph_title`, `text`,
|
|
27
|
+
`table`, `header` or `image`.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
block_label: str
|
|
31
|
+
block_content: str
|
|
32
|
+
block_bbox: list[int]
|
|
33
|
+
block_id: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class OcrPageResult(TypedDict):
|
|
37
|
+
"""The blocks belonging to one page of a PDF. `page_index` is 0-indexed."""
|
|
38
|
+
|
|
39
|
+
page_index: int
|
|
40
|
+
blocks: list[OcrBlock]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class OcrResult(TypedDict):
|
|
44
|
+
"""Full structured OCR output for a PDF.
|
|
45
|
+
|
|
46
|
+
`markdown` is the cleaned concatenation across all pages, with any
|
|
47
|
+
HTML tables rewritten as pipe tables. `pages` holds per-page blocks
|
|
48
|
+
for downstream layout work. `page_width` and `page_height` come
|
|
49
|
+
from the first page only.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
page_count: int
|
|
53
|
+
page_width: int
|
|
54
|
+
page_height: int
|
|
55
|
+
markdown: str
|
|
56
|
+
pages: list[OcrPageResult]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _get_pipeline():
|
|
60
|
+
global _pipeline
|
|
61
|
+
if _pipeline is None:
|
|
62
|
+
with _pipeline_lock:
|
|
63
|
+
if _pipeline is None:
|
|
64
|
+
from paddleocr import PaddleOCRVL
|
|
65
|
+
|
|
66
|
+
log.info("Loading PaddleOCR-VL pipeline")
|
|
67
|
+
_pipeline = PaddleOCRVL(device="cpu")
|
|
68
|
+
return _pipeline
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _TableParser(HTMLParser):
|
|
72
|
+
def __init__(self):
|
|
73
|
+
super().__init__()
|
|
74
|
+
self.rows: list[list[str]] = []
|
|
75
|
+
self._current_row: list[str] = []
|
|
76
|
+
self._current_cell: list[str] = []
|
|
77
|
+
self._in_cell = False
|
|
78
|
+
self._is_header_row = False
|
|
79
|
+
self._has_header = False
|
|
80
|
+
|
|
81
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]):
|
|
82
|
+
if tag == "tr":
|
|
83
|
+
self._current_row = []
|
|
84
|
+
self._is_header_row = False
|
|
85
|
+
elif tag in ("td", "th"):
|
|
86
|
+
self._in_cell = True
|
|
87
|
+
self._current_cell = []
|
|
88
|
+
if tag == "th":
|
|
89
|
+
self._is_header_row = True
|
|
90
|
+
|
|
91
|
+
def handle_endtag(self, tag: str):
|
|
92
|
+
if tag in ("td", "th"):
|
|
93
|
+
self._in_cell = False
|
|
94
|
+
self._current_row.append("".join(self._current_cell).strip())
|
|
95
|
+
elif tag == "tr":
|
|
96
|
+
if self._current_row:
|
|
97
|
+
self.rows.append(self._current_row)
|
|
98
|
+
if self._is_header_row:
|
|
99
|
+
self._has_header = True
|
|
100
|
+
|
|
101
|
+
def handle_data(self, data: str):
|
|
102
|
+
if self._in_cell:
|
|
103
|
+
self._current_cell.append(data)
|
|
104
|
+
|
|
105
|
+
def to_markdown(self) -> str:
|
|
106
|
+
if not self.rows:
|
|
107
|
+
return ""
|
|
108
|
+
col_count = max(len(row) for row in self.rows)
|
|
109
|
+
lines = []
|
|
110
|
+
for i, row in enumerate(self.rows):
|
|
111
|
+
padded = row + [""] * (col_count - len(row))
|
|
112
|
+
lines.append("| " + " | ".join(padded) + " |")
|
|
113
|
+
if i == 0:
|
|
114
|
+
lines.append("| " + " | ".join("---" for _ in range(col_count)) + " |")
|
|
115
|
+
return "\n".join(lines)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
_TABLE_RE = re.compile(r"<table[^>]*>.*?</table>", re.DOTALL | re.IGNORECASE)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def run_ocr(pdf_path: Path) -> OcrResult:
|
|
122
|
+
"""Run PaddleOCR-VL on a PDF and return the full structured result.
|
|
123
|
+
|
|
124
|
+
Loads the PaddleOCR-VL pipeline on first call, which triggers a
|
|
125
|
+
model weights download the first time on a given machine and is
|
|
126
|
+
slow. The pipeline is cached for the rest of the process, so
|
|
127
|
+
repeated calls inside the same run are fast.
|
|
128
|
+
|
|
129
|
+
Each page is processed twice on purpose: once in isolation to keep
|
|
130
|
+
accurate per-page blocks and bounding boxes, and once concatenated
|
|
131
|
+
so that cross-page tables and titles merge cleanly in the markdown.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
pdf_path: Path to the PDF file to OCR.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
An `OcrResult` with page count, first-page dimensions, cleaned
|
|
138
|
+
markdown and per-page blocks with bounding boxes.
|
|
139
|
+
"""
|
|
140
|
+
pipeline = _get_pipeline()
|
|
141
|
+
pages_res = list(pipeline.predict(str(pdf_path)))
|
|
142
|
+
pages_res_for_concat = copy.deepcopy(pages_res)
|
|
143
|
+
|
|
144
|
+
per_page = []
|
|
145
|
+
for page_res in pages_res:
|
|
146
|
+
results = list(
|
|
147
|
+
pipeline.restructure_pages(
|
|
148
|
+
[copy.deepcopy(page_res)],
|
|
149
|
+
merge_tables=True,
|
|
150
|
+
relevel_titles=True,
|
|
151
|
+
concatenate_pages=False,
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
per_page.append(results[-1])
|
|
155
|
+
|
|
156
|
+
concatenated = list(
|
|
157
|
+
pipeline.restructure_pages(
|
|
158
|
+
pages_res_for_concat,
|
|
159
|
+
merge_tables=True,
|
|
160
|
+
relevel_titles=True,
|
|
161
|
+
concatenate_pages=True,
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
concat_result = concatenated[0]
|
|
166
|
+
markdown_raw = concat_result.markdown
|
|
167
|
+
markdown_text = (
|
|
168
|
+
markdown_raw["markdown_texts"] if isinstance(markdown_raw, dict) else markdown_raw
|
|
169
|
+
)
|
|
170
|
+
markdown = _clean_html_tables(markdown_text)
|
|
171
|
+
|
|
172
|
+
first_page_meta = per_page[0].json["res"]
|
|
173
|
+
page_count = len(pages_res)
|
|
174
|
+
page_width = first_page_meta.get("width", 0)
|
|
175
|
+
page_height = first_page_meta.get("height", 0)
|
|
176
|
+
|
|
177
|
+
pages = _build_page_blocks(per_page)
|
|
178
|
+
|
|
179
|
+
return OcrResult(
|
|
180
|
+
page_count=page_count,
|
|
181
|
+
page_width=page_width,
|
|
182
|
+
page_height=page_height,
|
|
183
|
+
markdown=markdown,
|
|
184
|
+
pages=pages,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _clean_html_tables(markdown: str) -> str:
|
|
189
|
+
def _replace_table(match: re.Match) -> str:
|
|
190
|
+
parser = _TableParser()
|
|
191
|
+
parser.feed(match.group(0))
|
|
192
|
+
converted = parser.to_markdown()
|
|
193
|
+
return converted if converted else match.group(0)
|
|
194
|
+
|
|
195
|
+
return _TABLE_RE.sub(_replace_table, markdown)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _parse_bbox(bbox) -> list[int]:
|
|
199
|
+
if isinstance(bbox, list):
|
|
200
|
+
return bbox
|
|
201
|
+
if isinstance(bbox, str):
|
|
202
|
+
try:
|
|
203
|
+
return json.loads(bbox)
|
|
204
|
+
except (json.JSONDecodeError, ValueError):
|
|
205
|
+
return []
|
|
206
|
+
return []
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _build_page_blocks(per_page_results: list) -> list[OcrPageResult]:
|
|
210
|
+
pages: list[OcrPageResult] = []
|
|
211
|
+
for page_index, result in enumerate(per_page_results):
|
|
212
|
+
blocks: list[OcrBlock] = []
|
|
213
|
+
parsing_res = result.json["res"].get("parsing_res_list", [])
|
|
214
|
+
for item in parsing_res:
|
|
215
|
+
content = item.get("block_content", "")
|
|
216
|
+
if item.get("block_label") == "table" and _TABLE_RE.search(content):
|
|
217
|
+
content = _clean_html_tables(content)
|
|
218
|
+
blocks.append(
|
|
219
|
+
OcrBlock(
|
|
220
|
+
block_label=item.get("block_label", ""),
|
|
221
|
+
block_content=content,
|
|
222
|
+
block_bbox=_parse_bbox(item.get("block_bbox", [])),
|
|
223
|
+
block_id=int(item.get("block_id", 0)),
|
|
224
|
+
)
|
|
225
|
+
)
|
|
226
|
+
pages.append(
|
|
227
|
+
OcrPageResult(
|
|
228
|
+
page_index=page_index,
|
|
229
|
+
blocks=blocks,
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
return pages
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def store_result(result: OcrResult, output_dir: Path, stem: str) -> tuple[Path, Path]:
|
|
236
|
+
"""Write an OCR result to disk as two files.
|
|
237
|
+
|
|
238
|
+
Creates `<output_dir>/<stem>_ocr.json` with the full structured
|
|
239
|
+
result and `<output_dir>/<stem>.md` with just the cleaned markdown.
|
|
240
|
+
The directory is created if it does not already exist.
|
|
241
|
+
|
|
242
|
+
Returns the json and markdown paths, in that order.
|
|
243
|
+
"""
|
|
244
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
245
|
+
json_path = output_dir / f"{stem}_ocr.json"
|
|
246
|
+
json_path.write_text(json.dumps(result, ensure_ascii=False, indent=2))
|
|
247
|
+
md_path = output_dir / f"{stem}.md"
|
|
248
|
+
md_path.write_text(result["markdown"])
|
|
249
|
+
return json_path, md_path
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def load_result(json_path: Path) -> OcrResult:
|
|
253
|
+
"""Read back an OCR result previously saved with `store_result`."""
|
|
254
|
+
return json.loads(json_path.read_text())
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Extract a flat outline from an OCR result for regulatory documents.
|
|
2
|
+
|
|
3
|
+
This module scans the block list of an `OcrResult` for headings that
|
|
4
|
+
match conventional regulatory section patterns such as `Article N`,
|
|
5
|
+
`Annex X`, `Chapter X`, `Part X` and `Section N`, and builds a flat
|
|
6
|
+
list of sections with page ranges and word counts. It is tuned for
|
|
7
|
+
legal and regulatory PDFs and will return an empty section list on
|
|
8
|
+
most other documents.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from collections import Counter
|
|
13
|
+
from typing import TypedDict
|
|
14
|
+
|
|
15
|
+
_SECTION_RE = re.compile(
|
|
16
|
+
r"^(Article\s+\d+|Annex\s+[A-Z0-9IVXLC]+|ANNEX\s+[A-Z0-9IVXLC]+|"
|
|
17
|
+
r"Chapter\s+[A-Z0-9IVXLC]+|CHAPTER\s+[A-Z0-9IVXLC]+|"
|
|
18
|
+
r"Part\s+[A-Z0-9]+|PART\s+[A-Z0-9]+|Section\s+\d+|SECTION\s+\d+)",
|
|
19
|
+
re.IGNORECASE,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class OutlineSection(TypedDict):
|
|
24
|
+
"""A single section in an `Outline`.
|
|
25
|
+
|
|
26
|
+
`reference` is the heading as it appeared in the PDF, normalised to
|
|
27
|
+
Title Case (e.g. `"Article 12"`, `"Annex IV"`). `title` is the
|
|
28
|
+
following heading if one exists, or an empty string. `start_page`
|
|
29
|
+
and `end_page` are 1-indexed and inclusive. `body_snippet` is the
|
|
30
|
+
first 300 characters of the section body, useful for previews.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
reference: str
|
|
34
|
+
title: str
|
|
35
|
+
start_page: int
|
|
36
|
+
end_page: int
|
|
37
|
+
word_count: int
|
|
38
|
+
block_counts: dict[str, int]
|
|
39
|
+
body_snippet: str
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Outline(TypedDict):
|
|
43
|
+
"""A flat outline of a document.
|
|
44
|
+
|
|
45
|
+
`reference_code` is a guess at the document's identifier from the
|
|
46
|
+
first page header (e.g. an EU regulation number). `sections` is a
|
|
47
|
+
sorted list of section entries. The other fields are global
|
|
48
|
+
counters across the full document.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
title: str
|
|
52
|
+
reference_code: str
|
|
53
|
+
page_count: int
|
|
54
|
+
total_words: int
|
|
55
|
+
total_blocks: int
|
|
56
|
+
block_type_summary: dict[str, int]
|
|
57
|
+
sections: list[OutlineSection]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def build_outline(ocr_result: dict) -> Outline:
|
|
61
|
+
"""Build an `Outline` from an `OcrResult` dict.
|
|
62
|
+
|
|
63
|
+
Walks every block on every page, picks out the document title and
|
|
64
|
+
reference code from the first couple of pages, then looks for
|
|
65
|
+
paragraph titles and doc titles matching the regulatory section
|
|
66
|
+
regex and assembles a sorted list of sections with page ranges and
|
|
67
|
+
word counts.
|
|
68
|
+
|
|
69
|
+
When the same reference appears more than once (a common quirk of
|
|
70
|
+
PaddleOCR-VL on running headers), the entry with a meaningful body
|
|
71
|
+
is preferred and the rest are dropped.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
ocr_result: An `OcrResult` dict (or any dict with the same
|
|
75
|
+
shape) as produced by `quire.run_ocr` or `quire.load_result`.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
An `Outline` TypedDict. The `sections` list is empty for
|
|
79
|
+
documents that do not use the expected heading conventions.
|
|
80
|
+
"""
|
|
81
|
+
pages = ocr_result.get("pages", [])
|
|
82
|
+
outline: Outline = {
|
|
83
|
+
"title": "",
|
|
84
|
+
"reference_code": "",
|
|
85
|
+
"page_count": ocr_result.get("page_count", len(pages)),
|
|
86
|
+
"total_words": 0,
|
|
87
|
+
"total_blocks": 0,
|
|
88
|
+
"block_type_summary": {},
|
|
89
|
+
"sections": [],
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
_extract_title(pages, outline)
|
|
93
|
+
_extract_reference_code(pages, outline)
|
|
94
|
+
_compute_global_stats(pages, outline)
|
|
95
|
+
_extract_sections(pages, outline)
|
|
96
|
+
|
|
97
|
+
return outline
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def get_section_text(ocr_result: dict, section: OutlineSection) -> str:
|
|
101
|
+
"""Return the full text of a section as a single joined string.
|
|
102
|
+
|
|
103
|
+
Concatenates every non-empty block on pages within the section's
|
|
104
|
+
`start_page..end_page` range, with one block per line.
|
|
105
|
+
"""
|
|
106
|
+
pages = ocr_result.get("pages", [])
|
|
107
|
+
parts: list[str] = []
|
|
108
|
+
for page in pages:
|
|
109
|
+
page_num = page.get("page_index", 0) + 1
|
|
110
|
+
if page_num < section["start_page"] or page_num > section["end_page"]:
|
|
111
|
+
continue
|
|
112
|
+
for block in page.get("blocks", []):
|
|
113
|
+
content = block.get("block_content", "").strip()
|
|
114
|
+
if content:
|
|
115
|
+
parts.append(content)
|
|
116
|
+
return "\n".join(parts)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get_pages_text(ocr_result: dict, start_page: int, end_page: int) -> str:
|
|
120
|
+
"""Return the text of a page range as a single joined string.
|
|
121
|
+
|
|
122
|
+
Page numbers are 1-indexed and both bounds are inclusive.
|
|
123
|
+
"""
|
|
124
|
+
pages = ocr_result.get("pages", [])
|
|
125
|
+
parts: list[str] = []
|
|
126
|
+
for page in pages:
|
|
127
|
+
page_num = page.get("page_index", 0) + 1
|
|
128
|
+
if page_num < start_page or page_num > end_page:
|
|
129
|
+
continue
|
|
130
|
+
for block in page.get("blocks", []):
|
|
131
|
+
content = block.get("block_content", "").strip()
|
|
132
|
+
if content:
|
|
133
|
+
parts.append(content)
|
|
134
|
+
return "\n".join(parts)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _extract_title(pages: list[dict], outline: Outline) -> None:
|
|
138
|
+
for page in pages[:3]:
|
|
139
|
+
for block in page.get("blocks", []):
|
|
140
|
+
if block.get("block_label") == "doc_title":
|
|
141
|
+
outline["title"] = block.get("block_content", "").strip()
|
|
142
|
+
return
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _extract_reference_code(pages: list[dict], outline: Outline) -> None:
|
|
146
|
+
for page in pages[:2]:
|
|
147
|
+
for block in page.get("blocks", []):
|
|
148
|
+
if block.get("block_label") == "header":
|
|
149
|
+
content = block.get("block_content", "").strip()
|
|
150
|
+
if content and any(c.isdigit() for c in content):
|
|
151
|
+
outline["reference_code"] = content.split()[0] if content.split() else content
|
|
152
|
+
return
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _compute_global_stats(pages: list[dict], outline: Outline) -> None:
|
|
156
|
+
label_counts: Counter[str] = Counter()
|
|
157
|
+
total_words = 0
|
|
158
|
+
|
|
159
|
+
for page in pages:
|
|
160
|
+
for block in page.get("blocks", []):
|
|
161
|
+
label = block.get("block_label", "unknown")
|
|
162
|
+
label_counts[label] += 1
|
|
163
|
+
content = block.get("block_content", "")
|
|
164
|
+
total_words += len(content.split())
|
|
165
|
+
|
|
166
|
+
outline["total_words"] = total_words
|
|
167
|
+
outline["total_blocks"] = sum(label_counts.values())
|
|
168
|
+
outline["block_type_summary"] = dict(label_counts.most_common())
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _extract_sections(pages: list[dict], outline: Outline) -> None:
|
|
172
|
+
raw_headings: list[dict] = []
|
|
173
|
+
|
|
174
|
+
for page in pages:
|
|
175
|
+
page_num = page.get("page_index", 0) + 1
|
|
176
|
+
blocks = page.get("blocks", [])
|
|
177
|
+
|
|
178
|
+
for i, block in enumerate(blocks):
|
|
179
|
+
label = block.get("block_label", "")
|
|
180
|
+
content = block.get("block_content", "").strip()
|
|
181
|
+
if label not in ("paragraph_title", "doc_title"):
|
|
182
|
+
continue
|
|
183
|
+
match = _SECTION_RE.match(content)
|
|
184
|
+
if not match:
|
|
185
|
+
continue
|
|
186
|
+
|
|
187
|
+
reference = match.group(0)
|
|
188
|
+
if reference.split()[0].isupper():
|
|
189
|
+
reference = reference.split()[0].title() + " " + " ".join(reference.split()[1:])
|
|
190
|
+
|
|
191
|
+
title = ""
|
|
192
|
+
body_snippet = ""
|
|
193
|
+
body_chars = 0
|
|
194
|
+
for j in range(i + 1, len(blocks)):
|
|
195
|
+
nxt = blocks[j]
|
|
196
|
+
nxt_label = nxt.get("block_label", "")
|
|
197
|
+
nxt_content = nxt.get("block_content", "").strip()
|
|
198
|
+
if not nxt_content:
|
|
199
|
+
continue
|
|
200
|
+
if nxt_label in ("paragraph_title", "doc_title") and _SECTION_RE.match(nxt_content):
|
|
201
|
+
break
|
|
202
|
+
if nxt_label == "paragraph_title" and not title:
|
|
203
|
+
title = nxt_content
|
|
204
|
+
continue
|
|
205
|
+
body_chars += len(nxt_content)
|
|
206
|
+
if len(body_snippet) < 300:
|
|
207
|
+
body_snippet += nxt_content[: 300 - len(body_snippet)] + " "
|
|
208
|
+
|
|
209
|
+
raw_headings.append(
|
|
210
|
+
{
|
|
211
|
+
"reference": reference,
|
|
212
|
+
"title": title,
|
|
213
|
+
"page_num": page_num,
|
|
214
|
+
"body_chars": body_chars,
|
|
215
|
+
"body_snippet": body_snippet.strip(),
|
|
216
|
+
}
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
by_ref: dict[str, list[dict]] = {}
|
|
220
|
+
for h in raw_headings:
|
|
221
|
+
by_ref.setdefault(h["reference"], []).append(h)
|
|
222
|
+
|
|
223
|
+
deduped: list[dict] = []
|
|
224
|
+
for entries in by_ref.values():
|
|
225
|
+
with_body = [e for e in entries if e["body_chars"] > 50]
|
|
226
|
+
chosen = with_body[0] if with_body else entries[-1]
|
|
227
|
+
deduped.append(chosen)
|
|
228
|
+
|
|
229
|
+
deduped.sort(key=lambda s: s["page_num"])
|
|
230
|
+
|
|
231
|
+
for i, s in enumerate(deduped):
|
|
232
|
+
end_page = deduped[i + 1]["page_num"] if i + 1 < len(deduped) else outline["page_count"]
|
|
233
|
+
|
|
234
|
+
block_counts: Counter[str] = Counter()
|
|
235
|
+
word_count = 0
|
|
236
|
+
for page in pages:
|
|
237
|
+
pn = page.get("page_index", 0) + 1
|
|
238
|
+
if s["page_num"] <= pn <= end_page:
|
|
239
|
+
for block in page.get("blocks", []):
|
|
240
|
+
block_counts[block.get("block_label", "text")] += 1
|
|
241
|
+
word_count += len(block.get("block_content", "").split())
|
|
242
|
+
|
|
243
|
+
outline["sections"].append(
|
|
244
|
+
OutlineSection(
|
|
245
|
+
reference=s["reference"],
|
|
246
|
+
title=s["title"],
|
|
247
|
+
start_page=s["page_num"],
|
|
248
|
+
end_page=end_page,
|
|
249
|
+
word_count=word_count,
|
|
250
|
+
block_counts=dict(block_counts),
|
|
251
|
+
body_snippet=s["body_snippet"],
|
|
252
|
+
)
|
|
253
|
+
)
|