pgx-docling-parser-core 0.0.0.dev0__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.

Potentially problematic release.


This version of pgx-docling-parser-core might be problematic. Click here for more details.

core/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from core.base import BaseDoclingConverter, PdfConversionMode, get_pdf_conversion_mode
5
+
6
+ # Read version from VERSION file at repository root
7
+ _version_file = Path(__file__).parent.parent.parent.parent.parent / "VERSION"
8
+ __version__ = _version_file.read_text().strip() if _version_file.exists() else "0.0.0"
9
+
10
+ __all__ = [
11
+ "__version__",
12
+ "BaseDoclingConverter",
13
+ "PdfConversionMode",
14
+ "get_pdf_conversion_mode",
15
+ ]
core/base.py ADDED
@@ -0,0 +1,66 @@
1
+ from abc import ABC, abstractmethod
2
+ from enum import Enum
3
+ from pathlib import Path
4
+
5
+
6
+ import os
7
+
8
+ from docling_core.types.doc.document import DoclingDocument
9
+
10
+ PAPERLESS_DOCLING_PDF_CONVERSION_MODE = "PAPERLESS_DOCLING_PDF_CONVERSION_MODE"
11
+
12
+ class PdfConversionMode(Enum):
13
+ EASYOCR = "easyocr"
14
+ TESSERACT = "tesseract"
15
+ GRANITE_DOCLING = "granite_docling"
16
+
17
+
18
+ def get_pdf_conversion_mode() -> PdfConversionMode:
19
+ """
20
+ Get the PDF conversion mode from environment variable.
21
+
22
+ Returns:
23
+ PdfConversionMode: The conversion mode, defaults to EASYOCR if not set or invalid.
24
+ """
25
+ env_value = os.environ.get(PAPERLESS_DOCLING_PDF_CONVERSION_MODE, "").lower()
26
+
27
+ # Try to match the environment variable value to an enum member
28
+ for mode in PdfConversionMode:
29
+ if mode.value == env_value:
30
+ return mode
31
+
32
+ # Default to EASYOCR if not set or invalid value
33
+ return PdfConversionMode.EASYOCR
34
+
35
+ class BaseDoclingConverter(ABC):
36
+ """Base class for all docling converters."""
37
+
38
+ def __init__(self) -> None:
39
+ self.pdf_conversion_mode = get_pdf_conversion_mode()
40
+
41
+ def convert(self, document_path: Path) -> DoclingDocument | None:
42
+ """Convert a document to a DoclingDocument."""
43
+ doc = None
44
+ if self.pdf_conversion_mode == PdfConversionMode.EASYOCR:
45
+ doc= self.convert_easyocr(document_path)
46
+ elif self.pdf_conversion_mode == PdfConversionMode.TESSERACT:
47
+ doc = self.convert_tesseract(document_path)
48
+ elif self.pdf_conversion_mode == PdfConversionMode.GRANITE_DOCLING:
49
+ doc = self.convert_granite_docling(document_path)
50
+ return doc
51
+
52
+
53
+ @abstractmethod
54
+ def convert_easyocr(self, document_path: Path) -> DoclingDocument:
55
+ pass
56
+
57
+ @abstractmethod
58
+ def convert_tesseract(self, document_path: Path) -> DoclingDocument:
59
+ pass
60
+
61
+ @abstractmethod
62
+ def convert_granite_docling(self, document_path: Path) -> DoclingDocument:
63
+ pass
64
+
65
+
66
+
core/parsers.py ADDED
@@ -0,0 +1,205 @@
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ import tempfile
5
+ import datetime
6
+ import logging
7
+
8
+ from pathlib import Path
9
+ from typing import Self
10
+ from types import TracebackType
11
+ from typing import TYPE_CHECKING
12
+
13
+ from docling_core.types.doc.document import DoclingDocument
14
+
15
+ # Configure logging
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from types import TracebackType
21
+ #from paperless.parsers import MetadataEntry
22
+ from paperless.parsers import ParserContext
23
+
24
+ def _make_tempdir() -> Path:
25
+ """Allocate a temp working directory under SCRATCH_DIR if available.
26
+
27
+ Falls back to the system temp directory when Django settings are not
28
+ configured (i.e. when running unit tests outside Paperless-ngx).
29
+ """
30
+ parent: Path | None = None
31
+ try:
32
+ from django.conf import settings # noqa: PLC0415
33
+ scratch = getattr(settings, "SCRATCH_DIR", None)
34
+ if scratch is not None:
35
+ parent = Path(scratch)
36
+ parent.mkdir(parents=True, exist_ok=True)
37
+ logger.debug(f"Using SCRATCH_DIR for temp directory: {parent}")
38
+ except Exception as e:
39
+ logger.debug(f"Django settings not available, using system temp directory: {e}")
40
+ parent = None
41
+
42
+ tempdir = Path(tempfile.mkdtemp(prefix="paperless-ngx-docling-", dir=parent))
43
+ logger.debug(f"Created temp directory: {tempdir}")
44
+ return tempdir
45
+
46
+ def _date_to_datetime(d: datetime.date | None) -> datetime.datetime | None:
47
+ if d is None:
48
+ return None
49
+ return datetime.datetime(d.year, d.month, d.day, tzinfo=datetime.timezone.utc)
50
+
51
+ class DoclingParser:
52
+ name = "Docling Parser"
53
+ version = "0.1.0"
54
+ author = "Thomas Eberle"
55
+ url = "https://github.com/T-Eberle/paperless-docling-parser/issues"
56
+
57
+ @classmethod
58
+ def supported_mime_types(cls) -> dict[str, str]:
59
+ """Return mapping of supported MIME types to file extensions.
60
+
61
+ Returns:
62
+ dict[str, str]: Dictionary mapping MIME type strings to their
63
+ corresponding file extensions (including the dot prefix).
64
+ """
65
+ return {
66
+ "application/pdf": ".pdf",
67
+ }
68
+
69
+ @classmethod
70
+ def score(cls, mime_type: str, filename: str, path: Path | None = None) -> int | None:
71
+ return 100
72
+
73
+ @property
74
+ def can_produce_archive(self) -> bool:
75
+ return False
76
+
77
+ @property
78
+ def requires_pdf_rendition(self) -> bool:
79
+ return False
80
+
81
+
82
+ def __init__(self, logging_group: object = None) -> None:
83
+ logger.info("Initializing DoclingParser")
84
+ self._tempdir = _make_tempdir()
85
+ self._text: str | None = None
86
+ self._archive_path: Path | None = None
87
+ self.converter = DoclingRemoteConverter()
88
+ logger.debug(f"DoclingParser initialized with temp directory: {self._tempdir}")
89
+
90
+ def __enter__(self) -> Self:
91
+ return self
92
+
93
+ def __exit__(
94
+ self,
95
+ exc_type: type[BaseException] | None,
96
+ exc_val: BaseException | None,
97
+ exc_tb: TracebackType | None,
98
+ ) -> None:
99
+ logger.debug(f"Cleaning up temp directory: {self._tempdir}")
100
+ shutil.rmtree(self._tempdir, ignore_errors=True)
101
+
102
+ def configure(self, context: ParserContext) -> None:
103
+ pass
104
+
105
+ def get_thumbnail(self, document_path: Path, mime_type: str) -> Path:
106
+ logger.debug(f"Generating thumbnail for: {document_path} (mime_type: {mime_type})")
107
+ from PIL import Image, ImageDraw
108
+ out = self._tempdir / "thumb.webp"
109
+ # If it's a PDF, convert the first page to a thumbnail
110
+ if mime_type == "application/pdf":
111
+ try:
112
+ import fitz # PyMuPDF
113
+
114
+ # Open the PDF
115
+ pdf_document = fitz.open(document_path)
116
+
117
+ # Get the first page
118
+ if len(pdf_document) > 0:
119
+ first_page = pdf_document[0]
120
+
121
+ # Calculate zoom factor to get desired dimensions
122
+ # Get page dimensions
123
+ page_rect = first_page.rect
124
+ page_width = page_rect.width
125
+ page_height = page_rect.height
126
+
127
+ # Calculate zoom to fit 500x700
128
+ zoom_x = 500 / page_width
129
+ zoom_y = 700 / page_height
130
+ zoom = min(zoom_x, zoom_y) # Use smaller zoom to fit within bounds
131
+
132
+ # Create transformation matrix
133
+ mat = fitz.Matrix(zoom, zoom)
134
+
135
+ # Render page to pixmap
136
+ pix = first_page.get_pixmap(matrix=mat)
137
+
138
+ # Convert pixmap to PIL Image
139
+ img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
140
+
141
+ # Create a new 500x700 white canvas
142
+ canvas = Image.new("RGB", (500, 700), color="white")
143
+
144
+ # Calculate position to center the image
145
+ x_offset = (500 - img.width) // 2
146
+ y_offset = (700 - img.height) // 2
147
+
148
+ # Paste the rendered page onto the canvas
149
+ canvas.paste(img, (x_offset, y_offset))
150
+
151
+ # Save as WebP
152
+ canvas.save(out, format="WEBP")
153
+
154
+ pdf_document.close()
155
+ logger.info(f"Successfully generated PDF thumbnail: {out}")
156
+ return out
157
+
158
+ pdf_document.close()
159
+ except Exception as e:
160
+ # Fall back to placeholder if PDF rendering fails
161
+ logger.warning(f"Failed to generate PDF thumbnail, using placeholder: {e}")
162
+ pass
163
+
164
+ # Fallback: create a placeholder thumbnail
165
+ logger.debug("Creating placeholder thumbnail")
166
+ img = Image.new("RGB", (500, 700), color="white")
167
+ ImageDraw.Draw(img).text((10, 10), "PDF Document", fill="black")
168
+ img.save(out, format="WEBP")
169
+ return out
170
+
171
+ def parse(self, document_path: Path, mime_type: str, *, produce_archive: bool = True) -> None:
172
+ """
173
+ Parse a document using docling-serve API.
174
+
175
+ Args:
176
+ document_path: Path to the document to parse
177
+ mime_type: MIME type of the document
178
+ produce_archive: Whether to produce an archive (not supported)
179
+ """
180
+ logger.info(f"Parsing document: {document_path} (mime_type: {mime_type})")
181
+ # Use the synchronous wrapper to call the async convert method
182
+ result = self.converter.convert(document_path)
183
+
184
+ if isinstance(result, DoclingDocument):
185
+ self._text = result.export_to_markdown()
186
+ logger.info(f"Successfully parsed document to markdown, length: {len(self._text)} characters")
187
+ else:
188
+ self._text = str(result)
189
+ logger.warning(f"Result was not a DoclingDocument, converted to string: {type(result)}")
190
+
191
+
192
+ def get_text(self) -> str | None:
193
+ return self._text
194
+
195
+ def get_date(self) -> datetime.datetime | None:
196
+ return None
197
+
198
+ def get_archive_path(self) -> Path | None:
199
+ return self._archive_path
200
+
201
+ def get_page_count(self, document_path: Path, mime_type: str) -> int | None:
202
+ return None
203
+
204
+ def extract_metadata(self, document_path: Path, mime_type: str) -> list:
205
+ return []
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: pgx-docling-parser-core
3
+ Version: 0.0.0.dev0
4
+ Summary: Core classes for paperless-docling-parser
5
+ Author: T-Eberle
6
+ License-Expression: MIT
7
+ Requires-Python: <3.14,>=3.10
8
+ Requires-Dist: docling-core>=2.0.0
9
+ Description-Content-Type: text/markdown
10
+
11
+ # pgx-docling-parser-core
12
+
13
+ Core classes and base functionality for pgx-docling-parser.
14
+
15
+ This is an internal package used by both `pgx-docling-parser-local` and `pgx-docling-parser-serve`. It is not intended to be installed directly.
16
+
17
+ ## Contents
18
+
19
+ - Base converter classes
20
+ - Common utilities
21
+ - Shared types and enums
@@ -0,0 +1,6 @@
1
+ core/__init__.py,sha256=ZdrLSb1qWTPK4to5Uz6GL1KLg68RoKJQLZKnS0ny8LU,483
2
+ core/base.py,sha256=SBuyVGD7iw0dOLtjzsO7AVJn9Qk9OZPrg-VJzVULAfQ,2009
3
+ core/parsers.py,sha256=qtXtWcQ6zI_GM1kXE1lhTDPUS3VgWehHFA5qkx6Eamk,7553
4
+ pgx_docling_parser_core-0.0.0.dev0.dist-info/METADATA,sha256=DemYSezUVIatCTo1pZXsAFopPOl1Kp1B6WRVTxNFOHM,585
5
+ pgx_docling_parser_core-0.0.0.dev0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ pgx_docling_parser_core-0.0.0.dev0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any