evupdf 0.1.0__py3-none-any.whl
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.
- evupdf/__init__.py +47 -0
- evupdf/client.py +79 -0
- evupdf/config.py +31 -0
- evupdf/exceptions.py +31 -0
- evupdf/extractors/__init__.py +1 -0
- evupdf/extractors/base.py +23 -0
- evupdf/extractors/pymupdf.py +304 -0
- evupdf/models/__init__.py +16 -0
- evupdf/models/block.py +39 -0
- evupdf/models/document.py +24 -0
- evupdf/models/extraction.py +87 -0
- evupdf/models/page.py +35 -0
- evupdf/py.typed +0 -0
- evupdf/utils/__init__.py +1 -0
- evupdf/utils/dates.py +96 -0
- evupdf/utils/files.py +54 -0
- evupdf/utils/hashing.py +16 -0
- evupdf-0.1.0.dist-info/METADATA +158 -0
- evupdf-0.1.0.dist-info/RECORD +21 -0
- evupdf-0.1.0.dist-info/WHEEL +4 -0
- evupdf-0.1.0.dist-info/licenses/LICENSE +21 -0
evupdf/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""EvuPDF extracts structured, traceable data from PDFs."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from evupdf.client import PDFExtractor
|
|
6
|
+
from evupdf.config import ExtractorConfig
|
|
7
|
+
from evupdf.exceptions import (
|
|
8
|
+
EncryptedPDFError,
|
|
9
|
+
EvuPDFError,
|
|
10
|
+
FileValidationError,
|
|
11
|
+
InvalidPDFError,
|
|
12
|
+
PDFTooLargeError,
|
|
13
|
+
TooManyPagesError,
|
|
14
|
+
)
|
|
15
|
+
from evupdf.models import (
|
|
16
|
+
SCHEMA_VERSION,
|
|
17
|
+
BlockSource,
|
|
18
|
+
DocumentMetadata,
|
|
19
|
+
ExtractionResult,
|
|
20
|
+
ExtractionWarning,
|
|
21
|
+
Page,
|
|
22
|
+
TextBlock,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
__version__ = version("evupdf")
|
|
27
|
+
except PackageNotFoundError:
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"SCHEMA_VERSION",
|
|
32
|
+
"BlockSource",
|
|
33
|
+
"DocumentMetadata",
|
|
34
|
+
"EncryptedPDFError",
|
|
35
|
+
"EvuPDFError",
|
|
36
|
+
"ExtractionResult",
|
|
37
|
+
"ExtractionWarning",
|
|
38
|
+
"ExtractorConfig",
|
|
39
|
+
"FileValidationError",
|
|
40
|
+
"InvalidPDFError",
|
|
41
|
+
"PDFExtractor",
|
|
42
|
+
"PDFTooLargeError",
|
|
43
|
+
"Page",
|
|
44
|
+
"TextBlock",
|
|
45
|
+
"TooManyPagesError",
|
|
46
|
+
"__version__",
|
|
47
|
+
]
|
evupdf/client.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""The public extraction client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from evupdf.config import ExtractorConfig
|
|
8
|
+
from evupdf.extractors.pymupdf import PyMuPDFExtractor
|
|
9
|
+
from evupdf.models.extraction import ExtractionResult
|
|
10
|
+
from evupdf.utils.files import validate_pdf_path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PDFExtractor:
|
|
14
|
+
"""Extract text, pages, and layout from a local digital PDF.
|
|
15
|
+
|
|
16
|
+
Extraction reads the file on disk. It does not call a network service, an
|
|
17
|
+
OCR engine, or an AI provider. Pages with little or no native text are
|
|
18
|
+
flagged with an ``ocr_recommended`` warning; OCR itself is not run.
|
|
19
|
+
|
|
20
|
+
Example:
|
|
21
|
+
>>> from evupdf import PDFExtractor
|
|
22
|
+
>>> document = PDFExtractor().extract("invoice.pdf")
|
|
23
|
+
>>> document.save_json("invoice.json")
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, config: ExtractorConfig | None = None) -> None:
|
|
27
|
+
self.config = config if config is not None else ExtractorConfig()
|
|
28
|
+
self._backend = PyMuPDFExtractor()
|
|
29
|
+
|
|
30
|
+
def extract(
|
|
31
|
+
self,
|
|
32
|
+
path: str | Path,
|
|
33
|
+
*,
|
|
34
|
+
password: str | None = None,
|
|
35
|
+
preserve_coordinates: bool | None = None,
|
|
36
|
+
) -> ExtractionResult:
|
|
37
|
+
"""Extract ``path`` and return a validated raw result.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
path: Filesystem path to a ``.pdf`` file.
|
|
41
|
+
password: User password for an encrypted PDF. Omit this for a
|
|
42
|
+
PDF that is not password protected. The password is not
|
|
43
|
+
copied into the result or its JSON.
|
|
44
|
+
preserve_coordinates: Include a bounding box on each text block.
|
|
45
|
+
``None`` uses ``config.preserve_coordinates``.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
The raw document, including page geometry, text blocks, metadata,
|
|
49
|
+
and warnings.
|
|
50
|
+
|
|
51
|
+
Coordinates are PDF points (1/72 inch) on the displayed page. The
|
|
52
|
+
origin is the top-left corner, x increases to the right, and y
|
|
53
|
+
increases downward. ``page.width`` and ``page.height`` use that same
|
|
54
|
+
space, after page rotation.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
FileValidationError: The path is missing, not a file, or not a
|
|
58
|
+
``.pdf`` path.
|
|
59
|
+
PDFTooLargeError: The file exceeds ``config.max_file_size_bytes``.
|
|
60
|
+
InvalidPDFError: The file is empty, missing a PDF header, or
|
|
61
|
+
PyMuPDF cannot read it.
|
|
62
|
+
EncryptedPDFError: A password is required and was missing or wrong.
|
|
63
|
+
TooManyPagesError: The document exceeds ``config.max_page_count``.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
validated = validate_pdf_path(
|
|
67
|
+
path,
|
|
68
|
+
max_file_size_bytes=self.config.max_file_size_bytes,
|
|
69
|
+
)
|
|
70
|
+
if preserve_coordinates is None:
|
|
71
|
+
keep_coordinates = self.config.preserve_coordinates
|
|
72
|
+
else:
|
|
73
|
+
keep_coordinates = preserve_coordinates
|
|
74
|
+
return self._backend.extract(
|
|
75
|
+
validated,
|
|
76
|
+
password=password,
|
|
77
|
+
config=self.config,
|
|
78
|
+
preserve_coordinates=keep_coordinates,
|
|
79
|
+
)
|
evupdf/config.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Configuration for PDF extraction.
|
|
2
|
+
|
|
3
|
+
Python objects are the supported configuration format. Secrets are not part of
|
|
4
|
+
extraction configuration because raw extraction does not call external services.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ExtractorConfig(BaseModel):
|
|
13
|
+
"""Limits and extraction options for :class:`evupdf.PDFExtractor`.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
max_file_size_bytes: Reject files larger than this many bytes.
|
|
17
|
+
max_page_count: Reject documents with more pages than this.
|
|
18
|
+
max_page_dimension_points: Skip text extraction on a page whose
|
|
19
|
+
displayed width or height exceeds this size, in PDF points.
|
|
20
|
+
ocr_min_text_chars: Flag a page when its extracted text has fewer
|
|
21
|
+
non-whitespace characters than this. ``0`` disables the flag.
|
|
22
|
+
preserve_coordinates: Include a bounding box on each text block.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
26
|
+
|
|
27
|
+
max_file_size_bytes: int = Field(default=50 * 1024 * 1024, gt=0)
|
|
28
|
+
max_page_count: int = Field(default=500, gt=0)
|
|
29
|
+
max_page_dimension_points: float = Field(default=14_400, gt=0)
|
|
30
|
+
ocr_min_text_chars: int = Field(default=20, ge=0)
|
|
31
|
+
preserve_coordinates: bool = True
|
evupdf/exceptions.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Typed errors raised by EvuPDF.
|
|
2
|
+
|
|
3
|
+
Callers can catch :class:`EvuPDFError` for any library failure, or a subclass
|
|
4
|
+
when they want to handle a specific case.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class EvuPDFError(Exception):
|
|
11
|
+
"""Base class for errors raised by EvuPDF."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FileValidationError(EvuPDFError):
|
|
15
|
+
"""The input path is missing, not a file, or has the wrong extension."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class InvalidPDFError(EvuPDFError):
|
|
19
|
+
"""The file is empty, truncated, or not a readable PDF."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class EncryptedPDFError(EvuPDFError):
|
|
23
|
+
"""The PDF requires a password, or the supplied password was rejected."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PDFTooLargeError(EvuPDFError):
|
|
27
|
+
"""The PDF exceeds the configured maximum file size."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TooManyPagesError(EvuPDFError):
|
|
31
|
+
"""The PDF exceeds the configured maximum page count."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""PDF extraction backends."""
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Backend interface used by :class:`evupdf.PDFExtractor`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
from evupdf.config import ExtractorConfig
|
|
9
|
+
from evupdf.models.extraction import ExtractionResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PDFBackend(Protocol):
|
|
13
|
+
"""Extract a validated local PDF into the raw result model."""
|
|
14
|
+
|
|
15
|
+
def extract(
|
|
16
|
+
self,
|
|
17
|
+
path: Path,
|
|
18
|
+
*,
|
|
19
|
+
password: str | None,
|
|
20
|
+
config: ExtractorConfig,
|
|
21
|
+
preserve_coordinates: bool,
|
|
22
|
+
) -> ExtractionResult:
|
|
23
|
+
"""Extract ``path``. The path has already passed file validation."""
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Native text and layout extraction with PyMuPDF.
|
|
2
|
+
|
|
3
|
+
The backend reads text and geometry only. It does not run PDF JavaScript,
|
|
4
|
+
open attachments, or follow links.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import pymupdf
|
|
13
|
+
|
|
14
|
+
from evupdf.config import ExtractorConfig
|
|
15
|
+
from evupdf.exceptions import EncryptedPDFError, InvalidPDFError, TooManyPagesError
|
|
16
|
+
from evupdf.models.block import BlockSource, TextBlock
|
|
17
|
+
from evupdf.models.document import DocumentMetadata
|
|
18
|
+
from evupdf.models.extraction import ExtractionResult, ExtractionWarning
|
|
19
|
+
from evupdf.models.page import Page
|
|
20
|
+
from evupdf.utils.dates import normalize_pdf_date
|
|
21
|
+
from evupdf.utils.hashing import sha256_file
|
|
22
|
+
|
|
23
|
+
ENGINE = "pymupdf"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PyMuPDFExtractor:
|
|
27
|
+
"""Extract digital PDF text with PyMuPDF."""
|
|
28
|
+
|
|
29
|
+
def extract(
|
|
30
|
+
self,
|
|
31
|
+
path: Path,
|
|
32
|
+
*,
|
|
33
|
+
password: str | None,
|
|
34
|
+
config: ExtractorConfig,
|
|
35
|
+
preserve_coordinates: bool,
|
|
36
|
+
) -> ExtractionResult:
|
|
37
|
+
file_hash = sha256_file(path)
|
|
38
|
+
try:
|
|
39
|
+
document = pymupdf.open(path)
|
|
40
|
+
except Exception as exc:
|
|
41
|
+
raise InvalidPDFError(
|
|
42
|
+
f"Could not open '{path.name}' as a PDF: {exc}. "
|
|
43
|
+
"The file may be truncated or malformed."
|
|
44
|
+
) from exc
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
return _extract_open_document(
|
|
48
|
+
document,
|
|
49
|
+
path=path,
|
|
50
|
+
file_hash=file_hash,
|
|
51
|
+
password=password,
|
|
52
|
+
config=config,
|
|
53
|
+
preserve_coordinates=preserve_coordinates,
|
|
54
|
+
)
|
|
55
|
+
finally:
|
|
56
|
+
document.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _extract_open_document(
|
|
60
|
+
document: Any,
|
|
61
|
+
*,
|
|
62
|
+
path: Path,
|
|
63
|
+
file_hash: str,
|
|
64
|
+
password: str | None,
|
|
65
|
+
config: ExtractorConfig,
|
|
66
|
+
preserve_coordinates: bool,
|
|
67
|
+
) -> ExtractionResult:
|
|
68
|
+
if document.needs_pass and (password is None or not document.authenticate(password)):
|
|
69
|
+
raise EncryptedPDFError(
|
|
70
|
+
f"'{path.name}' is encrypted. Pass the user password to extract(), "
|
|
71
|
+
"or export an unprotected copy of the PDF."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
page_count = int(document.page_count)
|
|
75
|
+
if page_count > config.max_page_count:
|
|
76
|
+
raise TooManyPagesError(
|
|
77
|
+
f"'{path.name}' has {page_count} pages, which exceeds the configured "
|
|
78
|
+
f"limit of {config.max_page_count}. Raise ExtractorConfig.max_page_count "
|
|
79
|
+
"if this document is trusted and should be processed."
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
metadata, warnings = _read_metadata(document)
|
|
83
|
+
pages: list[Page] = []
|
|
84
|
+
for index in range(page_count):
|
|
85
|
+
page, page_warnings = _extract_page(
|
|
86
|
+
document[index],
|
|
87
|
+
page_number=index + 1,
|
|
88
|
+
config=config,
|
|
89
|
+
preserve_coordinates=preserve_coordinates,
|
|
90
|
+
)
|
|
91
|
+
pages.append(page)
|
|
92
|
+
warnings.extend(page_warnings)
|
|
93
|
+
|
|
94
|
+
return ExtractionResult(
|
|
95
|
+
document_id=file_hash[:16],
|
|
96
|
+
file_name=path.name,
|
|
97
|
+
file_hash=f"sha256:{file_hash}",
|
|
98
|
+
page_count=len(pages),
|
|
99
|
+
metadata=metadata,
|
|
100
|
+
pages=pages,
|
|
101
|
+
warnings=warnings,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _read_metadata(document: Any) -> tuple[DocumentMetadata, list[ExtractionWarning]]:
|
|
106
|
+
try:
|
|
107
|
+
raw = document.metadata or {}
|
|
108
|
+
except Exception as exc:
|
|
109
|
+
warning = ExtractionWarning(
|
|
110
|
+
code="metadata_unavailable",
|
|
111
|
+
message=f"Document metadata could not be read: {exc}",
|
|
112
|
+
)
|
|
113
|
+
return DocumentMetadata(), [warning]
|
|
114
|
+
|
|
115
|
+
if not isinstance(raw, dict):
|
|
116
|
+
warning = ExtractionWarning(
|
|
117
|
+
code="metadata_unavailable",
|
|
118
|
+
message="Document metadata was not a dictionary and was ignored.",
|
|
119
|
+
)
|
|
120
|
+
return DocumentMetadata(), [warning]
|
|
121
|
+
|
|
122
|
+
metadata = DocumentMetadata(
|
|
123
|
+
title=_clean_text(raw.get("title")),
|
|
124
|
+
author=_clean_text(raw.get("author")),
|
|
125
|
+
creation_date=normalize_pdf_date(_clean_text(raw.get("creationDate"))),
|
|
126
|
+
modification_date=normalize_pdf_date(_clean_text(raw.get("modDate"))),
|
|
127
|
+
subject=_clean_text(raw.get("subject")),
|
|
128
|
+
keywords=_clean_text(raw.get("keywords")),
|
|
129
|
+
creator=_clean_text(raw.get("creator")),
|
|
130
|
+
producer=_clean_text(raw.get("producer")),
|
|
131
|
+
)
|
|
132
|
+
return metadata, []
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _extract_page(
|
|
136
|
+
page: Any,
|
|
137
|
+
*,
|
|
138
|
+
page_number: int,
|
|
139
|
+
config: ExtractorConfig,
|
|
140
|
+
preserve_coordinates: bool,
|
|
141
|
+
) -> tuple[Page, list[ExtractionWarning]]:
|
|
142
|
+
warnings: list[ExtractionWarning] = []
|
|
143
|
+
try:
|
|
144
|
+
width = round(float(page.rect.width), 2)
|
|
145
|
+
height = round(float(page.rect.height), 2)
|
|
146
|
+
rotation = int(page.rotation)
|
|
147
|
+
except Exception as exc:
|
|
148
|
+
warnings.append(
|
|
149
|
+
ExtractionWarning(
|
|
150
|
+
code="page_extraction_failed",
|
|
151
|
+
message=f"Page {page_number} geometry could not be read: {exc}",
|
|
152
|
+
page_number=page_number,
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
return (
|
|
156
|
+
Page(
|
|
157
|
+
page_number=page_number,
|
|
158
|
+
width=0.0,
|
|
159
|
+
height=0.0,
|
|
160
|
+
rotation=0,
|
|
161
|
+
ocr_recommended=True,
|
|
162
|
+
blocks=[],
|
|
163
|
+
),
|
|
164
|
+
warnings,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
if width > config.max_page_dimension_points or height > config.max_page_dimension_points:
|
|
168
|
+
warnings.append(
|
|
169
|
+
ExtractionWarning(
|
|
170
|
+
code="page_dimension_exceeded",
|
|
171
|
+
message=(
|
|
172
|
+
f"Page {page_number} is {width:.1f} by {height:.1f} points, which exceeds "
|
|
173
|
+
f"the configured limit of {config.max_page_dimension_points:.1f} points. "
|
|
174
|
+
"Text was not extracted from this page."
|
|
175
|
+
),
|
|
176
|
+
page_number=page_number,
|
|
177
|
+
)
|
|
178
|
+
)
|
|
179
|
+
return (
|
|
180
|
+
Page(
|
|
181
|
+
page_number=page_number,
|
|
182
|
+
width=width,
|
|
183
|
+
height=height,
|
|
184
|
+
rotation=rotation,
|
|
185
|
+
ocr_recommended=True,
|
|
186
|
+
blocks=[],
|
|
187
|
+
),
|
|
188
|
+
warnings,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
blocks = _text_blocks(
|
|
193
|
+
page,
|
|
194
|
+
page_number=page_number,
|
|
195
|
+
preserve_coordinates=preserve_coordinates,
|
|
196
|
+
)
|
|
197
|
+
except Exception as exc:
|
|
198
|
+
warnings.append(
|
|
199
|
+
ExtractionWarning(
|
|
200
|
+
code="page_extraction_failed",
|
|
201
|
+
message=f"Page {page_number} text could not be extracted: {exc}",
|
|
202
|
+
page_number=page_number,
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
blocks = []
|
|
206
|
+
|
|
207
|
+
extraction_failed = any(warning.code == "page_extraction_failed" for warning in warnings)
|
|
208
|
+
text = "\n".join(block.text for block in blocks)
|
|
209
|
+
ocr_recommended = True if extraction_failed else _needs_ocr(text, config.ocr_min_text_chars)
|
|
210
|
+
if ocr_recommended and not extraction_failed:
|
|
211
|
+
warnings.append(
|
|
212
|
+
ExtractionWarning(
|
|
213
|
+
code="ocr_recommended",
|
|
214
|
+
message=(
|
|
215
|
+
f"Page {page_number} has little or no extractable text. "
|
|
216
|
+
"It may be scanned or image-only, and OCR may be needed."
|
|
217
|
+
),
|
|
218
|
+
page_number=page_number,
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
return (
|
|
223
|
+
Page(
|
|
224
|
+
page_number=page_number,
|
|
225
|
+
width=width,
|
|
226
|
+
height=height,
|
|
227
|
+
rotation=rotation,
|
|
228
|
+
ocr_recommended=ocr_recommended,
|
|
229
|
+
blocks=blocks,
|
|
230
|
+
),
|
|
231
|
+
warnings,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _text_blocks(
|
|
236
|
+
page: Any,
|
|
237
|
+
*,
|
|
238
|
+
page_number: int,
|
|
239
|
+
preserve_coordinates: bool,
|
|
240
|
+
) -> list[TextBlock]:
|
|
241
|
+
# sort=False keeps PyMuPDF's content-stream order. reading_order records
|
|
242
|
+
# that order; it is not a layout-normalized reading order.
|
|
243
|
+
raw = page.get_text("dict", sort=False)
|
|
244
|
+
if not isinstance(raw, dict):
|
|
245
|
+
raise TypeError("PyMuPDF text extraction did not return a dictionary.")
|
|
246
|
+
raw_blocks = raw.get("blocks", [])
|
|
247
|
+
blocks: list[TextBlock] = []
|
|
248
|
+
for raw_block in raw_blocks:
|
|
249
|
+
if not isinstance(raw_block, dict) or raw_block.get("type") != 0:
|
|
250
|
+
continue
|
|
251
|
+
text = _block_text(raw_block)
|
|
252
|
+
if not text.strip():
|
|
253
|
+
continue
|
|
254
|
+
bbox = _bbox(raw_block.get("bbox")) if preserve_coordinates else None
|
|
255
|
+
blocks.append(
|
|
256
|
+
TextBlock(
|
|
257
|
+
block_id=f"p{page_number}_b{len(blocks)}",
|
|
258
|
+
text=text,
|
|
259
|
+
bbox=bbox,
|
|
260
|
+
reading_order=len(blocks),
|
|
261
|
+
source=BlockSource(engine=ENGINE, confidence=None),
|
|
262
|
+
)
|
|
263
|
+
)
|
|
264
|
+
return blocks
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _block_text(block: dict[str, Any]) -> str:
|
|
268
|
+
lines: list[str] = []
|
|
269
|
+
for line in block.get("lines") or []:
|
|
270
|
+
if not isinstance(line, dict):
|
|
271
|
+
continue
|
|
272
|
+
spans: list[str] = []
|
|
273
|
+
for span in line.get("spans") or []:
|
|
274
|
+
if isinstance(span, dict):
|
|
275
|
+
spans.append(str(span.get("text") or ""))
|
|
276
|
+
lines.append("".join(spans))
|
|
277
|
+
return "\n".join(lines).strip()
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _bbox(value: Any) -> tuple[float, float, float, float] | None:
|
|
281
|
+
if not isinstance(value, (list, tuple)) or len(value) != 4:
|
|
282
|
+
return None
|
|
283
|
+
try:
|
|
284
|
+
x0, y0, x1, y1 = (float(part) for part in value)
|
|
285
|
+
except (TypeError, ValueError):
|
|
286
|
+
return None
|
|
287
|
+
return (round(x0, 2), round(y0, 2), round(x1, 2), round(y1, 2))
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _needs_ocr(text: str, minimum_chars: int) -> bool:
|
|
291
|
+
"""Return whether a page has too little native text to trust as complete.
|
|
292
|
+
|
|
293
|
+
This is a character-count heuristic. It is not proof that a page is scanned.
|
|
294
|
+
"""
|
|
295
|
+
|
|
296
|
+
visible = sum(1 for character in text if not character.isspace())
|
|
297
|
+
return visible < minimum_chars
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _clean_text(value: Any) -> str | None:
|
|
301
|
+
if not isinstance(value, str):
|
|
302
|
+
return None
|
|
303
|
+
stripped = value.strip()
|
|
304
|
+
return stripped or None
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Public result models for raw PDF extraction."""
|
|
2
|
+
|
|
3
|
+
from evupdf.models.block import BlockSource, TextBlock
|
|
4
|
+
from evupdf.models.document import DocumentMetadata
|
|
5
|
+
from evupdf.models.extraction import SCHEMA_VERSION, ExtractionResult, ExtractionWarning
|
|
6
|
+
from evupdf.models.page import Page
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"SCHEMA_VERSION",
|
|
10
|
+
"BlockSource",
|
|
11
|
+
"DocumentMetadata",
|
|
12
|
+
"ExtractionResult",
|
|
13
|
+
"ExtractionWarning",
|
|
14
|
+
"Page",
|
|
15
|
+
"TextBlock",
|
|
16
|
+
]
|
evupdf/models/block.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Text blocks and the engine that produced them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BlockSource(BaseModel):
|
|
11
|
+
"""Where a block of text came from.
|
|
12
|
+
|
|
13
|
+
``confidence`` is null for native PDF text. EvuPDF does not invent a score
|
|
14
|
+
when the extractor does not provide one.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
18
|
+
|
|
19
|
+
engine: str
|
|
20
|
+
confidence: float | None = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TextBlock(BaseModel):
|
|
24
|
+
"""One text block on a page, in extraction order.
|
|
25
|
+
|
|
26
|
+
``bbox`` is ``[x0, y0, x1, y1]`` in PDF points. The origin is the top-left
|
|
27
|
+
of the displayed page, x increases to the right, and y increases downward.
|
|
28
|
+
``reading_order`` matches that extraction order. A later release can add a
|
|
29
|
+
separate layout-normalized order without replacing this value.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
33
|
+
|
|
34
|
+
block_id: str
|
|
35
|
+
type: Literal["text"] = "text"
|
|
36
|
+
text: str
|
|
37
|
+
bbox: tuple[float, float, float, float] | None = None
|
|
38
|
+
reading_order: int = Field(ge=0)
|
|
39
|
+
source: BlockSource
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Document-level metadata copied from the PDF information dictionary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DocumentMetadata(BaseModel):
|
|
9
|
+
"""Metadata fields that were present on the PDF.
|
|
10
|
+
|
|
11
|
+
Empty PDF metadata values are returned as ``None``. Dates are ISO 8601
|
|
12
|
+
when EvuPDF can parse them, and the original string otherwise.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
16
|
+
|
|
17
|
+
title: str | None = None
|
|
18
|
+
author: str | None = None
|
|
19
|
+
creation_date: str | None = None
|
|
20
|
+
modification_date: str | None = None
|
|
21
|
+
subject: str | None = None
|
|
22
|
+
keywords: str | None = None
|
|
23
|
+
creator: str | None = None
|
|
24
|
+
producer: str | None = None
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Versioned raw extraction result."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
9
|
+
|
|
10
|
+
from evupdf.exceptions import FileValidationError
|
|
11
|
+
from evupdf.models.document import DocumentMetadata
|
|
12
|
+
from evupdf.models.page import Page
|
|
13
|
+
|
|
14
|
+
SCHEMA_VERSION: Literal["1.0"] = "1.0"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ExtractionWarning(BaseModel):
|
|
18
|
+
"""A machine-readable warning attached to a raw extraction result."""
|
|
19
|
+
|
|
20
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
21
|
+
|
|
22
|
+
code: str
|
|
23
|
+
message: str
|
|
24
|
+
page_number: int | None = Field(default=None, ge=1)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ExtractionResult(BaseModel):
|
|
28
|
+
"""Raw extraction for one PDF.
|
|
29
|
+
|
|
30
|
+
This object is the source evidence. It is not an interpretation of the
|
|
31
|
+
document, and it does not fill missing metadata with guessed values.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
35
|
+
|
|
36
|
+
schema_version: Literal["1.0"] = SCHEMA_VERSION
|
|
37
|
+
document_id: str
|
|
38
|
+
file_name: str
|
|
39
|
+
file_hash: str
|
|
40
|
+
mime_type: Literal["application/pdf"] = "application/pdf"
|
|
41
|
+
page_count: int = Field(ge=0)
|
|
42
|
+
metadata: DocumentMetadata
|
|
43
|
+
pages: list[Page]
|
|
44
|
+
warnings: list[ExtractionWarning] = Field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
@model_validator(mode="after")
|
|
47
|
+
def _pages_match_count(self) -> ExtractionResult:
|
|
48
|
+
if self.page_count != len(self.pages):
|
|
49
|
+
raise ValueError(
|
|
50
|
+
f"page_count is {self.page_count}, but {len(self.pages)} pages were provided."
|
|
51
|
+
)
|
|
52
|
+
expected = list(range(1, len(self.pages) + 1))
|
|
53
|
+
actual = [page.page_number for page in self.pages]
|
|
54
|
+
if actual != expected:
|
|
55
|
+
raise ValueError(f"Page numbers must be 1-based and contiguous, got {actual}.")
|
|
56
|
+
return self
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def text(self) -> str:
|
|
60
|
+
"""Non-empty page text joined by a blank line. This is not included in the JSON."""
|
|
61
|
+
|
|
62
|
+
return "\n\n".join(page.text for page in self.pages if page.text)
|
|
63
|
+
|
|
64
|
+
def to_dict(self) -> dict[str, Any]:
|
|
65
|
+
"""Return JSON-compatible data for this result."""
|
|
66
|
+
|
|
67
|
+
return self.model_dump(mode="json")
|
|
68
|
+
|
|
69
|
+
def to_json(self, *, indent: int | None = 2) -> str:
|
|
70
|
+
"""Serialize this result to a JSON string."""
|
|
71
|
+
|
|
72
|
+
return self.model_dump_json(indent=indent)
|
|
73
|
+
|
|
74
|
+
def save_json(self, path: str | Path, *, indent: int | None = 2) -> None:
|
|
75
|
+
"""Write this result as UTF-8 JSON.
|
|
76
|
+
|
|
77
|
+
Raises:
|
|
78
|
+
FileValidationError: The destination directory does not exist.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
destination = Path(path)
|
|
82
|
+
parent = destination.parent
|
|
83
|
+
if parent != Path(".") and not parent.exists():
|
|
84
|
+
raise FileValidationError(
|
|
85
|
+
f"Output directory does not exist: {parent}. Create it before saving JSON."
|
|
86
|
+
)
|
|
87
|
+
destination.write_text(self.to_json(indent=indent) + "\n", encoding="utf-8")
|
evupdf/models/page.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""A single extracted PDF page."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
8
|
+
|
|
9
|
+
from evupdf.models.block import TextBlock
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Page(BaseModel):
|
|
13
|
+
"""One page of raw extraction.
|
|
14
|
+
|
|
15
|
+
Page numbers are 1-based. ``width`` and ``height`` are the displayed page
|
|
16
|
+
size in PDF points after rotation. ``tables`` is reserved and empty until
|
|
17
|
+
table extraction exists.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
21
|
+
|
|
22
|
+
page_number: int = Field(ge=1)
|
|
23
|
+
width: float = Field(ge=0)
|
|
24
|
+
height: float = Field(ge=0)
|
|
25
|
+
rotation: int = 0
|
|
26
|
+
extraction_method: Literal["pymupdf"] = "pymupdf"
|
|
27
|
+
ocr_recommended: bool
|
|
28
|
+
blocks: list[TextBlock] = Field(default_factory=list)
|
|
29
|
+
tables: list[Any] = Field(default_factory=list)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def text(self) -> str:
|
|
33
|
+
"""Block text joined by newlines, in extraction order."""
|
|
34
|
+
|
|
35
|
+
return "\n".join(block.text for block in self.blocks)
|
evupdf/py.typed
ADDED
|
File without changes
|
evupdf/utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Internal file, hash, and metadata helpers."""
|
evupdf/utils/dates.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""PDF metadata date normalization.
|
|
2
|
+
|
|
3
|
+
PDF dates look like ``D:YYYYMMDDHHmmSSOHH'mm'``. A value that does not match
|
|
4
|
+
that shape is returned unchanged. Missing timezone information is left missing
|
|
5
|
+
rather than assumed to be UTC.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from datetime import date
|
|
12
|
+
|
|
13
|
+
_PDF_DATE = re.compile(
|
|
14
|
+
r"(?P<year>\d{4})"
|
|
15
|
+
r"(?P<month>\d{2})?"
|
|
16
|
+
r"(?P<day>\d{2})?"
|
|
17
|
+
r"(?P<hour>\d{2})?"
|
|
18
|
+
r"(?P<minute>\d{2})?"
|
|
19
|
+
r"(?P<second>\d{2})?"
|
|
20
|
+
r"(?P<tz>Z|[+-]\d{2}'?\d{2}'?|[+-]\d{2})?"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def normalize_pdf_date(value: str | None) -> str | None:
|
|
25
|
+
"""Convert a PDF date string to ISO 8601 when the value is unambiguous."""
|
|
26
|
+
|
|
27
|
+
if value is None:
|
|
28
|
+
return None
|
|
29
|
+
raw = value.strip()
|
|
30
|
+
if not raw:
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
body = raw[2:] if raw.startswith("D:") else raw
|
|
34
|
+
match = _PDF_DATE.fullmatch(body)
|
|
35
|
+
if match is None:
|
|
36
|
+
return raw
|
|
37
|
+
|
|
38
|
+
year = int(match.group("year"))
|
|
39
|
+
month_text = match.group("month")
|
|
40
|
+
day_text = match.group("day")
|
|
41
|
+
if month_text is None or day_text is None:
|
|
42
|
+
return raw
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
parsed = date(year, int(month_text), int(day_text))
|
|
46
|
+
except ValueError:
|
|
47
|
+
return raw
|
|
48
|
+
|
|
49
|
+
hour_text = match.group("hour")
|
|
50
|
+
minute_text = match.group("minute")
|
|
51
|
+
second_text = match.group("second")
|
|
52
|
+
if hour_text is None and minute_text is None and second_text is None:
|
|
53
|
+
timezone = match.group("tz")
|
|
54
|
+
if timezone is not None:
|
|
55
|
+
return raw
|
|
56
|
+
return parsed.isoformat()
|
|
57
|
+
if hour_text is None or minute_text is None or second_text is None:
|
|
58
|
+
return raw
|
|
59
|
+
|
|
60
|
+
hour = int(hour_text)
|
|
61
|
+
minute = int(minute_text)
|
|
62
|
+
second = int(second_text)
|
|
63
|
+
if hour > 23 or minute > 59 or second > 59:
|
|
64
|
+
return raw
|
|
65
|
+
|
|
66
|
+
timezone = _format_timezone(match.group("tz"))
|
|
67
|
+
if match.group("tz") is not None and timezone is None:
|
|
68
|
+
return raw
|
|
69
|
+
|
|
70
|
+
stamp = f"{parsed.isoformat()}T{hour:02d}:{minute:02d}:{second:02d}"
|
|
71
|
+
if timezone is None:
|
|
72
|
+
return stamp
|
|
73
|
+
return f"{stamp}{timezone}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _format_timezone(value: str | None) -> str | None:
|
|
77
|
+
if value is None:
|
|
78
|
+
return None
|
|
79
|
+
if value == "Z":
|
|
80
|
+
return "+00:00"
|
|
81
|
+
digits = value.replace("'", "")
|
|
82
|
+
sign = digits[0]
|
|
83
|
+
if sign not in "+-":
|
|
84
|
+
return None
|
|
85
|
+
numbers = digits[1:]
|
|
86
|
+
if len(numbers) == 2:
|
|
87
|
+
hours = int(numbers)
|
|
88
|
+
minutes = 0
|
|
89
|
+
elif len(numbers) == 4:
|
|
90
|
+
hours = int(numbers[:2])
|
|
91
|
+
minutes = int(numbers[2:])
|
|
92
|
+
else:
|
|
93
|
+
return None
|
|
94
|
+
if hours > 23 or minutes > 59:
|
|
95
|
+
return None
|
|
96
|
+
return f"{sign}{hours:02d}:{minutes:02d}"
|
evupdf/utils/files.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Local PDF path checks.
|
|
2
|
+
|
|
3
|
+
These checks run before PyMuPDF opens the file. They do not execute PDF
|
|
4
|
+
contents, and they only read the file header plus filesystem metadata.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from evupdf.exceptions import FileValidationError, InvalidPDFError, PDFTooLargeError
|
|
12
|
+
|
|
13
|
+
# The PDF specification allows the "%PDF-" marker to appear within the first
|
|
14
|
+
# 1024 bytes so a file can carry a short prefix.
|
|
15
|
+
_HEADER_SCAN_BYTES = 1024
|
|
16
|
+
_PDF_MARKER = b"%PDF-"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def validate_pdf_path(path: str | Path, *, max_file_size_bytes: int) -> Path:
|
|
20
|
+
"""Return a usable PDF path, or raise a typed validation error."""
|
|
21
|
+
|
|
22
|
+
candidate = Path(path)
|
|
23
|
+
if not candidate.exists():
|
|
24
|
+
raise FileValidationError(f"File not found: {candidate}")
|
|
25
|
+
if not candidate.is_file():
|
|
26
|
+
raise FileValidationError(f"Path is not a file: {candidate}")
|
|
27
|
+
if candidate.suffix.lower() != ".pdf":
|
|
28
|
+
extension = candidate.suffix or "no extension"
|
|
29
|
+
raise FileValidationError(
|
|
30
|
+
f"Expected a .pdf file, got '{extension}': {candidate.name}. "
|
|
31
|
+
"Rename the file or pass a path that ends in .pdf."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
size = candidate.stat().st_size
|
|
35
|
+
if size > max_file_size_bytes:
|
|
36
|
+
raise PDFTooLargeError(
|
|
37
|
+
f"'{candidate.name}' is {size} bytes, which exceeds the configured "
|
|
38
|
+
f"limit of {max_file_size_bytes} bytes. Raise ExtractorConfig.max_file_size_bytes "
|
|
39
|
+
"if this file is trusted and should be processed."
|
|
40
|
+
)
|
|
41
|
+
if size == 0:
|
|
42
|
+
raise InvalidPDFError(f"'{candidate.name}' is empty and is not a readable PDF.")
|
|
43
|
+
if not _has_pdf_header(candidate):
|
|
44
|
+
raise InvalidPDFError(
|
|
45
|
+
f"'{candidate.name}' does not have a %PDF header in the first "
|
|
46
|
+
f"{_HEADER_SCAN_BYTES} bytes, so it was not opened as a PDF."
|
|
47
|
+
)
|
|
48
|
+
return candidate
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _has_pdf_header(path: Path) -> bool:
|
|
52
|
+
with path.open("rb") as handle:
|
|
53
|
+
prefix = handle.read(_HEADER_SCAN_BYTES)
|
|
54
|
+
return _PDF_MARKER in prefix
|
evupdf/utils/hashing.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Content hashes for extracted documents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def sha256_file(path: Path) -> str:
|
|
10
|
+
"""Return the lowercase hex SHA-256 digest of a file."""
|
|
11
|
+
|
|
12
|
+
digest = hashlib.sha256()
|
|
13
|
+
with path.open("rb") as handle:
|
|
14
|
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
15
|
+
digest.update(chunk)
|
|
16
|
+
return digest.hexdigest()
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: evupdf
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Extract text, layout, and metadata from digital PDFs into typed JSON.
|
|
5
|
+
Author: EvuPDF contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: document,extraction,pdf,pymupdf,text
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Text Processing
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: pydantic>=2
|
|
23
|
+
Requires-Dist: pymupdf<2,>=1.26
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: mypy>=1.13; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# EvuPDF
|
|
31
|
+
|
|
32
|
+
EvuPDF extracts text, page geometry, and metadata from digital PDFs. The result is a typed Python object with bounding boxes, a file hash, and JSON export. Core extraction works offline after installation. It does not call an AI provider.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install evupdf
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from evupdf import PDFExtractor
|
|
40
|
+
|
|
41
|
+
extractor = PDFExtractor()
|
|
42
|
+
result = extractor.extract("sample.pdf")
|
|
43
|
+
|
|
44
|
+
result.save_json("sample.json")
|
|
45
|
+
print(result.text)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Version 0.1.0 extracts digital PDFs. It detects pages that have little or no native text and reports that OCR may be needed. It does not run OCR, extract tables, extract images, classify documents, or call a language model.
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
|
|
52
|
+
Python 3.10 or newer is required.
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install evupdf
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
PyMuPDF 1.x is installed with EvuPDF. PyMuPDF is dual-licensed under the AGPL-3.0 or a commercial Artifex license. EvuPDF's own code is MIT. Read `THIRD_PARTY_NOTICES.md` before shipping a product that depends on this package.
|
|
59
|
+
|
|
60
|
+
Install from a checkout while developing:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
python -m pip install -e ".[dev]"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Quickstart
|
|
67
|
+
|
|
68
|
+
`extract()` reads one local `.pdf` file:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from evupdf import PDFExtractor
|
|
72
|
+
|
|
73
|
+
document = PDFExtractor().extract("invoice.pdf")
|
|
74
|
+
print(document.page_count)
|
|
75
|
+
print(document.pages[0].blocks[0].text)
|
|
76
|
+
print(document.pages[0].blocks[0].bbox)
|
|
77
|
+
document.save_json("invoice.json")
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A runnable script is in `examples/basic_extract.py`.
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
python examples/basic_extract.py invoice.pdf
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Encrypted PDFs need the user password. The password is used to open the file and is not written into the result:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
document = PDFExtractor().extract("secret.pdf", password="user-password")
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Set `preserve_coordinates=False` when bounding boxes are not needed.
|
|
93
|
+
|
|
94
|
+
## Coordinates
|
|
95
|
+
|
|
96
|
+
Bounding boxes and page width and height are in PDF points. One point is 1/72 inch. The origin is the top-left of the displayed page, x increases to the right, and y increases downward. Page numbers in the public result are 1-based. `rotation` is the page rotation in degrees.
|
|
97
|
+
|
|
98
|
+
`reading_order` follows PyMuPDF's content-stream order. EvuPDF does not yet reorder blocks into a layout-normalized reading order.
|
|
99
|
+
|
|
100
|
+
`source.confidence` is `null` for native text. EvuPDF does not invent a confidence score.
|
|
101
|
+
|
|
102
|
+
## Limits
|
|
103
|
+
|
|
104
|
+
`ExtractorConfig` controls how much work extraction will attempt:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from evupdf import ExtractorConfig, PDFExtractor
|
|
108
|
+
|
|
109
|
+
extractor = PDFExtractor(
|
|
110
|
+
ExtractorConfig(
|
|
111
|
+
max_file_size_bytes=20 * 1024 * 1024,
|
|
112
|
+
max_page_count=100,
|
|
113
|
+
ocr_min_text_chars=20,
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The defaults are 50 MB, 500 pages, and a page dimension of 14,400 points (200 inches). A page with fewer than 20 non-whitespace characters is flagged with warning code `ocr_recommended`. That flag is a heuristic, not proof that the page is a scan.
|
|
119
|
+
|
|
120
|
+
If text extraction fails on one page, earlier and later pages are still returned. The failed page is empty and carries warning code `page_extraction_failed`.
|
|
121
|
+
|
|
122
|
+
## Errors
|
|
123
|
+
|
|
124
|
+
| Exception | When it is raised |
|
|
125
|
+
| --- | --- |
|
|
126
|
+
| `FileValidationError` | The path is missing, not a file, or does not end in `.pdf`. |
|
|
127
|
+
| `InvalidPDFError` | The file is empty, has no `%PDF` header, or cannot be parsed. |
|
|
128
|
+
| `EncryptedPDFError` | A password is required and was omitted or rejected. |
|
|
129
|
+
| `PDFTooLargeError` | The file exceeds `max_file_size_bytes`. |
|
|
130
|
+
| `TooManyPagesError` | The document exceeds `max_page_count`. |
|
|
131
|
+
|
|
132
|
+
All of these inherit from `EvuPDFError`.
|
|
133
|
+
|
|
134
|
+
## What this version does not do
|
|
135
|
+
|
|
136
|
+
- OCR, including Tesseract
|
|
137
|
+
- Table extraction
|
|
138
|
+
- Embedded image export
|
|
139
|
+
- AI classification or schema-based structuring
|
|
140
|
+
- A command-line interface and an HTTP API
|
|
141
|
+
|
|
142
|
+
Those are later milestones. Optional extras such as `evupdf[ocr]` are not published yet, because the features they would install are not implemented.
|
|
143
|
+
|
|
144
|
+
## Development
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
python -m pip install -e ".[dev]"
|
|
148
|
+
ruff check src tests examples
|
|
149
|
+
ruff format src tests examples
|
|
150
|
+
mypy
|
|
151
|
+
pytest
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Tests generate small PDFs at runtime. Do not commit customer documents.
|
|
155
|
+
|
|
156
|
+
## License
|
|
157
|
+
|
|
158
|
+
EvuPDF source code is MIT. See `LICENSE` and `THIRD_PARTY_NOTICES.md`.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
evupdf/__init__.py,sha256=cV9tmnMVkyfDjSSAocPoESDBUZxNr-WKpHEwaVXss-U,988
|
|
2
|
+
evupdf/client.py,sha256=h_iMPVYgvpmEqYS6cH96ZyRm_Y1akHWAtM5K018yong,2984
|
|
3
|
+
evupdf/config.py,sha256=aPAQoXBIn8OS8qlv1gX8ZYYhdaN4kD4MWOgqrlA3njY,1265
|
|
4
|
+
evupdf/exceptions.py,sha256=5GaJLUim8BzexJBVPD9aWhUmCppFn40t-CQjvmsmaZk,815
|
|
5
|
+
evupdf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
evupdf/extractors/__init__.py,sha256=krC_J22O2Y4u0nIgZzFcO5GA3W5AOePO4Vh2hrLehaI,31
|
|
7
|
+
evupdf/extractors/base.py,sha256=oJU_3PzPbDpQXEiBSze0rCBV3KioXcuL45JPBgL09H0,612
|
|
8
|
+
evupdf/extractors/pymupdf.py,sha256=adA5557eJU2X-gHnyAeACJqJfjcK91j__0ywN3zwXgk,9693
|
|
9
|
+
evupdf/models/__init__.py,sha256=ehR3cwugtKJpOKj2DuIbZ-h_HcvxFmXVaTOSUtmISVQ,442
|
|
10
|
+
evupdf/models/block.py,sha256=PRv3w0ocI6IiyqyP61IVjgbKUbe277jqDKIVBh2-wsg,1130
|
|
11
|
+
evupdf/models/document.py,sha256=TduEVqnZ4Ij4O5DWzxitPfGS03nkaMesRZXltdscnSI,719
|
|
12
|
+
evupdf/models/extraction.py,sha256=hhT4_XduEMbxbtFqTTJEUA2H_rKvPhii3x7OmL2-j6A,2893
|
|
13
|
+
evupdf/models/page.py,sha256=HEKyezgVCLLwizngfX_mLeKgHpCer6hFdBDNSVNukOk,994
|
|
14
|
+
evupdf/utils/__init__.py,sha256=pO-cMcZlD3JSFZl7zJkiHH8q6RnZlIzvjwtCOQ7eh6g,49
|
|
15
|
+
evupdf/utils/dates.py,sha256=0j31DpjAcbhJxHhwU4PUthzSbcM3j19w2V13-rgh51I,2600
|
|
16
|
+
evupdf/utils/files.py,sha256=igHBE3AyTY-rzrY1kfmiPbGforRTvv-4Da9cvDeScL4,2031
|
|
17
|
+
evupdf/utils/hashing.py,sha256=rGF852MdwB2oVtQJrjvSQBIhgUr9RXMBHTTn7dgPBUc,418
|
|
18
|
+
evupdf-0.1.0.dist-info/METADATA,sha256=eIPm879IBiKbUbv2aQhApz0bS1uSO19QnNUyVP2diU8,5170
|
|
19
|
+
evupdf-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
20
|
+
evupdf-0.1.0.dist-info/licenses/LICENSE,sha256=dpWUnxG4BoZzHghSs_HBfkrTDK0ZD4GOkzmHLoG7eGM,1076
|
|
21
|
+
evupdf-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EvuPDF contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|