dorsal-pdf-extractor 0.6.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.
@@ -0,0 +1,30 @@
1
+ build/
2
+ dist/
3
+ *.egg-info/
4
+ __pycache__/
5
+ .pytest_cache/
6
+
7
+ # Environments
8
+ .env
9
+ .venv
10
+ env/
11
+ venv/
12
+ ENV/
13
+ env.bak/
14
+ venv.bak/
15
+
16
+ # Dorsal
17
+ dorsal.toml
18
+
19
+ # Coverage
20
+ .coverage
21
+ .coverage.*
22
+ htmlcov/
23
+
24
+ # Tooling
25
+ .mypy_cache/
26
+ .ruff_cache/
27
+
28
+ # Agents
29
+ CLAUDE.md
30
+ .claude/
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## 0.6.0 (2026-10-30)
4
+
5
+ ### Changed
6
+
7
+ - **Records are validated and stamped as OATS `document-extraction` 0.8.0.** `model_config.toml` now pins `schema_version = "0.8.0"`. Before, Dorsal used its default, 0.5.0. The record's fields and shape are the same.
8
+ - **Block ids are deterministic.** Each `id` is `p<page>-<hash>-<n>`: the page number, the first 12 hexadecimal characters of the SHA-256 digest of the block's text, and a count, from 1, of blocks with the same page and hash. Extracting the same file again gives the same ids. Before, every block got a random UUID4 on every run. See the README's "Block IDs" section.
9
+ - **Requires `dorsalhub>=0.12.1,<0.13`.** The model uses Dorsal's internal PDF functions, so the range has an upper bound. Dorsal 0.12.1 fixes boxes on rotated, cropped and offset pages, and the size of pages under 1 pt.
10
+ - OCR text has control characters removed, as native text already did.
11
+
12
+ ### Fixed
13
+
14
+ - A page whose size Dorsal reports as 0 no longer makes the record invalid. Its size is left out of `page_width` and `page_height`, which then list the other pages' sizes by page. Before, Dorsal dropped the whole annotation.
15
+ - `attributes.start_page` and `attributes.end_page` cover every page, including pages left out of `page_width` and `page_height`.
16
+
17
+ ### Added
18
+
19
+ - An `ocr` extra that installs `pytesseract`. OCR also needs the Tesseract binary.
20
+ - A contract test that runs the model on real PDFs and validates every record with `oatschema` at the pinned version, and tests that ids are stable and unique.
21
+ - `ruff` and `mypy` configuration.
22
+ - Package licence metadata (`Apache-2.0`) and the repository URL.
23
+
24
+ ### Removed
25
+
26
+ - The unused `dorsalhub-adapters` development dependency.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.5
2
+ Name: dorsal-pdf-extractor
3
+ Version: 0.6.0
4
+ Summary: Dorsal model: PDF Extractor
5
+ Project-URL: Repository, https://github.com/dorsalhub/pdf-extractor
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: dorsalhub<0.13,>=0.12.1
10
+ Provides-Extra: ocr
11
+ Requires-Dist: pytesseract>=0.3.13; extra == 'ocr'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Dorsal PDF Extractor
15
+
16
+ Fast, deterministic PDF extraction using [`pdfium`](https://pdfium.googlesource.com/pdfium/). Get native text and bounding boxes without the overhead of heavy AI layout models. Tesseract OCR fallback for scanned pages.
17
+
18
+ ## Features
19
+
20
+ * **Native Extraction:** Extracts text and its bounding boxes directly from the PDF document.
21
+ * **Tesseract OCR Fallback:** Optional optical character recognition (OCR) for scanned or empty pages.
22
+ * **Stable Block IDs:** Extracting the same file again gives the same block ids, so annotations that refer to a block keep working.
23
+ * **Schema Compliant:** Outputs records that validate against the [OATS](https://oatschema.org) `document-extraction` schema.
24
+ * **Interactive HTML Export:** Outputs can be exported to interactive HTML wireframes via the Dorsal CLI.
25
+
26
+
27
+ ## Quick Start
28
+
29
+ Run the model directly against a local PDF file:
30
+
31
+ ```bash
32
+ dorsal run dorsalhub/pdf-extractor ./document.pdf
33
+ ```
34
+
35
+ ### Configuration Options
36
+
37
+ In the CLI, you can pass options to the model using the `--opt` (or `-o`) flag.
38
+
39
+ Example: Run the extractor with OCR fallback enabled for a French language document:
40
+
41
+ ```bash
42
+ dorsal run dorsalhub/pdf-extractor ./document.pdf --opt use_ocr=true --opt ocr_language=fra
43
+ ```
44
+
45
+ **Options:**
46
+
47
+ * `strict` (default: `false`): Fail on a page with a zero or negative size, instead of clamping its boxes.
48
+ * `use_ocr` (default: `false`): Run Tesseract OCR on pages where no native text is found.
49
+ * `ocr_language` (default: `"eng"`): The Tesseract language code for OCR.
50
+ * `password` (no default): The password for an encrypted PDF. It isn't set in `model_config.toml`, so pass it with `--opt password=...` when you need it.
51
+
52
+ OCR needs the `ocr` extra (`pip install 'dorsal-pdf-extractor[ocr]'`, which installs `pytesseract`) and the [Tesseract](https://tesseract-ocr.github.io/tessdoc/Installation.html) binary on your `PATH`.
53
+
54
+ ### Output Formats & Exporting
55
+
56
+ By default, the CLI outputs a validated JSON record to the current working directory.
57
+
58
+ You can export to other formats right from the CLI. For example, exporting to HTML:
59
+
60
+ ```bash
61
+ dorsal run dorsalhub/pdf-extractor ./document.pdf --export=html
62
+ ```
63
+
64
+ ## Output
65
+
66
+ This model produces a file annotation conforming to the [OATS](https://oatschema.org) (Open Annotation Task Schemas) Document Extraction schema:
67
+
68
+ * **Schema ID:** `open/document-extraction` (v0.8.0, pinned in `model_config.toml`)
69
+ * **Key Fields:**
70
+ * `extraction_type`: The type of extraction: `boxes`, `text` (OCR only) or `mixed`.
71
+ * `unit`: `per_mille`. Box coordinates run from 0 to 1000 across the page, from the top-left corner.
72
+ * `page_width` / `page_height`: The size of the pages in points, as Dorsal reports it (whole numbers for ordinary pages). A single number when every page has the same size, otherwise a list of sizes with their pages. A page whose size is reported as 0 is left out of the list.
73
+ * `blocks`: One block per run of text that pdfium reports as a single rectangle (roughly one line), with `id`, `block_type`, `text`, `page_number` and, for native text, `box`. OCR gives one `text` block per page, with no box.
74
+ * `attributes`: `chunk_type`, `start_page` and `end_page`. Dorsal uses these when it splits a large record into chunks.
75
+
76
+ ### Block IDs
77
+
78
+ Each block's `id` is `p<page>-<hash>-<n>`, for example `p1-75690e15d48c-1`:
79
+
80
+ * `<page>` is the block's `page_number`;
81
+ * `<hash>` is the first 12 hexadecimal characters of the SHA-256 digest of the block's `text`, encoded as UTF-8;
82
+ * `<n>` counts, from 1, the blocks in the record with the same page and hash, in record order. It tells apart blocks with the same text on the same page.
83
+
84
+ The ids are unique within a record, including across the chunks Dorsal splits a large record into, and can be recomputed from the record alone. The same file, extracted with the same versions of this model, Dorsal, pypdfium2 and (for OCR) Tesseract, and the same options, always gives the same ids.
85
+
86
+ A block's id changes when its page or text changes, or when a block with the same text is added or removed before it on the same page. A change to a block's box alone, or to other blocks' text, leaves it unchanged.
87
+
88
+ ## Development
89
+
90
+ ### Running Tests
91
+
92
+ This repository uses `pytest` for integration testing, and `ruff` and `mypy` for linting.
93
+
94
+ ```bash
95
+ uv sync --extra ocr
96
+ uv run pytest
97
+ uv run ruff check .
98
+ uv run mypy
99
+ ```
100
+
101
+ The OCR test is skipped unless the Tesseract binary is installed.
102
+
103
+ ## License
104
+
105
+ This project is licensed under the Apache 2.0 License.
@@ -0,0 +1,92 @@
1
+ # Dorsal PDF Extractor
2
+
3
+ Fast, deterministic PDF extraction using [`pdfium`](https://pdfium.googlesource.com/pdfium/). Get native text and bounding boxes without the overhead of heavy AI layout models. Tesseract OCR fallback for scanned pages.
4
+
5
+ ## Features
6
+
7
+ * **Native Extraction:** Extracts text and its bounding boxes directly from the PDF document.
8
+ * **Tesseract OCR Fallback:** Optional optical character recognition (OCR) for scanned or empty pages.
9
+ * **Stable Block IDs:** Extracting the same file again gives the same block ids, so annotations that refer to a block keep working.
10
+ * **Schema Compliant:** Outputs records that validate against the [OATS](https://oatschema.org) `document-extraction` schema.
11
+ * **Interactive HTML Export:** Outputs can be exported to interactive HTML wireframes via the Dorsal CLI.
12
+
13
+
14
+ ## Quick Start
15
+
16
+ Run the model directly against a local PDF file:
17
+
18
+ ```bash
19
+ dorsal run dorsalhub/pdf-extractor ./document.pdf
20
+ ```
21
+
22
+ ### Configuration Options
23
+
24
+ In the CLI, you can pass options to the model using the `--opt` (or `-o`) flag.
25
+
26
+ Example: Run the extractor with OCR fallback enabled for a French language document:
27
+
28
+ ```bash
29
+ dorsal run dorsalhub/pdf-extractor ./document.pdf --opt use_ocr=true --opt ocr_language=fra
30
+ ```
31
+
32
+ **Options:**
33
+
34
+ * `strict` (default: `false`): Fail on a page with a zero or negative size, instead of clamping its boxes.
35
+ * `use_ocr` (default: `false`): Run Tesseract OCR on pages where no native text is found.
36
+ * `ocr_language` (default: `"eng"`): The Tesseract language code for OCR.
37
+ * `password` (no default): The password for an encrypted PDF. It isn't set in `model_config.toml`, so pass it with `--opt password=...` when you need it.
38
+
39
+ OCR needs the `ocr` extra (`pip install 'dorsal-pdf-extractor[ocr]'`, which installs `pytesseract`) and the [Tesseract](https://tesseract-ocr.github.io/tessdoc/Installation.html) binary on your `PATH`.
40
+
41
+ ### Output Formats & Exporting
42
+
43
+ By default, the CLI outputs a validated JSON record to the current working directory.
44
+
45
+ You can export to other formats right from the CLI. For example, exporting to HTML:
46
+
47
+ ```bash
48
+ dorsal run dorsalhub/pdf-extractor ./document.pdf --export=html
49
+ ```
50
+
51
+ ## Output
52
+
53
+ This model produces a file annotation conforming to the [OATS](https://oatschema.org) (Open Annotation Task Schemas) Document Extraction schema:
54
+
55
+ * **Schema ID:** `open/document-extraction` (v0.8.0, pinned in `model_config.toml`)
56
+ * **Key Fields:**
57
+ * `extraction_type`: The type of extraction: `boxes`, `text` (OCR only) or `mixed`.
58
+ * `unit`: `per_mille`. Box coordinates run from 0 to 1000 across the page, from the top-left corner.
59
+ * `page_width` / `page_height`: The size of the pages in points, as Dorsal reports it (whole numbers for ordinary pages). A single number when every page has the same size, otherwise a list of sizes with their pages. A page whose size is reported as 0 is left out of the list.
60
+ * `blocks`: One block per run of text that pdfium reports as a single rectangle (roughly one line), with `id`, `block_type`, `text`, `page_number` and, for native text, `box`. OCR gives one `text` block per page, with no box.
61
+ * `attributes`: `chunk_type`, `start_page` and `end_page`. Dorsal uses these when it splits a large record into chunks.
62
+
63
+ ### Block IDs
64
+
65
+ Each block's `id` is `p<page>-<hash>-<n>`, for example `p1-75690e15d48c-1`:
66
+
67
+ * `<page>` is the block's `page_number`;
68
+ * `<hash>` is the first 12 hexadecimal characters of the SHA-256 digest of the block's `text`, encoded as UTF-8;
69
+ * `<n>` counts, from 1, the blocks in the record with the same page and hash, in record order. It tells apart blocks with the same text on the same page.
70
+
71
+ The ids are unique within a record, including across the chunks Dorsal splits a large record into, and can be recomputed from the record alone. The same file, extracted with the same versions of this model, Dorsal, pypdfium2 and (for OCR) Tesseract, and the same options, always gives the same ids.
72
+
73
+ A block's id changes when its page or text changes, or when a block with the same text is added or removed before it on the same page. A change to a block's box alone, or to other blocks' text, leaves it unchanged.
74
+
75
+ ## Development
76
+
77
+ ### Running Tests
78
+
79
+ This repository uses `pytest` for integration testing, and `ruff` and `mypy` for linting.
80
+
81
+ ```bash
82
+ uv sync --extra ocr
83
+ uv run pytest
84
+ uv run ruff check .
85
+ uv run mypy
86
+ ```
87
+
88
+ The OCR test is skipped unless the Tesseract binary is installed.
89
+
90
+ ## License
91
+
92
+ This project is licensed under the Apache 2.0 License.
@@ -0,0 +1,3 @@
1
+ from .model import PdfExtractor
2
+
3
+ __all__ = ["PdfExtractor"]
@@ -0,0 +1,218 @@
1
+ # Copyright 2026 Dorsal Hub LTD
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import hashlib
16
+ import logging
17
+ import re
18
+ from importlib.metadata import version
19
+ from typing import Any
20
+
21
+ from dorsal.common.model import AnnotationModel
22
+ from dorsal.file.preprocessing.pdf import extract_pdf_layout_per_mille, ocr_extract_pdf_text
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ MAX_TEXT_LENGTH = 4096
27
+ BLOCK_ID_HASH_LENGTH = 12
28
+
29
+
30
+ def block_id_prefix(page_number: int, text: str) -> str:
31
+ """Return the part of a block id that comes from the block's page and text.
32
+
33
+ The prefix is ``p<page_number>-<hash>``, where ``<hash>`` is the first 12
34
+ hexadecimal characters of the SHA-256 digest of the block's UTF-8 text.
35
+ """
36
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:BLOCK_ID_HASH_LENGTH]
37
+ return f"p{page_number}-{digest}"
38
+
39
+
40
+ def assign_block_ids(blocks: list[dict[str, Any]]) -> None:
41
+ """Give each block a deterministic id that is unique within the list.
42
+
43
+ A block's id is ``<prefix>-<n>``, where ``<prefix>`` comes from
44
+ :func:`block_id_prefix` and ``<n>`` counts the blocks, in list order, that
45
+ share that prefix, starting at 1. The ids can be recomputed from a record's
46
+ blocks alone.
47
+ """
48
+ seen: dict[str, int] = {}
49
+ for block in blocks:
50
+ prefix = block_id_prefix(block["page_number"], block["text"])
51
+ seen[prefix] = seen.get(prefix, 0) + 1
52
+ block["id"] = f"{prefix}-{seen[prefix]}"
53
+
54
+
55
+ class PdfExtractor(AnnotationModel):
56
+ id = "github:dorsalhub/pdf-extractor"
57
+ version = version("dorsal-pdf-extractor")
58
+
59
+ _RX_CONTROL_CHARS = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]+")
60
+
61
+ @staticmethod
62
+ def _format_dimension(dim_map: dict[int | float, list[int]], page_count: int) -> Any:
63
+ """Format a page size map as one number, or as a list of sizes with their pages."""
64
+ if not dim_map:
65
+ return None
66
+ covered = sum(len(pages) for pages in dim_map.values())
67
+ if len(dim_map) == 1 and covered == page_count:
68
+ return next(iter(dim_map))
69
+ return [{"value": v, "pages": p} for v, p in dim_map.items()]
70
+
71
+ def _build_record(
72
+ self,
73
+ blocks: list[dict[str, Any]],
74
+ page_numbers: list[int],
75
+ global_widths: dict[int | float, list[int]],
76
+ global_heights: dict[int | float, list[int]],
77
+ ) -> dict[str, Any]:
78
+ """Assemble the extracted blocks and page sizes into a `document-extraction` record."""
79
+ has_boxes = any(b.get("block_type") == "box" for b in blocks)
80
+ has_text = any(b.get("block_type") == "text" for b in blocks)
81
+
82
+ if has_boxes and has_text:
83
+ extraction_type = "mixed"
84
+ elif has_text:
85
+ extraction_type = "text"
86
+ else:
87
+ extraction_type = "boxes"
88
+
89
+ record: dict[str, Any] = {
90
+ "extraction_type": extraction_type,
91
+ "producer": f"pdf-extractor-v{self.version}",
92
+ "blocks": blocks,
93
+ }
94
+
95
+ if extraction_type in ("boxes", "mixed"):
96
+ record["unit"] = "per_mille"
97
+
98
+ page_width = self._format_dimension(global_widths, len(page_numbers))
99
+ if page_width is not None:
100
+ record["page_width"] = page_width
101
+
102
+ page_height = self._format_dimension(global_heights, len(page_numbers))
103
+ if page_height is not None:
104
+ record["page_height"] = page_height
105
+
106
+ if page_numbers:
107
+ record["attributes"] = {
108
+ "chunk_type": "page_range",
109
+ "start_page": min(page_numbers),
110
+ "end_page": max(page_numbers),
111
+ }
112
+
113
+ return record
114
+
115
+ def _clean_text(self, text: str, page_number: int) -> str:
116
+ """Strip control characters and surrounding whitespace, and cap the length."""
117
+ clean_text = self._RX_CONTROL_CHARS.sub("", text).strip()
118
+ if len(clean_text) > MAX_TEXT_LENGTH:
119
+ self.log_debug(
120
+ "Truncating text in block on page %s (length %d > %d limit). Begins: %s",
121
+ page_number,
122
+ len(clean_text),
123
+ MAX_TEXT_LENGTH,
124
+ clean_text[:50],
125
+ )
126
+ clean_text = clean_text[:MAX_TEXT_LENGTH]
127
+ return clean_text
128
+
129
+ def main(
130
+ self,
131
+ password: str | None = None,
132
+ strict: bool = False,
133
+ use_ocr: bool = False,
134
+ ocr_language: str = "eng",
135
+ ) -> dict[str, Any] | None:
136
+ """
137
+ Dorsal model for deterministic PDF text and layout extraction.
138
+
139
+ Args:
140
+ password (str | None): Optional password for opening an encrypted PDF.
141
+ strict (bool): If True, fails on a page with a zero or negative size instead of clamping its boxes.
142
+ use_ocr (bool): If True, runs Tesseract OCR on pages with no native text.
143
+ ocr_language (str): The Tesseract language code (e.g., 'eng').
144
+
145
+ Returns:
146
+ dict[str, Any] | None: A single `document-extraction` record for the whole
147
+ document, or None on failure. Dorsal splits it into chunks if it is
148
+ too large for the schema.
149
+ """
150
+ try:
151
+ pages = extract_pdf_layout_per_mille(self.file_path, password=password, strict=strict)
152
+ except Exception as e:
153
+ self.set_error(f"PDF extraction failed: {e}")
154
+ return None
155
+
156
+ all_blocks: list[dict[str, Any]] = []
157
+ page_numbers: list[int] = []
158
+ global_page_widths_map: dict[int | float, list[int]] = {}
159
+ global_page_heights_map: dict[int | float, list[int]] = {}
160
+ empty_pages: list[int] = []
161
+
162
+ for page in pages:
163
+ page_numbers.append(page.page_number)
164
+ if page.width > 0:
165
+ global_page_widths_map.setdefault(page.width, []).append(page.page_number)
166
+ if page.height > 0:
167
+ global_page_heights_map.setdefault(page.height, []).append(page.page_number)
168
+
169
+ if not page.tokens:
170
+ empty_pages.append(page.page_number)
171
+ continue
172
+
173
+ for token in page.tokens:
174
+ clean_text = self._clean_text(token.text, page.page_number)
175
+ if not clean_text:
176
+ continue
177
+
178
+ x0, y0, x1, y1 = token.box
179
+ all_blocks.append(
180
+ {
181
+ "id": "",
182
+ "block_type": "box",
183
+ "text": clean_text,
184
+ "page_number": page.page_number,
185
+ "box": {
186
+ "x": x0,
187
+ "y": y0,
188
+ "width": max(0, x1 - x0),
189
+ "height": max(0, y1 - y0),
190
+ },
191
+ }
192
+ )
193
+
194
+ if use_ocr and empty_pages:
195
+ self.log_debug("Running fallback OCR on %d empty pages...", len(empty_pages))
196
+ try:
197
+ ocr_results = ocr_extract_pdf_text(self.file_path, language=ocr_language, password=password)
198
+
199
+ for page_num in empty_pages:
200
+ ocr_index = page_num - 1
201
+ if ocr_index < len(ocr_results):
202
+ text = self._clean_text(ocr_results[ocr_index], page_num)
203
+ if text:
204
+ all_blocks.append(
205
+ {
206
+ "id": "",
207
+ "block_type": "text",
208
+ "text": text,
209
+ "page_number": page_num,
210
+ }
211
+ )
212
+ except Exception as e:
213
+ self.log_warning("Fallback OCR failed: %s", e)
214
+
215
+ all_blocks.sort(key=lambda x: x["page_number"])
216
+ assign_block_ids(all_blocks)
217
+
218
+ return self._build_record(all_blocks, page_numbers, global_page_widths_map, global_page_heights_map)