pgx-docling-parser-core 0.0.0.dev0__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.
Potentially problematic release.
This version of pgx-docling-parser-core might be problematic. Click here for more details.
- pgx_docling_parser_core-0.0.0.dev0/.gitignore +218 -0
- pgx_docling_parser_core-0.0.0.dev0/PKG-INFO +21 -0
- pgx_docling_parser_core-0.0.0.dev0/README.md +11 -0
- pgx_docling_parser_core-0.0.0.dev0/pyproject.toml +32 -0
- pgx_docling_parser_core-0.0.0.dev0/src/core/__init__.py +15 -0
- pgx_docling_parser_core-0.0.0.dev0/src/core/base.py +66 -0
- pgx_docling_parser_core-0.0.0.dev0/src/core/parsers.py +205 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
@@ -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,11 @@
|
|
|
1
|
+
# pgx-docling-parser-core
|
|
2
|
+
|
|
3
|
+
Core classes and base functionality for pgx-docling-parser.
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
## Contents
|
|
8
|
+
|
|
9
|
+
- Base converter classes
|
|
10
|
+
- Common utilities
|
|
11
|
+
- Shared types and enums
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24", "hatch-vcs>=0.3.0"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pgx-docling-parser-core"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Core classes for paperless-docling-parser"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10,<3.14"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "T-Eberle" },
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
# Core dependencies needed by both local and docling_serve
|
|
17
|
+
dependencies = [
|
|
18
|
+
"docling-core>=2.0.0",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[tool.hatch.build.targets.wheel]
|
|
22
|
+
packages = ["src/core"]
|
|
23
|
+
|
|
24
|
+
[tool.hatch.version]
|
|
25
|
+
source = "vcs"
|
|
26
|
+
root = "../.."
|
|
27
|
+
fallback-version = "0.0.0.dev0"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.sdist]
|
|
30
|
+
include = [
|
|
31
|
+
"src/",
|
|
32
|
+
]
|
|
@@ -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
|
+
]
|
|
@@ -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
|
+
|
|
@@ -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 []
|