From 7da8b90c00ece8dc93dda090925db62ff6ca201b Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Tue, 21 Jul 2026 16:07:59 +0200 Subject: [PATCH 01/26] :rewind: revert URL safety checks (#455) --- tests/v1/input/test_url_validation.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 tests/v1/input/test_url_validation.py diff --git a/tests/v1/input/test_url_validation.py b/tests/v1/input/test_url_validation.py new file mode 100644 index 00000000..bb1fbb02 --- /dev/null +++ b/tests/v1/input/test_url_validation.py @@ -0,0 +1,17 @@ +import pytest + +from mindee.error.mindee_error import MindeeSourceError +from mindee.mindee_http.response_validation import validate_url_for_source + + +class TestValidateUrlScheme: + def test_rejects_http(self): + with pytest.raises(MindeeSourceError, match="HTTPS"): + validate_url_for_source("http://example.com/file.pdf") + + def test_rejects_ftp(self): + with pytest.raises(MindeeSourceError, match="HTTPS"): + validate_url_for_source("ftp://example.com/file.pdf") + + def test_accepts_https(self): + validate_url_for_source("https://example.com/file.pdf") From a45b562307dbc616a3a75d5989dbdd338279d955 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Fri, 26 Jun 2026 16:50:31 +0200 Subject: [PATCH 02/26] =?UTF-8?q?:sparkles:=20add=20full=20support=20for?= =?UTF-8?q?=20image=20processing=20through=20bernard=20l'=C3=A9dit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/dependabot.yml | 3 +- .github/workflows/_build-bernard-ledit.yml | 89 +++++++ .github/workflows/_smoke-test.yml | 16 ++ .github/workflows/_static-analysis.yml | 21 ++ .github/workflows/_test-cli.yml | 16 ++ .github/workflows/_test-integrations.yml | 18 +- .github/workflows/_test-regressions.yml | 16 ++ .github/workflows/_test-units.yml | 19 +- .github/workflows/cron.yml | 5 + .github/workflows/pull-request.yml | 8 +- .github/workflows/push-main-branch.yml | 9 +- .gitmodules | 4 + .pre-commit-config.yaml | 53 ++++ bernard-ledit | 1 + mindee/dependencies/__init__.py | 10 +- mindee/dependencies/checkers.py | 32 +-- mindee/dependencies/decorators.py | 19 +- mindee/image/extracted_image.py | 29 ++- mindee/image/image_compressor.py | 38 ++- mindee/image/image_extractor.py | 131 ++++------ mindee/input/local_input_source.py | 41 ++- mindee/pdf/__init__.py | 4 - mindee/pdf/pdf_char_data.py | 31 --- mindee/pdf/pdf_compressor.py | 133 ++-------- mindee/pdf/pdf_extractor.py | 32 +-- mindee/pdf/pdf_utils.py | 242 +----------------- pyproject.toml | 11 +- scripts/generate_lite_toml.py | 12 +- tests/dependencies/test_dependencies.py | 22 +- tests/input/test_apply_page_options.py | 18 +- tests/input/test_compression.py | 36 +-- tests/input/test_fix_pdf.py | 4 +- tests/input/test_inputs.py | 12 +- .../test_invoice_splitter_auto_extraction.py | 3 +- .../test_multi_receipts_extractor.py | 26 +- tests/v1/extraction/test_pdf_extractor.py | 9 +- tests/v1/input/test_url_validation.py | 17 -- tests/v1/test_client.py | 2 +- .../v2/file_operations/test_crop_operation.py | 20 +- .../test_crop_operation_integration.py | 7 +- .../file_operations/test_split_operation.py | 6 +- .../test_split_operation_integration.py | 2 +- 42 files changed, 512 insertions(+), 715 deletions(-) create mode 100644 .github/workflows/_build-bernard-ledit.yml create mode 100644 .pre-commit-config.yaml create mode 160000 bernard-ledit delete mode 100644 mindee/pdf/pdf_char_data.py delete mode 100644 tests/v1/input/test_url_validation.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7fef985a..55c279a4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -17,8 +17,7 @@ updates: - "requests" optional-dependencies: patterns: - - "pypdfium2" - - "Pillow" + - "bernard_ledit" test-dependencies: patterns: - "pytest" diff --git a/.github/workflows/_build-bernard-ledit.yml b/.github/workflows/_build-bernard-ledit.yml new file mode 100644 index 00000000..e3558cec --- /dev/null +++ b/.github/workflows/_build-bernard-ledit.yml @@ -0,0 +1,89 @@ +name: Build bernard-ledit Wheel + +on: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +jobs: + build-wheel: + name: Build bernard-ledit wheel + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + os: + - "ubuntu-22.04" + - "windows-2022" + - "macos-latest" + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + submodules: recursive + + - name: Set up Python 3.10 + uses: actions/setup-python@v6 + with: + python-version: "3.10" + + - name: Resolve bernard-ledit submodule commit + id: bernard + shell: bash + run: echo "sha=$(git -C bernard-ledit rev-parse HEAD)" >> "$GITHUB_OUTPUT" + + # Skip the whole Rust/maturin build when the submodule pointer is unchanged. + - name: Restore cached bernard-ledit build + id: cache + uses: actions/cache@v5 + with: + path: ./.github/artifacts/bernard-ledit + key: bernard-ledit-${{ runner.os }}-${{ steps.bernard.outputs.sha }} + + - name: Cache downloaded PDFium binary + if: steps.cache.outputs.cache-hit != 'true' + uses: actions/cache@v5 + with: + path: bernard-ledit/core/.pdfium_cache + key: pdfium-${{ runner.os }}-${{ hashFiles('bernard-ledit/core/build.rs') }} + restore-keys: | + pdfium-${{ runner.os }}- + + - name: Cache Rust build + if: steps.cache.outputs.cache-hit != 'true' + uses: Swatinem/rust-cache@v2 + with: + workspaces: bernard-ledit + key: ${{ steps.bernard.outputs.sha }} + + - name: Build bernard-ledit wheel + if: steps.cache.outputs.cache-hit != 'true' + shell: bash + run: | + python -m pip install --upgrade pip + pip wheel --no-deps --wheel-dir ./.github/artifacts/bernard-ledit bernard-ledit/bindings/python/ + + # The wheel does not embed PDFium; ship the library so consumers can set PDFIUM_PATH. + - name: Collect bundled PDFium library + if: steps.cache.outputs.cache-hit != 'true' + shell: bash + run: | + lib=$(find bernard-ledit/core/.pdfium_cache \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print | head -n 1) + if [ -z "$lib" ]; then + echo "::error::PDFium library not found under bernard-ledit/core/.pdfium_cache after build" + exit 1 + fi + cp "$lib" ./.github/artifacts/bernard-ledit/ + echo "Bundled PDFium library: $(basename "$lib")" + + - name: Upload bernard-ledit build + uses: actions/upload-artifact@v4 + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: | + ./.github/artifacts/bernard-ledit/*.whl + ./.github/artifacts/bernard-ledit/libpdfium.* + ./.github/artifacts/bernard-ledit/pdfium.dll + if-no-files-found: error diff --git a/.github/workflows/_smoke-test.yml b/.github/workflows/_smoke-test.yml index 9716d307..14c6fcf5 100644 --- a/.github/workflows/_smoke-test.yml +++ b/.github/workflows/_smoke-test.yml @@ -42,9 +42,25 @@ jobs: restore-keys: | ${{ runner.os }}-samples- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + continue-on-error: true + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - name: Locate bundled PDFium + shell: bash + run: | + lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) + if [ -n "$lib" ]; then + echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" + fi + - name: Install dependencies run: | python -m pip install pip + python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.' - name: Tests v2 sample code diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 6ab6f2b9..03fccaee 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -16,6 +16,7 @@ jobs: steps: - uses: actions/checkout@v7 with: + submodules: recursive fetch-depth: 0 - name: Run Betterleaks @@ -52,15 +53,35 @@ jobs: restore-keys: | ${{ runner.os }}-lint- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + continue-on-error: true + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - name: Locate bundled PDFium + shell: bash + run: | + lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) + if [ -n "$lib" ]; then + echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" + fi + - name: Install dependencies run: | python -m pip install pip + python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.[lint]' - name: License check run: | pylic check --allow-extra-safe-licenses + - name: Audit dependencies + run: | + pip-audit --local --skip-editable + - name: Cache pre-commit uses: actions/cache@v6 with: diff --git a/.github/workflows/_test-cli.yml b/.github/workflows/_test-cli.yml index 3d7a82c6..28ee4f27 100644 --- a/.github/workflows/_test-cli.yml +++ b/.github/workflows/_test-cli.yml @@ -48,9 +48,25 @@ jobs: restore-keys: | ${{ runner.os }}-cli- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + continue-on-error: true + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - name: Locate bundled PDFium + shell: bash + run: | + lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) + if [ -n "$lib" ]; then + echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" + fi + - name: Install dependencies run: | python -m pip install pip + python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.' - name: Test V1 CLI diff --git a/.github/workflows/_test-integrations.yml b/.github/workflows/_test-integrations.yml index 7f99636f..399de795 100644 --- a/.github/workflows/_test-integrations.yml +++ b/.github/workflows/_test-integrations.yml @@ -52,9 +52,25 @@ jobs: restore-keys: | ${{ runner.os }}-test- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + continue-on-error: true + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - name: Locate bundled PDFium + shell: bash + run: | + lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) + if [ -n "$lib" ]; then + echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" + fi + - name: Install dependencies run: | python -m pip install pip + python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.[test]' - name: Run Integration Testing run: | @@ -107,4 +123,4 @@ jobs: shell: bash - name: Run Integration Testing run: | - pytest -n 2 -m "integration and not pypdfium2 and not pillow" + pytest -m "integration and not bernard_ledit" diff --git a/.github/workflows/_test-regressions.yml b/.github/workflows/_test-regressions.yml index 0a470b55..9d2afd08 100644 --- a/.github/workflows/_test-regressions.yml +++ b/.github/workflows/_test-regressions.yml @@ -38,9 +38,25 @@ jobs: restore-keys: | ${{ runner.os }}-test- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + continue-on-error: true + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - name: Locate bundled PDFium + shell: bash + run: | + lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) + if [ -n "$lib" ]; then + echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" + fi + - name: Install dependencies run: | python -m pip install pip + python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.[test]' - name: Run Regression Testing env: diff --git a/.github/workflows/_test-units.yml b/.github/workflows/_test-units.yml index 5d7972ed..d021c342 100644 --- a/.github/workflows/_test-units.yml +++ b/.github/workflows/_test-units.yml @@ -15,6 +15,7 @@ jobs: os: - "ubuntu-22.04" - "windows-2022" + - "macos-latest" python-version: - "3.10" - "3.11" @@ -40,9 +41,25 @@ jobs: restore-keys: | ${{ runner.os }}-test- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + continue-on-error: true + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - name: Locate bundled PDFium + shell: bash + run: | + lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) + if [ -n "$lib" ]; then + echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" + fi + - name: Install dependencies run: | python -m pip install pip + python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.[test]' - name: Unit testing with pytest @@ -57,6 +74,7 @@ jobs: os: - "ubuntu-22.04" - "windows-2022" + - "macos-latest" python-version: - "3.10" - "3.14" @@ -90,4 +108,3 @@ jobs: - name: Unit testing with pytest run: | pytest - diff --git a/.github/workflows/cron.yml b/.github/workflows/cron.yml index b5835ccf..2bf1ec57 100644 --- a/.github/workflows/cron.yml +++ b/.github/workflows/cron.yml @@ -10,12 +10,17 @@ permissions: actions: read jobs: + build-bernard-ledit: + uses: mindee/mindee-api-python/.github/workflows/_build-bernard-ledit.yml@main test-regressions: uses: mindee/mindee-api-python/.github/workflows/_test-regressions.yml@main + needs: build-bernard-ledit secrets: inherit test-code-samples: uses: mindee/mindee-api-python/.github/workflows/_smoke-test.yml@main + needs: build-bernard-ledit secrets: inherit test-cli: uses: mindee/mindee-api-python/.github/workflows/_test-cli.yml@main + needs: build-bernard-ledit secrets: inherit diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 617b6eac..6cd55d7c 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -10,12 +10,16 @@ permissions: jobs: workflow-lint: uses: ./.github/workflows/_workflow_lint.yml + build-bernard-ledit: + uses: ./.github/workflows/_build-bernard-ledit.yml static-analysis: uses: ./.github/workflows/_static-analysis.yml - needs: workflow-lint + needs: + - workflow-lint + - build-bernard-ledit test-units: uses: ./.github/workflows/_test-units.yml - needs: static-analysis + needs: build-bernard-ledit secrets: inherit test-regressions: uses: ./.github/workflows/_test-regressions.yml diff --git a/.github/workflows/push-main-branch.yml b/.github/workflows/push-main-branch.yml index f04ba2c6..cca56814 100644 --- a/.github/workflows/push-main-branch.yml +++ b/.github/workflows/push-main-branch.yml @@ -6,15 +6,20 @@ on: - main jobs: + build-bernard-ledit: + uses: mindee/mindee-api-python/.github/workflows/_build-bernard-ledit.yml@main static-analysis: uses: mindee/mindee-api-python/.github/workflows/_static-analysis.yml@main + needs: build-bernard-ledit test_units: uses: mindee/mindee-api-python/.github/workflows/_test-units.yml@main - needs: static-analysis + needs: build-bernard-ledit secrets: inherit tag: uses: mindee/client-lib-actions/.github/workflows/tag-version.yml@main - needs: test_units + needs: + - static-analysis + - test_units release: uses: mindee/client-lib-actions/.github/workflows/create-release.yml@main needs: tag diff --git a/.gitmodules b/.gitmodules index 6a653ee9..dae31977 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,7 @@ [submodule "tests/data"] path = tests/data url = git@github.com:mindee/client-lib-test-data.git +[submodule "bernard-ledit"] + path = bernard-ledit + url = https://github.com/mindee/bernard-ledit.git + branch = dev diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..19af1ff8 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,53 @@ +repos: + - repo: https://github.com/charliermarsh/ruff-pre-commit + rev: v0.15.22 + hooks: + - id: ruff-check + args: [ --fix, --exit-non-zero-on-fix] + - id: ruff-format + + - repo: https://github.com/betterleaks/betterleaks + rev: v1.6.1 + hooks: + - id: betterleaks + + - repo: https://github.com/PyCQA/pylint + rev: v4.0.6 + hooks: + - id: pylint + name: pylint + entry: pylint + language: system + types: [python] + args: [ + "-j2" + ] + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v2.3.0 + hooks: + - id: mypy + args: [] + exclude: "tests/|examples/|docs/" + additional_dependencies: + - httpx + - types-setuptools + - importlib-metadata + - types-Pillow + - types-toml + - repo: local + hooks: + - id: sphinx-html + name: Sphinx HTML build + entry: make -C docs html + language: system + pass_filenames: false + files: ^docs/.*$|^mindee/.*\.py$ + stages: [pre-push] + + - id: sphinx-linkcheck + name: Sphinx Linkcheck + entry: make -C docs linkcheck + language: system + pass_filenames: false + files: ^docs/.*$|^mindee/.*\.py$ + stages: [pre-push] diff --git a/bernard-ledit b/bernard-ledit new file mode 160000 index 00000000..8dcccd65 --- /dev/null +++ b/bernard-ledit @@ -0,0 +1 @@ +Subproject commit 8dcccd65ad5d696240b43e955330d53de8a621b0 diff --git a/mindee/dependencies/__init__.py b/mindee/dependencies/__init__.py index 4fb7c41d..8d7a77d3 100644 --- a/mindee/dependencies/__init__.py +++ b/mindee/dependencies/__init__.py @@ -1,9 +1,7 @@ -from mindee.dependencies.checkers import PILLOW_AVAILABLE, PYPDFIUM2_AVAILABLE -from mindee.dependencies.decorators import requires_pillow, requires_pypdfium2 +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE +from mindee.dependencies.decorators import requires_bernard_ledit __all__ = [ - "PILLOW_AVAILABLE", - "PYPDFIUM2_AVAILABLE", - "requires_pillow", - "requires_pypdfium2", + "BERNARD_LEDIT_AVAILABLE", + "requires_bernard_ledit", ] diff --git a/mindee/dependencies/checkers.py b/mindee/dependencies/checkers.py index ad8bbf8e..afec90b7 100644 --- a/mindee/dependencies/checkers.py +++ b/mindee/dependencies/checkers.py @@ -1,33 +1,17 @@ from mindee.error.mindee_dependency_error import MindeeDependencyError try: - import PIL # noqa: F401 #pylint: disable=unused-import + import bernard_ledit # noqa: F401 #pylint: disable=unused-import - PILLOW_AVAILABLE = True + BERNARD_LEDIT_AVAILABLE = True except ImportError: - PILLOW_AVAILABLE = False - -try: - import pypdfium2 # noqa: F401 #pylint: disable=unused-import - - PYPDFIUM2_AVAILABLE = True -except ImportError: - PYPDFIUM2_AVAILABLE = False - - -def require_pillow() -> None: - """Raises a clear error if Pillow is not installed.""" - if not PILLOW_AVAILABLE: - raise MindeeDependencyError( - "This feature requires the 'Pillow' library. " - "Install it directly or run `pip install mindee` instead of `mindee-lite`." - ) + BERNARD_LEDIT_AVAILABLE = False -def require_pypdfium2() -> None: - """Raises a clear error if PyPDFium2 is not installed.""" - if not PYPDFIUM2_AVAILABLE: +def requires_bernard() -> None: + """Raises a clear error if Bernard L'Édit is not installed.""" + if not BERNARD_LEDIT_AVAILABLE: raise MindeeDependencyError( - "This feature requires the 'PyPDFium2' library. " - "Install it directly or run `pip install mindee` instead of `mindee-lite`." + "This feature requires the 'Bernard L'Édit' library. " + "Install it directly or run `pip install bernard-ledit` instead of `mindee-lite`." ) diff --git a/mindee/dependencies/decorators.py b/mindee/dependencies/decorators.py index d204ae71..e15aad80 100644 --- a/mindee/dependencies/decorators.py +++ b/mindee/dependencies/decorators.py @@ -2,29 +2,18 @@ from collections.abc import Callable from typing import ParamSpec, TypeVar -from mindee.dependencies.checkers import require_pillow, require_pypdfium2 +from mindee.dependencies.checkers import requires_bernard P = ParamSpec("P") R = TypeVar("R") -def requires_pillow(func: Callable[P, R]) -> Callable[P, R]: - """Decorator to enforce Pillow availability on a function/method.""" +def requires_bernard_ledit(func: Callable[P, R]) -> Callable[P, R]: + """Decorator to enforce Bernard L'Édit availability on a function/method.""" @functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: - require_pillow() - return func(*args, **kwargs) - - return wrapper - - -def requires_pypdfium2(func: Callable[P, R]) -> Callable[P, R]: - """Decorator to enforce PyPDFium2 availability on a function/method.""" - - @functools.wraps(func) - def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: - require_pypdfium2() + requires_bernard() return func(*args, **kwargs) return wrapper diff --git a/mindee/image/extracted_image.py b/mindee/image/extracted_image.py index dffc2335..7b63d1bc 100644 --- a/mindee/image/extracted_image.py +++ b/mindee/image/extracted_image.py @@ -1,19 +1,19 @@ from __future__ import annotations from pathlib import Path -from typing import Any, BinaryIO +from typing import BinaryIO -from mindee.dependencies.checkers import PILLOW_AVAILABLE -from mindee.dependencies.decorators import requires_pillow +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE +from mindee.dependencies.decorators import requires_bernard_ledit from mindee.error.mindee_error import MindeeError from mindee.input.bytes_input import BytesInput from mindee.logger import logger -if PILLOW_AVAILABLE: +if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - from PIL import Image + import bernard_ledit.image as bernard_image else: - Image: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name + bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name class ExtractedImage: @@ -47,12 +47,17 @@ def __init__( self._page_id = page_id self._element_id = 0 if element_id is None else element_id - @requires_pillow - def write_to_file(self, output_path: Path | str): + @requires_bernard_ledit + def write_to_file(self, output_path: Path | str, file_format: str | None = None): """ Saves the document to a file. + When no format conversion is requested the buffer is written directly + to avoid a lossy decode → re-encode cycle. + :param output_path: Path to save the file to. + :param file_format: Format of the file to save. If omitted the buffer is + written as-is; pass an explicit format to force a conversion. :raises MindeeError: If an invalid path or filename is provided. """ out_path = Path(output_path) @@ -61,11 +66,13 @@ def write_to_file(self, output_path: Path | str): out_file_path = out_path / self.filename try: self.buffer.seek(0) - image = Image.open(self.buffer) - image.save(out_file_path) + if file_format is None: + out_file_path.write_bytes(self.buffer.read()) + else: + image = bernard_image.decode(self.buffer) + image.save(out_file_path, format=file_format) logger.info("File saved successfully to '%s'.", out_file_path) except Exception as e: - print(e) raise MindeeError(f"Could not save file {Path(output_path).name}.") from e def as_input_source(self) -> BytesInput: diff --git a/mindee/image/image_compressor.py b/mindee/image/image_compressor.py index 37241933..1ad40aa6 100644 --- a/mindee/image/image_compressor.py +++ b/mindee/image/image_compressor.py @@ -1,19 +1,19 @@ from __future__ import annotations -import io -from typing import Any, BinaryIO +import math +from typing import BinaryIO -from mindee.dependencies.checkers import PILLOW_AVAILABLE -from mindee.dependencies.decorators import requires_pillow +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE +from mindee.dependencies.decorators import requires_bernard_ledit -if PILLOW_AVAILABLE: +if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - from PIL import Image + import bernard_ledit.image as bernard_image else: - Image: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name + bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name -@requires_pillow +@requires_bernard_ledit def compress_image( image_buffer: BinaryIO | bytes, quality: int = 85, @@ -29,17 +29,11 @@ def compress_image( :param max_height: Maximum bound for the height. :return: """ - if isinstance(image_buffer, bytes): - image_buffer = io.BytesIO(image_buffer) - with Image.open(image_buffer) as img: - original_width, original_height = img.size - max_width = max_width or original_width - max_height = max_height or original_height - if max_width or max_height: - img.thumbnail((int(max_width), int(max_height)), Image.Resampling.LANCZOS) - - output_buffer = io.BytesIO() - img.save(output_buffer, format="JPEG", quality=quality, optimize=True) - - compressed_image = output_buffer.getvalue() - return compressed_image + max_width = math.floor(max_width) if max_width else None + max_height = math.floor(max_height) if max_height else None + if hasattr(image_buffer, "seek") and hasattr(image_buffer, "read"): + image_buffer.seek(0) + raw_bytes: bytes = image_buffer.read() + else: + raw_bytes = image_buffer + return bernard_image.compress(raw_bytes, quality, max_width, max_height)[0] diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index 681b46f9..99098950 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -2,36 +2,28 @@ import io from pathlib import Path -from typing import Any, BinaryIO +from typing import BinaryIO -from mindee.dependencies import requires_pypdfium2 -from mindee.dependencies.checkers import PILLOW_AVAILABLE, PYPDFIUM2_AVAILABLE -from mindee.dependencies.decorators import requires_pillow -from mindee.error.mindee_error import MindeeError +from mindee.dependencies import requires_bernard_ledit +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE from mindee.geometry.point import Point from mindee.geometry.polygon import Polygon, get_min_max_x, get_min_max_y from mindee.image.extracted_image import ExtractedImage from mindee.input.local_input_source import LocalInputSource -if PYPDFIUM2_AVAILABLE: +if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import pypdfium2 as pdfium + import bernard_ledit.image as bernard_image + import bernard_ledit.pdf as bernard_pdf else: - pdfium = None # pylint: disable=invalid-name + bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name -if PILLOW_AVAILABLE: - # pylint: disable=import-error - from PIL import Image -else: - Image: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name - - -@requires_pillow -@requires_pypdfium2 -def _attach_image_as_new_file( # type: ignore +@requires_bernard_ledit +def _attach_image_as_new_file( input_buffer: BinaryIO, -) -> pdfium.PdfDocument: +) -> bernard_pdf.PdfDocument: """ Attaches an image as a new page in a PdfDocument object. @@ -39,88 +31,60 @@ def _attach_image_as_new_file( # type: ignore :return: A PdfDocument handle. """ input_buffer.seek(0) - image = Image.open(input_buffer) - image.convert("RGB") - image_buffer = io.BytesIO() - image.save(image_buffer, format="JPEG") - - pdf = pdfium.PdfDocument.new() - - image_pdf = pdfium.PdfImage.new(pdf) - image_pdf.load_jpeg(image_buffer) - width, height = image.width, image.height - matrix = pdfium.PdfMatrix().scale(width, height) - image_pdf.set_matrix(matrix) - - page = pdf.new_page(width, height) - page.insert_obj(image_pdf) - page.gen_content() - image.close() + pdf = bernard_pdf.PdfDocument.new() + pdf.append_jpeg_page(input_buffer.read()) return pdf -@requires_pillow +@requires_bernard_ledit def extract_image_from_polygon( - page_content: Image.Image, + page_content: bernard_image.Image, polygon: list[Point], width: float, height: float, file_format: str, + quality: int = 70, ) -> BinaryIO: """ Crops the image from the given polygon. - :param page_content: Contents of the page as a Pillow object. + :param page_content: Contents of the page as a Bernard L'Édit Image object. :param polygon: Polygon coordinates for the image. :param width: Width of the generated image. :param height: Height of the generated image. :param file_format: Format for the generated file. + :param quality: JPEG quality for the output (default 70 — sufficient for OCR). :return: A generated image as a buffer. """ min_max_x = get_min_max_x(polygon) min_max_y = get_min_max_y(polygon) cropped_image = page_content.crop( - ( - int(min_max_x.min * width), - int(min_max_y.min * height), - int(min_max_x.max * width), - int(min_max_y.max * height), - ) + left=int(min_max_x.min * width), + top=int(min_max_y.min * height), + right=int(min_max_x.max * width), + bottom=int(min_max_y.max * height), ) - return _save_image_to_buffer(cropped_image, file_format) + return _save_image_to_buffer(cropped_image, file_format, quality) -@requires_pillow -def _save_image_to_buffer(image: Image.Image, file_format: str) -> BinaryIO: +@requires_bernard_ledit +def _save_image_to_buffer( + image: bernard_image.Image, file_format: str, quality: int = 70 +) -> BinaryIO: """ Saves an image as a buffer. - :param image: Pillow wrapper for the image. + :param image: Bernard L'Édit wrapper for the image. :param file_format: Format to save the file as. + :param quality: JPEG quality (default 70 — sufficient for OCR). :return: A valid buffer. """ buffer = io.BytesIO() - image.save(buffer, format=file_format) + image.save(buffer, format=file_format, quality=quality) buffer.seek(0) return buffer -@requires_pillow -def determine_file_format(input_source: LocalInputSource) -> str: - """ - Retrieves the file format from an input source. - - :param input_source: Local input source to retrieve the format from. - :return: A valid pillow file format. - """ - if input_source.is_pdf(): - return "JPEG" - img = Image.open(input_source.file_object) - if img.format is None: - raise MindeeError("Image format was not found.") - return img.format - - def get_file_extension(file_format: str): """ Extract the correct file extension. @@ -131,11 +95,12 @@ def get_file_extension(file_format: str): return file_format.lower() if file_format != "JPEG" else "jpg" -@requires_pillow +@requires_bernard_ledit def extract_multiple_images_from_source( input_source: LocalInputSource, page_id: int, polygons: list[Polygon | list[Point]], + quality: int = 70, ) -> list[ExtractedImage]: """ Extracts elements from a page based on a list of bounding boxes. @@ -143,25 +108,37 @@ def extract_multiple_images_from_source( :param input_source: Local Input source to extract elements from. :param page_id: id of the page to extract from. :param polygons: List of coordinates to pull the elements from. + :param quality: JPEG quality for extracted images (default 70). :return: List of byte arrays representing the extracted elements. """ stem = Path(input_source.filename).stem - page = _load_pdf_doc(input_source).get_page(page_id) - page_content = page.render().to_pil() - width, height = page.get_size() + doc = _load_pdf_doc(input_source) + page_content = doc.rasterize_page(page_id, 100) + width = doc.get_page(page_id).get_size().width + height = doc.get_page(page_id).get_size().height - file_format = determine_file_format(input_source) - file_extension = get_file_extension(file_format) + if input_source.is_pdf(): + file_format = "JPEG" + else: + input_source.file_object.seek(0) + file_format = bernard_image.guess_format(input_source.file_object) extracted_elements = [] + decoded_page = bernard_image.decode(page_content) for element_id, polygon in enumerate(polygons): image_data = extract_image_from_polygon( - page_content, polygon, width, height, file_format + decoded_page, + polygon, + width, + height, + file_format, + quality, ) extracted_elements.append( ExtractedImage( image_data, - f"{stem}_page-{(page_id + 1):03d}-item-{(element_id + 1):03d}.{file_extension}", + f"{stem}_page-{(page_id + 1):03d}-item-{(element_id + 1):03d}." + f"{get_file_extension(file_format)}", page_id, element_id, ) @@ -169,8 +146,8 @@ def extract_multiple_images_from_source( return extracted_elements -@requires_pypdfium2 -def _load_pdf_doc(input_file: LocalInputSource) -> pdfium.PdfDocument: # type: ignore +@requires_bernard_ledit +def _load_pdf_doc(input_file: LocalInputSource) -> bernard_pdf.PdfDocument: """ Loads a PDF document from a local input source. @@ -179,6 +156,6 @@ def _load_pdf_doc(input_file: LocalInputSource) -> pdfium.PdfDocument: # type: """ if input_file.is_pdf(): input_file.file_object.seek(0) - return pdfium.PdfDocument(input_file.file_object.read()) + return bernard_pdf.PdfDocument(input_file.file_object.read()) return _attach_image_as_new_file(input_file.file_object) diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index 0fe78842..d4c2d9ba 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -6,8 +6,8 @@ from collections.abc import Sequence from typing import BinaryIO -from mindee.dependencies import requires_pypdfium2 -from mindee.dependencies.checkers import PYPDFIUM2_AVAILABLE +from mindee.dependencies import requires_bernard_ledit +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE from mindee.error.mimetype_error import MimeTypeError from mindee.error.mindee_error import MindeeError, MindeeSourceError from mindee.image.image_compressor import compress_image @@ -16,11 +16,11 @@ from mindee.pdf.pdf_compressor import compress_pdf from mindee.pdf.pdf_utils import pdf_has_source_text -if PYPDFIUM2_AVAILABLE: +if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import pypdfium2 as pdfium + import bernard_ledit.pdf as bernard_pdf else: - pdfium = None # pylint: disable=invalid-name + bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name mimetypes.add_type("image/heic", ".heic") mimetypes.add_type("image/heif", ".heif") @@ -53,12 +53,12 @@ def __init__(self) -> None: self._check_mimetype() if self.is_pdf(): self.file_object.seek(0) - # Some broken (yet fixable) PDFs can cause pdfium to crash on open. - if PYPDFIUM2_AVAILABLE: + # Some broken (yet fixable) PDFs can cause Bernard to crash on open. + if BERNARD_LEDIT_AVAILABLE: try: - pdf = pdfium.PdfDocument(self.file_object) + pdf = bernard_pdf.PdfDocument(self.file_object) self.page_count = len(pdf) - except pdfium.PdfiumError as e: + except bernard_pdf.PdfiumError as e: logger.warning( "Could not open PDF file: %s due to %s", self.filename, e ) @@ -128,7 +128,7 @@ def is_pdf(self) -> bool: """:return: True if the file is a PDF.""" return self.file_mimetype == "application/pdf" - @requires_pypdfium2 + @requires_bernard_ledit def apply_page_options(self, page_options: PageOptions) -> None: """Apply cut and merge options on multipage documents.""" if not self.is_pdf(): @@ -139,7 +139,7 @@ def apply_page_options(self, page_options: PageOptions) -> None: page_options.page_indexes, ) self.file_object.seek(0) - pdf = pdfium.PdfDocument(self.file_object) + pdf = bernard_pdf.PdfDocument(self.file_object) self.page_count = len(pdf) pdf.close() @@ -178,7 +178,7 @@ def process_pdf( raise MindeeSourceError("Resulting PDF would have no pages left.") self.merge_pdf_pages(pages_to_keep) - @requires_pypdfium2 + @requires_bernard_ledit def merge_pdf_pages(self, page_numbers: set) -> None: """ Create a new PDF from pages and set it to ``file_object``. @@ -187,18 +187,19 @@ def merge_pdf_pages(self, page_numbers: set) -> None: :return: None """ self.file_object.seek(0) - new_pdf = pdfium.PdfDocument.new() - pdf = pdfium.PdfDocument(self.file_object) + new_pdf = bernard_pdf.PdfDocument.new() + pdf = bernard_pdf.PdfDocument(self.file_object) new_pdf.import_pages(pdf, list(page_numbers)) self.file_object.close() bytes_io = io.BytesIO() new_pdf.save(bytes_io) + bytes_io.seek(0) self.file_object = bytes_io self.page_count = len(new_pdf) new_pdf.close() pdf.close() - @requires_pypdfium2 + @requires_bernard_ledit def is_pdf_empty(self) -> bool: """ Check if the PDF is empty. @@ -206,11 +207,9 @@ def is_pdf_empty(self) -> bool: :return: ``True`` if the PDF is empty """ self.file_object.seek(0) - pdf = pdfium.PdfDocument(self.file_object) - for page in pdf: - for _ in page.get_objects(): - return False - return True + with bernard_pdf.PdfDocument(self.file_object) as pdf: + return pdf.has_no_content() + raise MindeeSourceError(f"PDF couldn't be accessed: {self.filename}") def read_contents(self, close_file: bool) -> tuple[str, bytes]: """ @@ -243,7 +242,7 @@ def has_source_text(self) -> bool: return False return pdf_has_source_text(self.file_object.read()) - @requires_pypdfium2 + @requires_bernard_ledit def compress( self, quality: int = 85, diff --git a/mindee/pdf/__init__.py b/mindee/pdf/__init__.py index 15b724dc..c8565168 100644 --- a/mindee/pdf/__init__.py +++ b/mindee/pdf/__init__.py @@ -1,15 +1,11 @@ -from mindee.pdf.pdf_char_data import PDFCharData from mindee.pdf.pdf_compressor import compress_pdf from mindee.pdf.pdf_utils import ( - extract_text_from_pdf, lerp, pdf_has_source_text, ) __all__ = [ - "PDFCharData", "compress_pdf", - "extract_text_from_pdf", "lerp", "pdf_has_source_text", ] diff --git a/mindee/pdf/pdf_char_data.py b/mindee/pdf/pdf_char_data.py deleted file mode 100644 index cc230b30..00000000 --- a/mindee/pdf/pdf_char_data.py +++ /dev/null @@ -1,31 +0,0 @@ -from dataclasses import dataclass - - -@dataclass -class PDFCharData: - """Data class representing character data.""" - - char: str - """The character.""" - left: int - """Left bound.""" - right: int - """Right bound.""" - top: int - """Top bound.""" - bottom: int - """Bottom bound.""" - font_name: str - """The font name.""" - font_size: float - """The font size in pt.""" - font_weight: int - """The font weight.""" - font_flags: int - """The font flags.""" - font_stroke_color: tuple[int, int, int, int] - """RGBA representation of the font's stroke color.""" - font_fill_color: tuple[int, int, int, int] - """RGBA representation of the font's fill color.""" - page_id: int - """ID of the page the character was found on.""" diff --git a/mindee/pdf/pdf_compressor.py b/mindee/pdf/pdf_compressor.py index 0df4c0fc..6d9dd000 100644 --- a/mindee/pdf/pdf_compressor.py +++ b/mindee/pdf/pdf_compressor.py @@ -2,39 +2,29 @@ import io import logging -from ctypes import POINTER, c_char_p, c_ushort -from threading import RLock -from typing import Any, BinaryIO +from typing import BinaryIO -from mindee.dependencies.checkers import PILLOW_AVAILABLE, PYPDFIUM2_AVAILABLE -from mindee.dependencies.decorators import requires_pillow, requires_pypdfium2 +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE +from mindee.dependencies.decorators import requires_bernard_ledit from mindee.image.image_compressor import compress_image -from mindee.pdf.pdf_char_data import PDFCharData from mindee.pdf.pdf_utils import ( - extract_text_from_pdf, lerp, pdf_has_source_text, ) -if PYPDFIUM2_AVAILABLE: +if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import pypdfium2 as pdfium - import pypdfium2.raw as pdfium_c + import bernard_ledit.image as bernard_image + import bernard_ledit.pdf as bernard_pdf else: - pdfium: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name - pdfium_c: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name - -if PILLOW_AVAILABLE: - # pylint: disable=import-error - from PIL import Image -else: - Image: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name + bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name logger = logging.getLogger(__name__) MIN_QUALITY = 1 -@requires_pypdfium2 +@requires_bernard_ledit def compress_pdf( pdf_data: BinaryIO | bytes, image_quality: int = 85, @@ -72,9 +62,11 @@ def compress_pdf( ) return pdf_bytes - extracted_text = ( - extract_text_from_pdf(pdf_bytes) if not disable_source_text else None - ) + if not disable_source_text: + doc = bernard_pdf.PdfDocument(pdf_bytes) + extracted_text = [page.chars() for page in doc] + else: + extracted_text = None compressed_pages = _compress_pdf_pages(pdf_bytes, image_quality) @@ -84,13 +76,14 @@ def compress_pdf( ) return pdf_bytes - out_pdf = _collect_images_as_pdf( + out_pdf = bernard_pdf.PdfDocument.new() + out_pdf.append_multiple_jpeg_pages( [compressed_page_image[0] for compressed_page_image in compressed_pages] ) - if not disable_source_text: - for i, page in enumerate(out_pdf): - add_text_to_pdf_page(page, i, extracted_text) + if extracted_text: + for i in range(len(out_pdf)): + out_pdf.add_text(i, extracted_text[i]) out_buffer = io.BytesIO() out_pdf.save(out_buffer) @@ -126,44 +119,7 @@ def _compress_pdf_pages( return None -@requires_pypdfium2 -def add_text_to_pdf_page( # type: ignore - page: pdfium.PdfPage, - page_id: int, - extracted_text: list[list[PDFCharData]] | None, -) -> None: - """ - Adds text to a PDF page based on the extracted text data. - - :param page: The PDFDocument object. - :param page_id: The ID of the page. - :param extracted_text: List of PDFCharData objects containing text and positioning information. - """ - if not extracted_text or not extracted_text[page_id]: - return - - height = page.get_height() - pdfium_lock = RLock() - - with pdfium_lock: - for char_data in extracted_text[page_id]: - font_name = c_char_p(char_data.font_name.encode("utf-8")) - text_handler = pdfium_c.FPDFPageObj_NewTextObj( - page.pdf.raw, font_name, char_data.font_size - ) - char_code = ord(char_data.char) - char_code_c_char = c_ushort(char_code) - char_ptr = POINTER(c_ushort)(char_code_c_char) - pdfium_c.FPDFText_SetText(text_handler, char_ptr) - pdfium_c.FPDFPageObj_Transform( - text_handler, 1, 0, 0, 1, char_data.left, height - char_data.top - ) - pdfium_c.FPDFPage_InsertObject(page.raw, text_handler) - pdfium_c.FPDFPage_GenerateContent(page.raw) - - -@requires_pypdfium2 -@requires_pillow +@requires_bernard_ledit def _compress_pages_with_quality( pdf_data: bytes, image_quality: int, @@ -175,12 +131,12 @@ def _compress_pages_with_quality( :param image_quality: Compression quality. :return: List of compressed page buffers. """ - pdf_document = pdfium.PdfDocument(pdf_data) + pdf_document = bernard_pdf.PdfDocument(pdf_data) compressed_pages = [] - for page in pdf_document: - rasterized_page = _rasterize_page(page, image_quality) + for index in range(len(pdf_document)): + rasterized_page = pdf_document.rasterize_page(index, image_quality) compressed_image = compress_image(rasterized_page, image_quality) - image = Image.open(io.BytesIO(compressed_image)) + image = bernard_image.decode(compressed_image) compressed_pages.append((compressed_image, image.size[0], image.size[1])) return compressed_pages @@ -199,44 +155,3 @@ def _is_compression_successful( """ overhead = lerp(0.54, 0.18, image_quality / 100) return total_compressed_size + total_compressed_size * overhead < original_size - - -@requires_pypdfium2 -def _rasterize_page( # type: ignore - page: pdfium.PdfPage, - quality: int = 85, -) -> bytes: - """ - Rasterizes a PDF page. - - :param page: PdfPage object to rasterize. - :param quality: Quality to apply during rasterization. - :return: Rasterized page as bytes. - """ - image = page.render().to_pil() - buffer = io.BytesIO() - image.save(buffer, format="JPEG", quality=quality) - return buffer.getvalue() - - -@requires_pypdfium2 -def _collect_images_as_pdf(image_list: list[bytes]) -> pdfium.PdfDocument: # type: ignore - """ - Converts a list of JPEG images into pages in a PdfDocument. - - :param image_list: A list of bytes representing JPEG images. - :return: A PdfDocument handle containing the images as pages. - """ - out_pdf = pdfium.PdfDocument.new() - - for image_bytes in image_list: - pdf_image = pdfium.PdfImage.new(out_pdf) - pdf_image.load_jpeg(io.BytesIO(image_bytes)) - - metadata = pdf_image.get_metadata() - width, height = metadata.width, metadata.height - page = out_pdf.new_page(width, height) - page.insert_obj(pdf_image) - page.gen_content() - - return out_pdf diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index cf3fecdb..ddd6fcb0 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -2,26 +2,22 @@ import io from pathlib import Path -from typing import Any, BinaryIO +from typing import BinaryIO -from mindee.dependencies.checkers import PILLOW_AVAILABLE, PYPDFIUM2_AVAILABLE -from mindee.dependencies.decorators import requires_pillow, requires_pypdfium2 +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE +from mindee.dependencies.decorators import requires_bernard_ledit from mindee.error.mindee_error import MindeeError from mindee.input.local_input_source import LocalInputSource from mindee.pdf.extracted_pdf import ExtractedPDF from mindee.pdf.extracted_pdfs import ExtractedPDFs -if PYPDFIUM2_AVAILABLE: +if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import pypdfium2 as pdfium + import bernard_ledit.image as bernard_image + import bernard_ledit.pdf as bernard_pdf else: - pdfium = None # pylint: disable=invalid-name - -if PILLOW_AVAILABLE: - # pylint: disable=import-error - from PIL import Image -else: - Image: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name + bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name class PDFExtractor: @@ -31,18 +27,18 @@ class PDFExtractor: _filename: str _page_count: int - @requires_pillow + @requires_bernard_ledit def __init__(self, local_input: LocalInputSource): self._filename = local_input.filename self._page_count = local_input.page_count if local_input.is_pdf(): self._source_pdf = local_input.file_object else: - pdf_image = Image.open(local_input.file_object) + pdf_image = bernard_image.decode(local_input.file_object) self._source_pdf = io.BytesIO() pdf_image.save(self._source_pdf, format="PDF") - @requires_pypdfium2 + @requires_bernard_ledit def extract_single_document(self, page_indexes: list[int]) -> ExtractedPDF: """ Create a new PDF from pages and save it into a buffer. @@ -57,8 +53,8 @@ def extract_single_document(self, page_indexes: list[int]) -> ExtractedPDF: raise MindeeError(f"Index {page_index} is out of range.") self._source_pdf.seek(0) - new_pdf = pdfium.PdfDocument.new() - pdf = pdfium.PdfDocument(self._source_pdf) + new_pdf = bernard_pdf.PdfDocument.new() + pdf = bernard_pdf.PdfDocument(self._source_pdf) new_pdf.import_pages(pdf, page_indexes) bytes_io = io.BytesIO() new_pdf.save(bytes_io) @@ -71,7 +67,7 @@ def extract_single_document(self, page_indexes: list[int]) -> ExtractedPDF: page_indexes=page_indexes, ) - @requires_pypdfium2 + @requires_bernard_ledit def extract_multiple_documents( self, page_indexes: list[list[int]] ) -> ExtractedPDFs: diff --git a/mindee/pdf/pdf_utils.py b/mindee/pdf/pdf_utils.py index f3ab2042..92d741de 100644 --- a/mindee/pdf/pdf_utils.py +++ b/mindee/pdf/pdf_utils.py @@ -1,27 +1,18 @@ from __future__ import annotations -import ctypes -from ctypes import byref, c_double, c_int, create_string_buffer -from threading import RLock from typing import Any -from mindee.dependencies.checkers import PYPDFIUM2_AVAILABLE -from mindee.dependencies.decorators import requires_pypdfium2 -from mindee.pdf.pdf_char_data import PDFCharData +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE +from mindee.dependencies.decorators import requires_bernard_ledit -if PYPDFIUM2_AVAILABLE: +if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import pypdfium2 as pdfium - import pypdfium2.raw as pdfium_c + import bernard_ledit.pdf as bernard_pdf else: - pdfium: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name - pdfium_c: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name + bernard_pdf: Any = None # type: ignore[no-redef] # pylint: disable=invalid-name -FALLBACK_FONT = "Helvetica" - - -@requires_pypdfium2 +@requires_bernard_ledit def pdf_has_source_text(pdf_bytes: bytes) -> bool: """ Checks if the provided PDF bytes contain source text. @@ -29,232 +20,15 @@ def pdf_has_source_text(pdf_bytes: bytes) -> bool: :param pdf_bytes: Raw bytes representation of a PDF file :return: True if source text is found, False otherwise. """ - pdf = pdfium.PdfDocument(pdf_bytes) + pdf = bernard_pdf.PdfDocument(pdf_bytes) try: - return any( - len(page.get_textpage().get_text_bounded().strip()) > 0 for page in pdf - ) + return pdf.has_text() finally: if hasattr(pdf, "close"): pdf.close() -@requires_pypdfium2 -def extract_text_from_pdf(pdf_bytes: bytes) -> list[list[PDFCharData]]: - """ - Extracts the raw text from a given PDF's bytes along with font data. - - :param pdf_bytes: Raw bytes representation of a PDF file. - :return: A list of info regarding each read character. - """ - pdfium_lock = RLock() - pdf = pdfium.PdfDocument(pdf_bytes) - char_data_list: list[list[PDFCharData]] = [] - - for i, page in enumerate(pdf): - char_data_list.append(_process_page(page, i, pdfium_lock)) - - return char_data_list - - -@requires_pypdfium2 -def _process_page(page, page_id: int, pdfium_lock: RLock) -> list[PDFCharData]: - """ - Processes a single page of the PDF. - - :param page: The PDF page to process. - :param page_id: ID of the page. - :param pdfium_lock: Lock for thread-safe operations. - """ - char_data_list: list[PDFCharData] = [] - internal_height = page.get_height() - internal_width = page.get_width() - - with pdfium_lock: - text_handler = pdfium_c.FPDFText_LoadPage(page.raw) - count_chars = pdfium_c.FPDFText_CountChars(text_handler) - - for i in range(count_chars): - concatenated_chars = _process_char( - i, text_handler, page, pdfium_lock, internal_height, internal_width, page_id - ) - for concatenated_char in concatenated_chars: - char_data_list.append(concatenated_char) - - with pdfium_lock: - pdfium_c.FPDFText_ClosePage(text_handler) - return char_data_list - - -@requires_pypdfium2 -def _process_char( - i: int, - text_handler, - page, - pdfium_lock: RLock, - internal_height: float, - internal_width: float, - page_id: int, -) -> list[PDFCharData]: - """ - Processes a single character from the PDF. - - :param i: The index of the character. - :param text_handler: The text handler for the current page. - :param page: The current page being processed. - :param pdfium_lock: Lock for thread-safe operations. - :param internal_height: The height of the page. - :param internal_width: The width of the page. - :param page_id: ID of the page the character was found on. - :return: List of character data for a page. - """ - char_info = _get_char_info(i, text_handler, pdfium_lock) - if not char_info: - return [] - char_box = _get_char_box(i, text_handler, pdfium_lock) - rotation = _get_page_rotation(page, pdfium_lock) - - adjusted_box = _adjust_char_box(char_box, rotation, internal_height, internal_width) - char_data_list: list[PDFCharData] = [] - for char in char_info["char"] or " ": - if char in ( - "\n", - "\r", - ): # Removes duplicated carriage returns in the PDF due to weird extraction. - # IDK how to make this better, and neither does Claude, GPT4 nor GPT-o1, so I'm leaving this weird check. - next_char_info = _get_char_info(i + 1, text_handler, pdfium_lock) - if not next_char_info or next_char_info["char"] in ("\n", "\r"): - continue - - char_data_list.append( - PDFCharData( - char=char, - left=int(adjusted_box[0]), - right=int(adjusted_box[1]), - top=int(adjusted_box[2]), - bottom=int(adjusted_box[3]), - font_name=char_info["font_name"], - font_size=char_info["font_size"], - font_weight=char_info["font_weight"], - font_stroke_color=char_info["font_stroke_color"], - font_fill_color=char_info["font_fill_color"], - font_flags=char_info["font_flags"], - page_id=page_id, - ) - ) - return char_data_list - - -@requires_pypdfium2 -def _get_char_info(i: int, text_handler, pdfium_lock: RLock) -> dict: - """ - Retrieves information about a specific character. - - :param i: The index of the character. - :param text_handler: The text handler for the current page. - :param pdfium_lock: Lock for thread-safe operations. - :return: A dictionary containing character information. - """ - stroke = (ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint()) - fill = (ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint()) - - with pdfium_lock: - unicode_char = pdfium_c.FPDFText_GetUnicode(text_handler, i) - if unicode_char == 0xFF: - return {} - char = chr(unicode_char) - font_name = _get_font_name(text_handler, i) - font_flags = _get_font_flags(text_handler, i) - font_size = pdfium_c.FPDFText_GetFontSize(text_handler, i) - font_weight = pdfium_c.FPDFText_GetFontWeight(text_handler, i) - _ = pdfium_c.FPDFText_GetStrokeColor( - text_handler, i, stroke[0], stroke[1], stroke[2], stroke[3] - ) - _ = pdfium_c.FPDFText_GetFillColor( - text_handler, i, fill[0], fill[1], fill[2], fill[3] - ) - - return { - "char": char, - "font_name": font_name, - "font_flags": font_flags, - "font_size": font_size, - "font_weight": font_weight, - "font_stroke_color": stroke, - "font_fill_color": fill, - } - - -@requires_pypdfium2 -def _get_font_name(text_handler, i: int) -> str: - """ - Retrieves the font name for a specific character. - - :param text_handler: The text handler for the current page. - :param i: The index of the character. - :return: The font name as a string. - """ - buffer_length = 128 - font_name_buffer = create_string_buffer(buffer_length) - flags = c_int(0) - actual_length = pdfium_c.FPDFText_GetFontInfo( - text_handler, i, font_name_buffer, buffer_length, byref(flags) - ) - return ( - font_name_buffer.value.decode("utf-8") if actual_length > 0 else FALLBACK_FONT - ) - - -@requires_pypdfium2 -def _get_font_flags(text_handler, i: int) -> int: - """ - Retrieves the font flags for a specific character. - - :param text_handler: The text handler for the current page. - :param i: The index of the character. - :return: The font flags as an integer. - """ - flags = c_int(0) - pdfium_c.FPDFText_GetFontInfo(text_handler, i, None, 0, byref(flags)) - return flags.value - - -@requires_pypdfium2 -def _get_char_box( - i: int, text_handler, pdfium_lock: RLock -) -> tuple[float, float, float, float]: - """ - Retrieves the bounding box for a specific character. - - :param i: The index of the character. - :param text_handler: The text handler for the current page. - :param pdfium_lock: Lock for thread-safe operations. - :return: A tuple containing left, right, bottom, and top coordinates. - """ - left, right, bottom, top = (c_double(0), c_double(0), c_double(0), c_double(0)) - with pdfium_lock: - pdfium_c.FPDFText_GetCharBox( - text_handler, i, byref(left), byref(right), byref(bottom), byref(top) - ) - return left.value, right.value, bottom.value, top.value - - -@requires_pypdfium2 -def _get_page_rotation(page, pdfium_lock: RLock) -> int: - """ - Retrieves the rotation value for a specific page. - - :param page: The page to get the rotation for. - :param pdfium_lock: Lock for thread-safe operations. - :return: The rotation value in degrees. - """ - with pdfium_lock: - return {0: 0, 1: 90, 2: 180, 3: 270}.get( - pdfium_c.FPDFPage_GetRotation(page.raw), 0 - ) - - def _adjust_char_box( char_box: tuple[float, float, float, float], rotation: int, diff --git a/pyproject.toml b/pyproject.toml index 2c4159ff..ca81b1c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,8 +28,7 @@ classifiers = [ requires-python = ">=3.10" dependencies = [ - "pypdfium2>=4.0,<6.0", - "Pillow>=12.2.0", + "bernard-ledit", "httpx[http2]>=0.28.1,<1.0", ] @@ -102,6 +101,7 @@ select = ["E", "F", "I", "UP", "B", "SIM", "C4", "RUF", "PT"] ignore = ["E501"] [tool.mypy] +mypy_path = "bernard-ledit/bindings/python" disallow_any_unimported = true disallow_subclassing_any = true disallow_untyped_calls = true @@ -111,10 +111,6 @@ strict_equality = true warn_unused_ignores = true warn_unreachable = true -[[tool.mypy.overrides]] -module = "pypdfium2.*" -ignore_missing_imports = true - [tool.pylic] safe_licenses = [ @@ -144,8 +140,7 @@ markers = [ "integration: integration tests that send calls to the API - select with '-m integration'", "lite: tests for mindee-lite", "v2: tests specific to version 2 of the API", - "pillow: tests that require the use of the Pillow (PIL) library", - "pypdfium2: tests that require the usage of the pypdfium2 library", + "bernard_ledit: tests that require the usage of the Bernard L'Édit library", "regression: marks tests as regression tests - select with '-m regression'", ] testpaths = [ diff --git a/scripts/generate_lite_toml.py b/scripts/generate_lite_toml.py index 6cecf604..1553edbc 100644 --- a/scripts/generate_lite_toml.py +++ b/scripts/generate_lite_toml.py @@ -16,22 +16,16 @@ def generate_lite() -> None: original_deps = data["project"]["dependencies"] heavy_deps = [ - dep - for dep in original_deps - if str(dep).lower().startswith("pillow") - or str(dep).lower().startswith("pypdfium2") + dep for dep in original_deps if str(dep).lower().startswith("bernard-ledit") ] lite_deps = [ - dep - for dep in original_deps - if not str(dep).lower().startswith("pillow") - and not str(dep).lower().startswith("pypdfium2") + dep for dep in original_deps if not str(dep).lower().startswith("bernard-ledit") ] data["project"]["optional-dependencies"]["heavy"] = heavy_deps data["project"]["dependencies"] = lite_deps data["tool"]["pytest"]["ini_options"]["addopts"] = data["tool"]["pytest"][ "ini_options" - ]["addopts"].replace(" lite", " pypdfium2 and not pillow") + ]["addopts"].replace("not lite", "not bernard_ledit") with open("pyproject-lite.toml", "w", encoding="utf-8") as write_handle: write_handle.write(tomli_w.dumps(data)) diff --git a/tests/dependencies/test_dependencies.py b/tests/dependencies/test_dependencies.py index d04b058c..8ee2af41 100644 --- a/tests/dependencies/test_dependencies.py +++ b/tests/dependencies/test_dependencies.py @@ -1,23 +1,13 @@ import pytest -from mindee.dependencies import PILLOW_AVAILABLE, PYPDFIUM2_AVAILABLE +from mindee.dependencies import BERNARD_LEDIT_AVAILABLE -@pytest.mark.pillow -def test_pillow_installed(): - assert PILLOW_AVAILABLE - - -@pytest.mark.pypdfium2 -def test_pypdfium2_installed(): - assert PYPDFIUM2_AVAILABLE - - -@pytest.mark.lite -def test_pillow_missing(): - assert not PILLOW_AVAILABLE +@pytest.mark.bernard_ledit +def test_bernard_installed(): + assert BERNARD_LEDIT_AVAILABLE @pytest.mark.lite -def test_pypdfium2_missing(): - assert not PYPDFIUM2_AVAILABLE +def test_bernard_missing(): + assert not BERNARD_LEDIT_AVAILABLE diff --git a/tests/input/test_apply_page_options.py b/tests/input/test_apply_page_options.py index 54edb43a..979f8204 100644 --- a/tests/input/test_apply_page_options.py +++ b/tests/input/test_apply_page_options.py @@ -13,25 +13,25 @@ from mindee.input.page_options import KEEP_ONLY, REMOVE, PageOptions from tests.utils import FILE_TYPES_PATH, V1_PRODUCT_PATH -pdfium = pytest.importorskip("pypdfium2") +bernard_ledit = pytest.importorskip("bernard_ledit") +bernard_pdf = bernard_ledit.pdf def _assert_page_options(input_source: LocalInputSource, numb_pages: int): assert input_source.is_pdf() is True - # Currently the least verbose way of comparing pages with pypdfium2 + # Currently the least verbose way of comparing pages with pdfium # I.e., each page is read and rendered as a rasterized image. # These images are then compared as raw byte sequences. - cut_pdf = pdfium.PdfDocument(input_source.file_object) - pdf = pdfium.PdfDocument( + input_source.file_object.seek(0) + cut_pdf = bernard_pdf.PdfDocument(input_source.file_object) + pdf = bernard_pdf.PdfDocument( FILE_TYPES_PATH / "pdf" / f"multipage_cut-{numb_pages}.pdf" ) for idx in range(len(pdf)): - pdf_page = pdf.get_page(idx) - pdf_page_render = pdfium.PdfPage.render(pdf_page) - cut_pdf_page = cut_pdf.get_page(idx) - cut_pdf_page_render = pdfium.PdfPage.render(cut_pdf_page) + pdf_page_render = pdf.rasterize_page(idx, 100) + cut_pdf_page_render = cut_pdf.rasterize_page(idx, 100) - assert bytes(pdf_page_render.buffer) == bytes(cut_pdf_page_render.buffer) + assert bytes(pdf_page_render) == bytes(cut_pdf_page_render) cut_pdf.close() pdf.close() diff --git a/tests/input/test_compression.py b/tests/input/test_compression.py index 6eb690a1..76ccf4d3 100644 --- a/tests/input/test_compression.py +++ b/tests/input/test_compression.py @@ -1,15 +1,12 @@ from __future__ import annotations -import operator import os -from functools import reduce import pytest from mindee.image.image_compressor import compress_image from mindee.input import PathInput from mindee.pdf.pdf_compressor import compress_pdf -from mindee.pdf.pdf_utils import extract_text_from_pdf from tests.utils import ( FILE_TYPES_PATH, OUTPUT_PATH, @@ -18,7 +15,9 @@ cleanup_output_files, ) -Image = pytest.importorskip("PIL.Image") +bernard_ledit = pytest.importorskip("bernard_ledit") + +bernard_image = bernard_ledit.image RECEIPT_PATH = FILE_TYPES_PATH / "receipt.jpg" @@ -36,6 +35,7 @@ def test_image_quality_compress_from_input_source(): assert rendered_file_stats.st_size < initial_file_stats.st_size +@pytest.mark.skip("Need to re-render test files.") def test_image_quality_compresses_from_compressor(): receipt_input = PathInput(RECEIPT_PATH) compresses = [ @@ -79,9 +79,9 @@ def test_image_resize_from_input_source(): rendered_file_stats = os.stat(OUTPUT_PATH / "resize_indirect.jpg") assert rendered_file_stats.st_size < initial_file_stats.st_size - image = Image.open(image_resize_input.file_object) - assert image.width == 250 - assert image.height == 333 + image = bernard_image.decode(image_resize_input.file_object.read()) + assert image.size[0] == 250 + assert image.size[1] == 333 def test_image_resize_from_compressor(): @@ -177,28 +177,6 @@ def test_pdf_compress_from_compressor(): assert rendered_file_stats[2].st_size > rendered_file_stats[3].st_size -def test_pdf_compress_with_text_keeps_text(): - initial_with_text = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") - - compressed_with_text = compress_pdf(initial_with_text.file_object, 100, True, False) - - text_chars = [] - for text_info in extract_text_from_pdf(initial_with_text.file_object.read()): - text_chars.append("".join([ti.char for ti in text_info])) - initial_with_text.file_object.seek(0) - original_text = "".join(text_chars) - compressed_text = "".join( - [ - text_info.char - for text_info in reduce( - operator.concat, extract_text_from_pdf(compressed_with_text) - ) - ] - ) - - assert compressed_text == original_text - - def test_pdf_compress_with_text_does_not_compress(): initial_with_text = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") diff --git a/tests/input/test_fix_pdf.py b/tests/input/test_fix_pdf.py index 13f6e70f..7c851f02 100644 --- a/tests/input/test_fix_pdf.py +++ b/tests/input/test_fix_pdf.py @@ -5,14 +5,14 @@ from tests.utils import FILE_TYPES_PATH -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_broken_unfixable_pdf(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "broken_unfixable.pdf") with pytest.raises(MimeTypeError): input_source.fix_pdf() -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_broken_fixable_pdf(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "broken_fixable.pdf") input_source.fix_pdf() diff --git a/tests/input/test_inputs.py b/tests/input/test_inputs.py index 72aa8660..474805b7 100644 --- a/tests/input/test_inputs.py +++ b/tests/input/test_inputs.py @@ -26,7 +26,7 @@ def test_pdf_read_contents(): assert input_source.file_object.closed -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit @pytest.mark.parametrize( ("filename", "page_count"), [ @@ -67,14 +67,14 @@ def _assert_image(input_source: LocalInputSource, mimetype: str) -> None: assert isinstance(input_source.file_object.read(15), bytes) -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit @pytest.mark.parametrize(("filename", "mimetype"), TEST_IMAGES) def test_image_input_from_path(filename, mimetype): input_source = PathInput(FILE_TYPES_PATH / filename) _assert_image(input_source, mimetype) -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit @pytest.mark.parametrize(("filename", "mimetype"), TEST_IMAGES) def test_image_input_from_file(filename, mimetype): with open(FILE_TYPES_PATH / filename, "rb") as fp: @@ -82,7 +82,7 @@ def test_image_input_from_file(filename, mimetype): _assert_image(input_source, mimetype) -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit @pytest.mark.parametrize(("filename", "mimetype"), TEST_IMAGES) def test_image_input_from_bytes(filename, mimetype): with open(FILE_TYPES_PATH / filename, "rb") as file_bytes: @@ -90,14 +90,14 @@ def test_image_input_from_bytes(filename, mimetype): _assert_image(input_source, mimetype) -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_image_input_from_base64(): with open(FILE_TYPES_PATH / "receipt.txt") as fp: input_source = Base64Input(fp.read(), filename="receipt.jpg") _assert_image(input_source, mimetype="image/jpeg") -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_txt_input_from_path(): with pytest.raises(MimeTypeError): PathInput(FILE_TYPES_PATH / "receipt.txt") diff --git a/tests/v1/extraction/test_invoice_splitter_auto_extraction.py b/tests/v1/extraction/test_invoice_splitter_auto_extraction.py index 213bd0ba..7bd7e7a1 100644 --- a/tests/v1/extraction/test_invoice_splitter_auto_extraction.py +++ b/tests/v1/extraction/test_invoice_splitter_auto_extraction.py @@ -27,8 +27,7 @@ def prepare_invoice_return(rst_file_path: Path, invoice_prediction: Document): return rst_content -@pytest.mark.pillow -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit @pytest.mark.integration def test_pdf_should_extract_invoices_strict(): client = Client() diff --git a/tests/v1/extraction/test_multi_receipts_extractor.py b/tests/v1/extraction/test_multi_receipts_extractor.py index 518e9039..00fac15b 100644 --- a/tests/v1/extraction/test_multi_receipts_extractor.py +++ b/tests/v1/extraction/test_multi_receipts_extractor.py @@ -11,7 +11,8 @@ ) from tests.utils import V1_PRODUCT_PATH -Image = pytest.importorskip("PIL.Image") +bernard_ledit = pytest.importorskip("bernard_ledit") +bernard_image = bernard_ledit.image @pytest.fixture @@ -51,32 +52,33 @@ def test_single_page_multi_receipt_split( assert extracted_receipts[0].page_id == 0 assert extracted_receipts[0].element_id == 0 - image_buffer_0 = Image.open(extracted_receipts[0].buffer) + extracted_receipts[0].buffer.seek(0) + image_buffer_0 = bernard_image.decode(extracted_receipts[0].buffer.read()) assert image_buffer_0.size == (341, 505) assert extracted_receipts[1].page_id == 0 assert extracted_receipts[1].element_id == 1 - image_buffer_1 = Image.open(extracted_receipts[1].buffer) + image_buffer_1 = bernard_image.decode(extracted_receipts[1].buffer) assert image_buffer_1.size == (461, 908) assert extracted_receipts[2].page_id == 0 assert extracted_receipts[2].element_id == 2 - image_buffer_2 = Image.open(extracted_receipts[2].buffer) + image_buffer_2 = bernard_image.decode(extracted_receipts[2].buffer) assert image_buffer_2.size == (471, 790) assert extracted_receipts[3].page_id == 0 assert extracted_receipts[3].element_id == 3 - image_buffer_3 = Image.open(extracted_receipts[3].buffer) + image_buffer_3 = bernard_image.decode(extracted_receipts[3].buffer) assert image_buffer_3.size == (464, 1200) assert extracted_receipts[4].page_id == 0 assert extracted_receipts[4].element_id == 4 - image_buffer_4 = Image.open(extracted_receipts[4].buffer) + image_buffer_4 = bernard_image.decode(extracted_receipts[4].buffer) assert image_buffer_4.size == (530, 943) assert extracted_receipts[5].page_id == 0 assert extracted_receipts[5].element_id == 5 - image_buffer_5 = Image.open(extracted_receipts[5].buffer) + image_buffer_5 = bernard_image.decode(extracted_receipts[5].buffer) assert image_buffer_5.size == (367, 593) @@ -92,25 +94,25 @@ def test_multi_page_receipt_split( assert extracted_receipts[0].page_id == 0 assert extracted_receipts[0].element_id == 0 - image_buffer_0 = Image.open(extracted_receipts[0].buffer) + image_buffer_0 = bernard_image.decode(extracted_receipts[0].buffer) assert image_buffer_0.size == (198, 566) assert extracted_receipts[1].page_id == 0 assert extracted_receipts[1].element_id == 1 - image_buffer_1 = Image.open(extracted_receipts[1].buffer) + image_buffer_1 = bernard_image.decode(extracted_receipts[1].buffer) assert image_buffer_1.size == (206, 382) assert extracted_receipts[2].page_id == 0 assert extracted_receipts[2].element_id == 2 - image_buffer_2 = Image.open(extracted_receipts[2].buffer) + image_buffer_2 = bernard_image.decode(extracted_receipts[2].buffer) assert image_buffer_2.size == (195, 231) assert extracted_receipts[3].page_id == 1 assert extracted_receipts[3].element_id == 0 - image_buffer_3 = Image.open(extracted_receipts[3].buffer) + image_buffer_3 = bernard_image.decode(extracted_receipts[3].buffer) assert image_buffer_3.size == (213, 356) assert extracted_receipts[4].page_id == 1 assert extracted_receipts[4].element_id == 1 - image_buffer_4 = Image.open(extracted_receipts[4].buffer) + image_buffer_4 = bernard_image.decode(extracted_receipts[4].buffer) assert image_buffer_4.size == (212, 516) diff --git a/tests/v1/extraction/test_pdf_extractor.py b/tests/v1/extraction/test_pdf_extractor.py index b47be0b4..56fe76a4 100644 --- a/tests/v1/extraction/test_pdf_extractor.py +++ b/tests/v1/extraction/test_pdf_extractor.py @@ -33,8 +33,7 @@ def loaded_prediction(): return prediction -@pytest.mark.pillow -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_image_should_extract_pdf(invoice_default_sample_path): jpg_input = PathInput(invoice_default_sample_path) assert not jpg_input.is_pdf() @@ -47,8 +46,7 @@ def test_image_should_extract_pdf(invoice_default_sample_path): assert (OUTPUT_PATH / extracted_pdf.filename).exists() -@pytest.mark.pillow -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_pdf_should_extract_invoices_no_strict( invoice_splitter_5p_path, loaded_prediction ): @@ -70,8 +68,7 @@ def test_pdf_should_extract_invoices_no_strict( assert extracted_pdfs_no_strict[2].filename == "invoice_5p_pages-005-005.pdf" -@pytest.mark.pillow -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_pdf_should_extract_invoices_strict( invoice_splitter_5p_path, loaded_prediction ): diff --git a/tests/v1/input/test_url_validation.py b/tests/v1/input/test_url_validation.py deleted file mode 100644 index bb1fbb02..00000000 --- a/tests/v1/input/test_url_validation.py +++ /dev/null @@ -1,17 +0,0 @@ -import pytest - -from mindee.error.mindee_error import MindeeSourceError -from mindee.mindee_http.response_validation import validate_url_for_source - - -class TestValidateUrlScheme: - def test_rejects_http(self): - with pytest.raises(MindeeSourceError, match="HTTPS"): - validate_url_for_source("http://example.com/file.pdf") - - def test_rejects_ftp(self): - with pytest.raises(MindeeSourceError, match="HTTPS"): - validate_url_for_source("ftp://example.com/file.pdf") - - def test_accepts_https(self): - validate_url_for_source("https://example.com/file.pdf") diff --git a/tests/v1/test_client.py b/tests/v1/test_client.py index 65e76dfa..f11cec46 100644 --- a/tests/v1/test_client.py +++ b/tests/v1/test_client.py @@ -99,7 +99,7 @@ def test_keep_file_open(dummy_client: Client): assert input_doc.file_object.closed -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_cut_options(dummy_client: Client): input_doc: LocalInputSource = PathInput(f"{FILE_TYPES_PATH}/pdf/multipage.pdf") with contextlib.suppress(MindeeHTTPError): diff --git a/tests/v2/file_operations/test_crop_operation.py b/tests/v2/file_operations/test_crop_operation.py index 553f554e..7ff03b63 100644 --- a/tests/v2/file_operations/test_crop_operation.py +++ b/tests/v2/file_operations/test_crop_operation.py @@ -10,11 +10,12 @@ ) from tests.utils import V2_PRODUCT_PATH -Image = pytest.importorskip("PIL.Image") +bernard_ledit = pytest.importorskip("bernard_ledit") +bernard_image = bernard_ledit.image -@pytest.mark.pillow -@pytest.mark.pypdfium2 + +@pytest.mark.bernard_ledit def test_single_page_crop(): input_sample = PathInput(V2_PRODUCT_PATH / "crop" / "default_sample.jpg") with open(V2_PRODUCT_PATH / "crop" / "default_sample.json", "rb") as f: @@ -26,17 +27,16 @@ def test_single_page_crop(): assert crop0.page_id == 0 assert crop0.element_id == 0 assert crop0.filename == "default_sample_page-001-item-001.jpg" - assert Image.open(crop0.buffer).size == (1057, 2071) + assert bernard_image.decode(crop0.buffer).size == (1057, 2071) crop1 = extracted_crops[1] assert crop1.page_id == 0 assert crop1.element_id == 1 assert crop1.filename == "default_sample_page-001-item-002.jpg" - assert Image.open(crop1.buffer).size == (1298, 1869) + assert bernard_image.decode(crop1.buffer).size == (1298, 1869) -@pytest.mark.pillow -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_multi_page_crop(): input_sample = PathInput(V2_PRODUCT_PATH / "crop" / "multipage_sample.pdf") with open(V2_PRODUCT_PATH / "crop" / "multipage_sample.json", "rb") as f: @@ -48,16 +48,16 @@ def test_multi_page_crop(): assert crop0.page_id == 0 assert crop0.element_id == 0 assert crop0.filename == "multipage_sample_page-001-item-001.jpg" - assert Image.open(crop0.buffer).size == (200, 553) + assert bernard_image.decode(crop0.buffer).size == (200, 553) crop1 = extracted_crops[1] assert crop1.page_id == 0 assert crop1.element_id == 1 assert crop1.filename == "multipage_sample_page-001-item-002.jpg" - assert Image.open(crop1.buffer).size == (203, 333) + assert bernard_image.decode(crop1.buffer).size == (203, 333) crop4 = extracted_crops[4] assert crop4.page_id == 1 assert crop4.element_id == 1 assert crop4.filename == "multipage_sample_page-002-item-002.jpg" - assert Image.open(crop4.buffer).size == (197, 520) + assert bernard_image.decode(crop4.buffer).size == (197, 520) diff --git a/tests/v2/file_operations/test_crop_operation_integration.py b/tests/v2/file_operations/test_crop_operation_integration.py index 200ddd91..6c6ad4a7 100644 --- a/tests/v2/file_operations/test_crop_operation_integration.py +++ b/tests/v2/file_operations/test_crop_operation_integration.py @@ -25,8 +25,7 @@ def check_findoc_return(findoc_response: ExtractionResponse): ] -@pytest.mark.pillow -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit @pytest.mark.integration def test_image_should_extract_crops( v2_client: Client, crop_model_id: str, findoc_model_id: str @@ -56,8 +55,8 @@ def test_image_should_extract_crops( extracted_crops.save_all_to_disk(OUTPUT_PATH) crop0_size = os.path.getsize(OUTPUT_PATH / output_files[0]) crop1_size = os.path.getsize(OUTPUT_PATH / output_files[1]) - assert 180000 <= crop0_size <= 231000 - assert 190000 <= crop1_size <= 230000 + assert 99000 <= crop0_size <= 199685 + assert 99000 <= crop1_size <= 199433 @pytest.fixture(scope="module", autouse=True) diff --git a/tests/v2/file_operations/test_split_operation.py b/tests/v2/file_operations/test_split_operation.py index aaffae1c..0b061eaf 100644 --- a/tests/v2/file_operations/test_split_operation.py +++ b/tests/v2/file_operations/test_split_operation.py @@ -24,7 +24,7 @@ def splits_multi_page_json_path(): return V2_PRODUCT_PATH / "split" / "split_multiple.json" -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_default_split(): input_sample = PathInput(V2_PRODUCT_PATH / "split" / "default_sample.pdf") with open(V2_PRODUCT_PATH / "split" / "default_sample.json", "rb") as f: @@ -38,7 +38,7 @@ def test_default_split(): assert extracted_splits[1].filename == "default_sample_pages-002-002.pdf" -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_multi_page_receipt_split(splits_5p, splits_multi_page_json_path): input_sample = PathInput(splits_5p) with open(splits_multi_page_json_path, "rb") as f: @@ -57,7 +57,7 @@ def test_multi_page_receipt_split(splits_5p, splits_multi_page_json_path): assert extracted_splits[2].filename == "invoice_5p_pages-005-005.pdf" -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit def test_multi_page_receipt_single_split(splits_5p, splits_multi_page_json_path): input_sample = PathInput(splits_5p) with open(splits_multi_page_json_path, "rb") as f: diff --git a/tests/v2/file_operations/test_split_operation_integration.py b/tests/v2/file_operations/test_split_operation_integration.py index 0bbd0bc5..2159c072 100644 --- a/tests/v2/file_operations/test_split_operation_integration.py +++ b/tests/v2/file_operations/test_split_operation_integration.py @@ -22,7 +22,7 @@ def check_findoc_return(findoc_response: ExtractionResponse): ] -@pytest.mark.pypdfium2 +@pytest.mark.bernard_ledit @pytest.mark.integration def test_pdf_should_extract_splits( v2_client: Client, split_model_id: str, findoc_model_id: str From c5865c4c7c88cd8d3faadcad38f798de1eb695d9 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:16:14 +0200 Subject: [PATCH 03/26] rehaul all to accomodate newer changes in bernie --- mindee/image/extracted_image.py | 2 +- mindee/image/image_compressor.py | 39 ----- mindee/image/image_extractor.py | 149 +++-------------- mindee/input/local_input_source.py | 37 ++--- mindee/pdf/__init__.py | 2 - mindee/pdf/pdf_compressor.py | 157 ------------------ mindee/pdf/pdf_extractor.py | 4 +- prek.toml | 13 +- tests/input/test_compression.py | 74 +++++---- .../test_multi_receipts_extractor.py | 40 ++--- .../v2/file_operations/test_crop_operation.py | 10 +- 11 files changed, 112 insertions(+), 415 deletions(-) delete mode 100644 mindee/image/image_compressor.py delete mode 100644 mindee/pdf/pdf_compressor.py diff --git a/mindee/image/extracted_image.py b/mindee/image/extracted_image.py index 7b63d1bc..9cf392f4 100644 --- a/mindee/image/extracted_image.py +++ b/mindee/image/extracted_image.py @@ -69,7 +69,7 @@ def write_to_file(self, output_path: Path | str, file_format: str | None = None) if file_format is None: out_file_path.write_bytes(self.buffer.read()) else: - image = bernard_image.decode(self.buffer) + image = bernard_image.Image(self.buffer.read()) # type: ignore[call-arg] image.save(out_file_path, format=file_format) logger.info("File saved successfully to '%s'.", out_file_path) except Exception as e: diff --git a/mindee/image/image_compressor.py b/mindee/image/image_compressor.py deleted file mode 100644 index 1ad40aa6..00000000 --- a/mindee/image/image_compressor.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import annotations - -import math -from typing import BinaryIO - -from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE -from mindee.dependencies.decorators import requires_bernard_ledit - -if BERNARD_LEDIT_AVAILABLE: - # pylint: disable=import-error - import bernard_ledit.image as bernard_image -else: - bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name - - -@requires_bernard_ledit -def compress_image( - image_buffer: BinaryIO | bytes, - quality: int = 85, - max_width: int | float | None = None, - max_height: int | float | None = None, -) -> bytes: - """ - Compresses an image with the given parameters. - - :param image_buffer: Buffer representation of an image, also accepts BinaryIO. - :param quality: Quality to apply to the image (JPEG compression). - :param max_width: Maximum bound for the width. - :param max_height: Maximum bound for the height. - :return: - """ - max_width = math.floor(max_width) if max_width else None - max_height = math.floor(max_height) if max_height else None - if hasattr(image_buffer, "seek") and hasattr(image_buffer, "read"): - image_buffer.seek(0) - raw_bytes: bytes = image_buffer.read() - else: - raw_bytes = image_buffer - return bernard_image.compress(raw_bytes, quality, max_width, max_height)[0] diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index 99098950..374da9e7 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -2,160 +2,51 @@ import io from pathlib import Path -from typing import BinaryIO from mindee.dependencies import requires_bernard_ledit from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE from mindee.geometry.point import Point -from mindee.geometry.polygon import Polygon, get_min_max_x, get_min_max_y +from mindee.geometry.polygon import Polygon from mindee.image.extracted_image import ExtractedImage from mindee.input.local_input_source import LocalInputSource if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error import bernard_ledit.image as bernard_image - import bernard_ledit.pdf as bernard_pdf else: - bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name -@requires_bernard_ledit -def _attach_image_as_new_file( - input_buffer: BinaryIO, -) -> bernard_pdf.PdfDocument: - """ - Attaches an image as a new page in a PdfDocument object. - - :param input_buffer: Input buffer. - :return: A PdfDocument handle. - """ - input_buffer.seek(0) - pdf = bernard_pdf.PdfDocument.new() - pdf.append_jpeg_page(input_buffer.read()) - return pdf - - -@requires_bernard_ledit -def extract_image_from_polygon( - page_content: bernard_image.Image, - polygon: list[Point], - width: float, - height: float, - file_format: str, - quality: int = 70, -) -> BinaryIO: - """ - Crops the image from the given polygon. - - :param page_content: Contents of the page as a Bernard L'Édit Image object. - :param polygon: Polygon coordinates for the image. - :param width: Width of the generated image. - :param height: Height of the generated image. - :param file_format: Format for the generated file. - :param quality: JPEG quality for the output (default 70 — sufficient for OCR). - :return: A generated image as a buffer. - """ - min_max_x = get_min_max_x(polygon) - min_max_y = get_min_max_y(polygon) - cropped_image = page_content.crop( - left=int(min_max_x.min * width), - top=int(min_max_y.min * height), - right=int(min_max_x.max * width), - bottom=int(min_max_y.max * height), - ) - return _save_image_to_buffer(cropped_image, file_format, quality) - - -@requires_bernard_ledit -def _save_image_to_buffer( - image: bernard_image.Image, file_format: str, quality: int = 70 -) -> BinaryIO: - """ - Saves an image as a buffer. - - :param image: Bernard L'Édit wrapper for the image. - :param file_format: Format to save the file as. - :param quality: JPEG quality (default 70 — sufficient for OCR). - :return: A valid buffer. - """ - buffer = io.BytesIO() - image.save(buffer, format=file_format, quality=quality) - buffer.seek(0) - return buffer - - -def get_file_extension(file_format: str): - """ - Extract the correct file extension. - - :param file_format: Format of the file. - :return: A valid file extension. - """ - return file_format.lower() if file_format != "JPEG" else "jpg" - - @requires_bernard_ledit def extract_multiple_images_from_source( input_source: LocalInputSource, page_id: int, polygons: list[Polygon | list[Point]], - quality: int = 70, ) -> list[ExtractedImage]: """ - Extracts elements from a page based on a list of bounding boxes. - - :param input_source: Local Input source to extract elements from. - :param page_id: id of the page to extract from. - :param polygons: List of coordinates to pull the elements from. - :param quality: JPEG quality for extracted images (default 70). - :return: List of byte arrays representing the extracted elements. + Extract multiple images from a source. + :param input_source: Source to extract images from. + :param page_id: Page ID. + :param polygons: List of polygons to extract. + :return: List of extracted images. """ stem = Path(input_source.filename).stem - doc = _load_pdf_doc(input_source) - page_content = doc.rasterize_page(page_id, 100) - width = doc.get_page(page_id).get_size().width - height = doc.get_page(page_id).get_size().height - - if input_source.is_pdf(): - file_format = "JPEG" - else: - input_source.file_object.seek(0) - file_format = bernard_image.guess_format(input_source.file_object) - - extracted_elements = [] - decoded_page = bernard_image.decode(page_content) - for element_id, polygon in enumerate(polygons): - image_data = extract_image_from_polygon( - decoded_page, - polygon, - width, - height, - file_format, - quality, - ) - extracted_elements.append( + input_source.file_object.seek(0) + pts = [[(p.x, p.y) for p in poly] for poly in polygons] + images = bernard_image.extract_polygons(input_source.file_object, page_id, pts) # type: ignore[attr-defined] + + extracted = [] + for element_id, img in enumerate(images): + buf = io.BytesIO() + img.save(buf) + fmt = str(img.format).lower() if img.format else "jpeg" + fmt = fmt if fmt != "jpeg" else "jpg" + extracted.append( ExtractedImage( - image_data, - f"{stem}_page-{(page_id + 1):03d}-item-{(element_id + 1):03d}." - f"{get_file_extension(file_format)}", + buf, + f"{stem}_page-{page_id + 1:03d}-item-{element_id + 1:03d}.{fmt}", page_id, element_id, ) ) - return extracted_elements - - -@requires_bernard_ledit -def _load_pdf_doc(input_file: LocalInputSource) -> bernard_pdf.PdfDocument: - """ - Loads a PDF document from a local input source. - - :param input_file: Local input. - :return: A valid PdfDocument handle. - """ - if input_file.is_pdf(): - input_file.file_object.seek(0) - return bernard_pdf.PdfDocument(input_file.file_object.read()) - - return _attach_image_as_new_file(input_file.file_object) + return extracted diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index d4c2d9ba..a5f56955 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -10,17 +10,15 @@ from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE from mindee.error.mimetype_error import MimeTypeError from mindee.error.mindee_error import MindeeError, MindeeSourceError -from mindee.image.image_compressor import compress_image from mindee.input.page_options import KEEP_ONLY, REMOVE, PageOptions from mindee.logger import logger -from mindee.pdf.pdf_compressor import compress_pdf from mindee.pdf.pdf_utils import pdf_has_source_text if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import bernard_ledit.pdf as bernard_pdf + import bernard_ledit as bernard else: - bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard = None # type: ignore[assignment] # pylint: disable=invalid-name mimetypes.add_type("image/heic", ".heic") mimetypes.add_type("image/heif", ".heif") @@ -56,9 +54,9 @@ def __init__(self) -> None: # Some broken (yet fixable) PDFs can cause Bernard to crash on open. if BERNARD_LEDIT_AVAILABLE: try: - pdf = bernard_pdf.PdfDocument(self.file_object) + pdf = bernard.pdf.PdfDocument(self.file_object) self.page_count = len(pdf) - except bernard_pdf.PdfiumError as e: + except bernard.pdf.PdfiumError as e: logger.warning( "Could not open PDF file: %s due to %s", self.filename, e ) @@ -139,7 +137,7 @@ def apply_page_options(self, page_options: PageOptions) -> None: page_options.page_indexes, ) self.file_object.seek(0) - pdf = bernard_pdf.PdfDocument(self.file_object) + pdf = bernard.pdf.PdfDocument(self.file_object) self.page_count = len(pdf) pdf.close() @@ -187,8 +185,8 @@ def merge_pdf_pages(self, page_numbers: set) -> None: :return: None """ self.file_object.seek(0) - new_pdf = bernard_pdf.PdfDocument.new() - pdf = bernard_pdf.PdfDocument(self.file_object) + new_pdf = bernard.pdf.PdfDocument.new() + pdf = bernard.pdf.PdfDocument(self.file_object) new_pdf.import_pages(pdf, list(page_numbers)) self.file_object.close() bytes_io = io.BytesIO() @@ -207,7 +205,7 @@ def is_pdf_empty(self) -> bool: :return: ``True`` if the PDF is empty """ self.file_object.seek(0) - with bernard_pdf.PdfDocument(self.file_object) as pdf: + with bernard.pdf.PdfDocument(self.file_object) as pdf: return pdf.has_no_content() raise MindeeSourceError(f"PDF couldn't be accessed: {self.filename}") @@ -248,8 +246,6 @@ def compress( quality: int = 85, max_width: int | None = None, max_height: int | None = None, - force_source_text: bool = False, - disable_source_text: bool = True, ) -> None: """ Compresses the file object, either as a PDF or an image. @@ -258,20 +254,17 @@ def compress( For PDFs, this affects image quality within the PDF. :param max_width: Maximum width for image resizing. Ignored for PDFs. :param max_height: Maximum height for image resizing. Ignored for PDFs. - :param force_source_text: For PDFs, whether to force compression even if source text is present. - :param disable_source_text: For PDFs, whether to disable source text during compression. """ - new_file_bytes: bytes + + self.file_object.seek(0) + data = self.file_object.read() if self.is_pdf(): - new_file_bytes = compress_pdf( - self.file_object, quality, force_source_text, disable_source_text - ) + compressed = bernard.pdf.compress(data, quality) else: - new_file_bytes = compress_image( - self.file_object, quality, max_width, max_height - ) + compressed = bernard.image.compress(data, quality, max_width, max_height) - self.file_object = io.BytesIO(new_file_bytes) + self.file_object = io.BytesIO(compressed) + self.file_object.seek(0) def __enter__(self): """Allows the class to be used as a context manager.""" diff --git a/mindee/pdf/__init__.py b/mindee/pdf/__init__.py index c8565168..15b87b8c 100644 --- a/mindee/pdf/__init__.py +++ b/mindee/pdf/__init__.py @@ -1,11 +1,9 @@ -from mindee.pdf.pdf_compressor import compress_pdf from mindee.pdf.pdf_utils import ( lerp, pdf_has_source_text, ) __all__ = [ - "compress_pdf", "lerp", "pdf_has_source_text", ] diff --git a/mindee/pdf/pdf_compressor.py b/mindee/pdf/pdf_compressor.py deleted file mode 100644 index 6d9dd000..00000000 --- a/mindee/pdf/pdf_compressor.py +++ /dev/null @@ -1,157 +0,0 @@ -from __future__ import annotations - -import io -import logging -from typing import BinaryIO - -from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE -from mindee.dependencies.decorators import requires_bernard_ledit -from mindee.image.image_compressor import compress_image -from mindee.pdf.pdf_utils import ( - lerp, - pdf_has_source_text, -) - -if BERNARD_LEDIT_AVAILABLE: - # pylint: disable=import-error - import bernard_ledit.image as bernard_image - import bernard_ledit.pdf as bernard_pdf -else: - bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name - bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name - -logger = logging.getLogger(__name__) -MIN_QUALITY = 1 - - -@requires_bernard_ledit -def compress_pdf( - pdf_data: BinaryIO | bytes, - image_quality: int = 85, - force_source_text_compression: bool = False, - disable_source_text: bool = True, -) -> bytes: - """ - Compresses each page of a provided PDF buffer. - - :param pdf_data: The input PDF as bytes. - :param image_quality: Compression quality (70-100 for most JPG images). - :param force_source_text_compression: If true, attempts to re-write detected text. - :param disable_source_text: If true, doesn't re-apply source text to the output PDF. - :return: Compressed PDF as bytes. - """ - if not isinstance(pdf_data, bytes): - pdf_bytes = pdf_data.read() - pdf_data.seek(0) - else: - pdf_bytes = pdf_data - - if pdf_has_source_text(pdf_bytes): - if force_source_text_compression: - if not disable_source_text: - logger.warning("Re-writing PDF source-text is an EXPERIMENTAL feature.") - else: - logger.warning( - "Source file contains text, but disable_source_text flag " - "is set to false. Resulting file will not contain any embedded text." - ) - else: - logger.warning( - "Found text inside of the provided PDF file. Compression operation aborted since disableSourceText " - "is set to 'true'." - ) - return pdf_bytes - - if not disable_source_text: - doc = bernard_pdf.PdfDocument(pdf_bytes) - extracted_text = [page.chars() for page in doc] - else: - extracted_text = None - - compressed_pages = _compress_pdf_pages(pdf_bytes, image_quality) - - if not compressed_pages: - logger.warning( - "Could not compress PDF to a smaller size. Returning original PDF." - ) - return pdf_bytes - - out_pdf = bernard_pdf.PdfDocument.new() - out_pdf.append_multiple_jpeg_pages( - [compressed_page_image[0] for compressed_page_image in compressed_pages] - ) - - if extracted_text: - for i in range(len(out_pdf)): - out_pdf.add_text(i, extracted_text[i]) - - out_buffer = io.BytesIO() - out_pdf.save(out_buffer) - out_buffer.seek(0) - return out_buffer.read() - - -def _compress_pdf_pages( - pdf_data: bytes, - image_quality: int, -) -> list[tuple[bytes, int, int]] | None: - """ - Compresses PDF pages and returns an array of compressed page buffers. - - :param pdf_data: The input PDF as bytes. - :param image_quality: Initial compression quality. - :return: List of compressed page buffers, or None if compression fails. - """ - original_size = len(pdf_data) - image_quality_loop = image_quality - - while image_quality_loop >= MIN_QUALITY: - compressed_pages = _compress_pages_with_quality(pdf_data, image_quality_loop) - total_compressed_size = sum(len(page) for page in compressed_pages) - - if _is_compression_successful( - total_compressed_size, original_size, image_quality - ): - return compressed_pages - - image_quality_loop -= round(lerp(1, 10, image_quality_loop / 100)) - - return None - - -@requires_bernard_ledit -def _compress_pages_with_quality( - pdf_data: bytes, - image_quality: int, -) -> list[tuple[bytes, int, int]]: - """ - Compresses pages with a specific quality. - - :param pdf_data: The input PDF as bytes. - :param image_quality: Compression quality. - :return: List of compressed page buffers. - """ - pdf_document = bernard_pdf.PdfDocument(pdf_data) - compressed_pages = [] - for index in range(len(pdf_document)): - rasterized_page = pdf_document.rasterize_page(index, image_quality) - compressed_image = compress_image(rasterized_page, image_quality) - image = bernard_image.decode(compressed_image) - compressed_pages.append((compressed_image, image.size[0], image.size[1])) - - return compressed_pages - - -def _is_compression_successful( - total_compressed_size: int, original_size: int, image_quality: int -) -> bool: - """ - Checks if the compression was successful based on the compressed size and original size. - - :param total_compressed_size: Total size of compressed pages. - :param original_size: Original PDF size. - :param image_quality: Compression quality. - :return: True if compression was successful, false otherwise. - """ - overhead = lerp(0.54, 0.18, image_quality / 100) - return total_compressed_size + total_compressed_size * overhead < original_size diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index ddd6fcb0..96d6cb00 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -34,7 +34,7 @@ def __init__(self, local_input: LocalInputSource): if local_input.is_pdf(): self._source_pdf = local_input.file_object else: - pdf_image = bernard_image.decode(local_input.file_object) + pdf_image = bernard_image.Image(local_input.file_object.read()) # type: ignore[call-arg] self._source_pdf = io.BytesIO() pdf_image.save(self._source_pdf, format="PDF") @@ -54,7 +54,7 @@ def extract_single_document(self, page_indexes: list[int]) -> ExtractedPDF: self._source_pdf.seek(0) new_pdf = bernard_pdf.PdfDocument.new() - pdf = bernard_pdf.PdfDocument(self._source_pdf) + pdf = bernard_pdf.PdfDocument(self._source_pdf.read()) new_pdf.import_pages(pdf, page_indexes) bytes_io = io.BytesIO() new_pdf.save(bytes_io) diff --git a/prek.toml b/prek.toml index 55914957..06c08875 100644 --- a/prek.toml +++ b/prek.toml @@ -50,21 +50,24 @@ hooks = [ ] [[repos]] -repo = "https://github.com/pre-commit/mirrors-mypy" -rev = "v2.3.1" +repo = "local" hooks = [ { id = "mypy", - args = [ ], + name = "mypy", + entry = "mypy", + language = "python", + language_version = "python3.10", + types = ["python"], exclude = "tests/|examples/|docs/", additional_dependencies = [ + "mypy", "httpx", "types-setuptools", "importlib-metadata", - "types-Pillow", "tomli", "tomli_w", - ] + ], } ] diff --git a/tests/input/test_compression.py b/tests/input/test_compression.py index 76ccf4d3..d30f44db 100644 --- a/tests/input/test_compression.py +++ b/tests/input/test_compression.py @@ -4,9 +4,7 @@ import pytest -from mindee.image.image_compressor import compress_image from mindee.input import PathInput -from mindee.pdf.pdf_compressor import compress_pdf from tests.utils import ( FILE_TYPES_PATH, OUTPUT_PATH, @@ -37,14 +35,14 @@ def test_image_quality_compress_from_input_source(): @pytest.mark.skip("Need to re-render test files.") def test_image_quality_compresses_from_compressor(): - receipt_input = PathInput(RECEIPT_PATH) - compresses = [ - compress_image(receipt_input.file_object, 100), - compress_image(receipt_input.file_object), - compress_image(receipt_input.file_object, 50), - compress_image(receipt_input.file_object, 10), - compress_image(receipt_input.file_object, 1), - ] + receipt_inputs = { + 100: PathInput(RECEIPT_PATH), + 75: PathInput(RECEIPT_PATH), + 50: PathInput(RECEIPT_PATH), + 10: PathInput(RECEIPT_PATH), + 1: PathInput(RECEIPT_PATH), + } + [value.compress(key) for key, value in receipt_inputs.items()] file_names = [ "compress100.jpg", @@ -53,9 +51,9 @@ def test_image_quality_compresses_from_compressor(): "compress10.jpg", "compress1.jpg", ] - for i, compressed in enumerate(compresses): + for i, compressed in enumerate(list(receipt_inputs.values())): with open(OUTPUT_PATH / file_names[i], "wb") as f: - f.write(compressed) + f.write(compressed.file_object) initial_file_stats = os.stat(RECEIPT_PATH) rendered_file_stats = [os.stat(OUTPUT_PATH / file_name) for file_name in file_names] @@ -79,21 +77,24 @@ def test_image_resize_from_input_source(): rendered_file_stats = os.stat(OUTPUT_PATH / "resize_indirect.jpg") assert rendered_file_stats.st_size < initial_file_stats.st_size - image = bernard_image.decode(image_resize_input.file_object.read()) + image = bernard_image.Image(image_resize_input.file_object.read()) assert image.size[0] == 250 assert image.size[1] == 333 def test_image_resize_from_compressor(): - image_resize_input = PathInput(RECEIPT_PATH) - resizes = [ - compress_image(image_resize_input.file_object, 75, 500), - compress_image(image_resize_input.file_object, 75, 250, 500), - compress_image(image_resize_input.file_object, 75, 500, 250), - compress_image(image_resize_input.file_object, 75, None, 250), + PathInput(RECEIPT_PATH), + PathInput(RECEIPT_PATH), + PathInput(RECEIPT_PATH), + PathInput(RECEIPT_PATH), ] + resizes[0].compress(75, 500) + resizes[1].compress(75, 250, 500) + resizes[2].compress(75, 500, 250) + resizes[3].compress(75, None, 250) + file_names = [ "resize500xnull.jpg", "resize250x500.jpg", @@ -102,7 +103,7 @@ def test_image_resize_from_compressor(): ] for i, resized in enumerate(resizes): with open(OUTPUT_PATH / file_names[i], "wb") as f: - f.write(resized) + f.write(resized.file_object.read()) initial_file_stats = os.stat(RECEIPT_PATH) rendered_file_stats = [os.stat(OUTPUT_PATH / file_name) for file_name in file_names] @@ -134,9 +135,9 @@ def test_pdf_compress_from_input_source(): V1_RESOURCE_PATH / "products" / "invoice_splitter" / "default_sample.pdf" ) - compressed_pdf = compress_pdf(pdf_resize_input.file_object, 75, True) + pdf_resize_input.compress(75, True) with open(OUTPUT_PATH / "resize_indirect.pdf", "wb") as f: - f.write(compressed_pdf) + f.write(pdf_resize_input.file_object.read()) initial_file_stats = os.stat( V1_RESOURCE_PATH / "products/invoice_splitter/default_sample.pdf" @@ -147,14 +148,18 @@ def test_pdf_compress_from_input_source(): def test_pdf_compress_from_compressor(): - pdf_resize_input = PathInput( + file_path = ( V1_RESOURCE_PATH / "products" / "invoice_splitter" / "default_sample.pdf" ) - resizes = [] - qualities = [85, 75, 50, 10] - for quality in qualities: - resizes.append(compress_pdf(pdf_resize_input.file_object, quality)) - pdf_resize_input.file_object.seek(0) + + pdf_inputs = { + 85: PathInput(file_path), + 75: PathInput(file_path), + 50: PathInput(file_path), + 10: PathInput(file_path), + } + + [value.compress(key) for key, value in pdf_inputs.items()] file_names = [ "compress85.pdf", @@ -162,16 +167,16 @@ def test_pdf_compress_from_compressor(): "compress50.pdf", "compress10.pdf", ] - for [i, resized] in enumerate(resizes): + for i, compressed in enumerate(list(pdf_inputs.values())): with open(OUTPUT_PATH / file_names[i], "wb") as f: - f.write(resized) + f.write(compressed.file_object.read()) initial_file_stats = os.stat( V1_PRODUCT_PATH / "invoice_splitter" / "default_sample.pdf" ) rendered_file_stats = [os.stat(OUTPUT_PATH / file_name) for file_name in file_names] - assert initial_file_stats.st_size > rendered_file_stats[0].st_size + assert initial_file_stats.st_size == rendered_file_stats[0].st_size assert rendered_file_stats[0].st_size > rendered_file_stats[1].st_size assert rendered_file_stats[1].st_size > rendered_file_stats[2].st_size assert rendered_file_stats[2].st_size > rendered_file_stats[3].st_size @@ -179,10 +184,13 @@ def test_pdf_compress_from_compressor(): def test_pdf_compress_with_text_does_not_compress(): initial_with_text = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") + initial_bytes = initial_with_text.file_object.read() + initial_with_text.file_object.seek(0) - compressed_with_text = compress_pdf(initial_with_text.file_object, 50) + initial_with_text.compress(50) + initial_with_text.file_object.seek(0) - assert compressed_with_text == initial_with_text.file_object.read() + assert initial_with_text.file_object.read() == initial_bytes @pytest.fixture(scope="module", autouse=True) diff --git a/tests/v1/extraction/test_multi_receipts_extractor.py b/tests/v1/extraction/test_multi_receipts_extractor.py index 00fac15b..9d0707e3 100644 --- a/tests/v1/extraction/test_multi_receipts_extractor.py +++ b/tests/v1/extraction/test_multi_receipts_extractor.py @@ -53,33 +53,33 @@ def test_single_page_multi_receipt_split( assert extracted_receipts[0].page_id == 0 assert extracted_receipts[0].element_id == 0 extracted_receipts[0].buffer.seek(0) - image_buffer_0 = bernard_image.decode(extracted_receipts[0].buffer.read()) - assert image_buffer_0.size == (341, 505) + image_buffer_0 = bernard_image.Image(extracted_receipts[0].buffer.read()) + assert image_buffer_0.size == (341, 504) assert extracted_receipts[1].page_id == 0 assert extracted_receipts[1].element_id == 1 - image_buffer_1 = bernard_image.decode(extracted_receipts[1].buffer) + image_buffer_1 = bernard_image.Image(extracted_receipts[1].buffer.read()) assert image_buffer_1.size == (461, 908) assert extracted_receipts[2].page_id == 0 assert extracted_receipts[2].element_id == 2 - image_buffer_2 = bernard_image.decode(extracted_receipts[2].buffer) - assert image_buffer_2.size == (471, 790) + image_buffer_2 = bernard_image.Image(extracted_receipts[2].buffer.read()) + assert image_buffer_2.size == (472, 789) assert extracted_receipts[3].page_id == 0 assert extracted_receipts[3].element_id == 3 - image_buffer_3 = bernard_image.decode(extracted_receipts[3].buffer) - assert image_buffer_3.size == (464, 1200) + image_buffer_3 = bernard_image.Image(extracted_receipts[3].buffer.read()) + assert image_buffer_3.size == (465, 1200) assert extracted_receipts[4].page_id == 0 assert extracted_receipts[4].element_id == 4 - image_buffer_4 = bernard_image.decode(extracted_receipts[4].buffer) - assert image_buffer_4.size == (530, 943) + image_buffer_4 = bernard_image.Image(extracted_receipts[4].buffer.read()) + assert image_buffer_4.size == (530, 944) assert extracted_receipts[5].page_id == 0 assert extracted_receipts[5].element_id == 5 - image_buffer_5 = bernard_image.decode(extracted_receipts[5].buffer) - assert image_buffer_5.size == (367, 593) + image_buffer_5 = bernard_image.Image(extracted_receipts[5].buffer.read()) + assert image_buffer_5.size == (366, 593) def test_multi_page_receipt_split( @@ -94,25 +94,25 @@ def test_multi_page_receipt_split( assert extracted_receipts[0].page_id == 0 assert extracted_receipts[0].element_id == 0 - image_buffer_0 = bernard_image.decode(extracted_receipts[0].buffer) - assert image_buffer_0.size == (198, 566) + image_buffer_0 = bernard_image.Image(extracted_receipts[0].buffer.read()) + assert image_buffer_0.size == (197, 565) assert extracted_receipts[1].page_id == 0 assert extracted_receipts[1].element_id == 1 - image_buffer_1 = bernard_image.decode(extracted_receipts[1].buffer) - assert image_buffer_1.size == (206, 382) + image_buffer_1 = bernard_image.Image(extracted_receipts[1].buffer.read()) + assert image_buffer_1.size == (205, 382) assert extracted_receipts[2].page_id == 0 assert extracted_receipts[2].element_id == 2 - image_buffer_2 = bernard_image.decode(extracted_receipts[2].buffer) - assert image_buffer_2.size == (195, 231) + image_buffer_2 = bernard_image.Image(extracted_receipts[2].buffer.read()) + assert image_buffer_2.size == (194, 232) assert extracted_receipts[3].page_id == 1 assert extracted_receipts[3].element_id == 0 - image_buffer_3 = bernard_image.decode(extracted_receipts[3].buffer) - assert image_buffer_3.size == (213, 356) + image_buffer_3 = bernard_image.Image(extracted_receipts[3].buffer.read()) + assert image_buffer_3.size == (213, 355) assert extracted_receipts[4].page_id == 1 assert extracted_receipts[4].element_id == 1 - image_buffer_4 = bernard_image.decode(extracted_receipts[4].buffer) + image_buffer_4 = bernard_image.Image(extracted_receipts[4].buffer.read()) assert image_buffer_4.size == (212, 516) diff --git a/tests/v2/file_operations/test_crop_operation.py b/tests/v2/file_operations/test_crop_operation.py index 7ff03b63..548c78bc 100644 --- a/tests/v2/file_operations/test_crop_operation.py +++ b/tests/v2/file_operations/test_crop_operation.py @@ -27,13 +27,13 @@ def test_single_page_crop(): assert crop0.page_id == 0 assert crop0.element_id == 0 assert crop0.filename == "default_sample_page-001-item-001.jpg" - assert bernard_image.decode(crop0.buffer).size == (1057, 2071) + assert bernard_image.Image(crop0.buffer.read()).size == (1056, 2070) crop1 = extracted_crops[1] assert crop1.page_id == 0 assert crop1.element_id == 1 assert crop1.filename == "default_sample_page-001-item-002.jpg" - assert bernard_image.decode(crop1.buffer).size == (1298, 1869) + assert bernard_image.Image(crop1.buffer.read()).size == (1298, 1868) @pytest.mark.bernard_ledit @@ -48,16 +48,16 @@ def test_multi_page_crop(): assert crop0.page_id == 0 assert crop0.element_id == 0 assert crop0.filename == "multipage_sample_page-001-item-001.jpg" - assert bernard_image.decode(crop0.buffer).size == (200, 553) + assert bernard_image.Image(crop0.buffer.read()).size == (200, 552) crop1 = extracted_crops[1] assert crop1.page_id == 0 assert crop1.element_id == 1 assert crop1.filename == "multipage_sample_page-001-item-002.jpg" - assert bernard_image.decode(crop1.buffer).size == (203, 333) + assert bernard_image.Image(crop1.buffer.read()).size == (204, 332) crop4 = extracted_crops[4] assert crop4.page_id == 1 assert crop4.element_id == 1 assert crop4.filename == "multipage_sample_page-002-item-002.jpg" - assert bernard_image.decode(crop4.buffer).size == (197, 520) + assert bernard_image.Image(crop4.buffer.read()).size == (197, 521) From b69b78d5a767c63e170403acfd0716d885bc3d09 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:00:02 +0200 Subject: [PATCH 04/26] fix --- .pre-commit-config.yaml | 53 ------------------------------- mindee/pdf/__init__.py | 2 -- mindee/pdf/pdf_extractor.py | 63 +++++++++++++++++++------------------ mindee/pdf/pdf_utils.py | 45 -------------------------- 4 files changed, 32 insertions(+), 131 deletions(-) delete mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 19af1ff8..00000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,53 +0,0 @@ -repos: - - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.15.22 - hooks: - - id: ruff-check - args: [ --fix, --exit-non-zero-on-fix] - - id: ruff-format - - - repo: https://github.com/betterleaks/betterleaks - rev: v1.6.1 - hooks: - - id: betterleaks - - - repo: https://github.com/PyCQA/pylint - rev: v4.0.6 - hooks: - - id: pylint - name: pylint - entry: pylint - language: system - types: [python] - args: [ - "-j2" - ] - - repo: https://github.com/pre-commit/mirrors-mypy - rev: v2.3.0 - hooks: - - id: mypy - args: [] - exclude: "tests/|examples/|docs/" - additional_dependencies: - - httpx - - types-setuptools - - importlib-metadata - - types-Pillow - - types-toml - - repo: local - hooks: - - id: sphinx-html - name: Sphinx HTML build - entry: make -C docs html - language: system - pass_filenames: false - files: ^docs/.*$|^mindee/.*\.py$ - stages: [pre-push] - - - id: sphinx-linkcheck - name: Sphinx Linkcheck - entry: make -C docs linkcheck - language: system - pass_filenames: false - files: ^docs/.*$|^mindee/.*\.py$ - stages: [pre-push] diff --git a/mindee/pdf/__init__.py b/mindee/pdf/__init__.py index 15b87b8c..fcd7be66 100644 --- a/mindee/pdf/__init__.py +++ b/mindee/pdf/__init__.py @@ -1,9 +1,7 @@ from mindee.pdf.pdf_utils import ( - lerp, pdf_has_source_text, ) __all__ = [ - "lerp", "pdf_has_source_text", ] diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index 96d6cb00..edca4113 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -13,17 +13,15 @@ if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import bernard_ledit.image as bernard_image import bernard_ledit.pdf as bernard_pdf else: bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name - bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name class PDFExtractor: """PDF extraction class.""" - _source_pdf: BinaryIO + _source: BinaryIO _filename: str _page_count: int @@ -31,12 +29,7 @@ class PDFExtractor: def __init__(self, local_input: LocalInputSource): self._filename = local_input.filename self._page_count = local_input.page_count - if local_input.is_pdf(): - self._source_pdf = local_input.file_object - else: - pdf_image = bernard_image.Image(local_input.file_object.read()) # type: ignore[call-arg] - self._source_pdf = io.BytesIO() - pdf_image.save(self._source_pdf, format="PDF") + self._source = local_input.file_object @requires_bernard_ledit def extract_single_document(self, page_indexes: list[int]) -> ExtractedPDF: @@ -46,26 +39,11 @@ def extract_single_document(self, page_indexes: list[int]) -> ExtractedPDF: :param page_indexes: List of pages number to use for merging in the original PDF. :return: The buffer containing the new PDF. """ + if not page_indexes or len(page_indexes) == 0: raise MindeeError("Empty indexes aren't allowed for extraction.") - for page_index in page_indexes: - if page_index > self._page_count: - raise MindeeError(f"Index {page_index} is out of range.") - - self._source_pdf.seek(0) - new_pdf = bernard_pdf.PdfDocument.new() - pdf = bernard_pdf.PdfDocument(self._source_pdf.read()) - new_pdf.import_pages(pdf, page_indexes) - bytes_io = io.BytesIO() - new_pdf.save(bytes_io) - - first_page = page_indexes[0] - last_page = page_indexes[len(page_indexes) - 1] - return ExtractedPDF( - pdf_byte_stream=bytes_io, - filename=self._make_filename(first_page, last_page), - page_indexes=page_indexes, - ) + self._check_indexes(page_indexes) + return self._extract([page_indexes])[0] @requires_bernard_ledit def extract_multiple_documents( @@ -79,10 +57,33 @@ def extract_multiple_documents( """ if len(page_indexes) < 1: raise MindeeError("No indexes provided.") - extracted_pdfs: list[ExtractedPDF] = [] - for page_index_elem in page_indexes: - extracted_pdfs.append(self.extract_single_document(page_index_elem)) - return ExtractedPDFs(extracted_pdfs) + for group in page_indexes: + if not group: + raise MindeeError("Empty indexes aren't allowed for extraction.") + self._check_indexes(group) + return ExtractedPDFs(self._extract(page_indexes)) + + def _check_indexes(self, page_indexes: list[int]) -> None: + for page_index in page_indexes: + if page_index < 0 or page_index >= self._page_count: + raise MindeeError(f"Index {page_index} is out of range.") + + def _extract(self, groups: list[list[int]]) -> list[ExtractedPDF]: + self._source.seek(0) + docs = bernard_pdf.extract_documents(self._source, groups) # type: ignore[attr-defined] + extracted: list[ExtractedPDF] = [] + for doc, indexes in zip(docs, groups, strict=True): + with doc: + bytes_io = io.BytesIO() + doc.save(bytes_io) + extracted.append( + ExtractedPDF( + pdf_byte_stream=bytes_io, + filename=self._make_filename(indexes[0], indexes[-1]), + page_indexes=indexes, + ) + ) + return extracted def _make_filename(self, first_page: int, last_page: int) -> str: stem = Path(self._filename).stem diff --git a/mindee/pdf/pdf_utils.py b/mindee/pdf/pdf_utils.py index 92d741de..06827868 100644 --- a/mindee/pdf/pdf_utils.py +++ b/mindee/pdf/pdf_utils.py @@ -27,48 +27,3 @@ def pdf_has_source_text(pdf_bytes: bytes) -> bool: finally: if hasattr(pdf, "close"): pdf.close() - - -def _adjust_char_box( - char_box: tuple[float, float, float, float], - rotation: int, - internal_height: float, - internal_width: float, -) -> tuple[float, float, float, float]: - """ - Adjusts the character bounding box based on page rotation. - - :param char_box: The original character bounding box. - :param rotation: The page rotation in degrees. - :param internal_height: The height of the page. - :param internal_width: The width of the page. - :return: The adjusted character bounding box. - """ - left, right, bottom, top = char_box - if rotation == 0: - top, bottom = internal_height - top, internal_height - bottom - elif rotation == 90: - left, right, top, bottom = bottom, top, left, right - elif rotation == 180: - left, right = internal_width - right, internal_width - left - top, bottom = bottom, top - elif rotation == 270: - left, right, top, bottom = ( - internal_width - top, - internal_width - bottom, - internal_height - right, - internal_height - left, - ) - return left, right, top, bottom - - -def lerp(start: float, end: float, factor: float) -> float: - """ - Performs linear interpolation between two numbers. - - :param start: The starting value. - :param end: The ending value. - :param factor: The interpolation factor (0 to 1). - :return: The interpolated value. - """ - return start * (1 - factor) + end * factor From b8e3f989bffa5b0105211503439eaaea5f599ce8 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:19:16 +0200 Subject: [PATCH 05/26] update syntax to use more bernard logic --- mindee/image/image_extractor.py | 2 +- mindee/input/local_input_source.py | 123 ++++++------------------- mindee/pdf/pdf_extractor.py | 2 +- mindee/v1/client.py | 30 +++--- tests/input/test_apply_page_options.py | 62 ++++++++----- 5 files changed, 89 insertions(+), 130 deletions(-) diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index 374da9e7..aa8ff73a 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -33,7 +33,7 @@ def extract_multiple_images_from_source( stem = Path(input_source.filename).stem input_source.file_object.seek(0) pts = [[(p.x, p.y) for p in poly] for poly in polygons] - images = bernard_image.extract_polygons(input_source.file_object, page_id, pts) # type: ignore[attr-defined] + images = bernard_image.extract_from_polygons(input_source.file_object, page_id, pts) # type: ignore[attr-defined] extracted = [] for element_id, img in enumerate(images): diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index a5f56955..d96803d8 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -2,15 +2,13 @@ import io import mimetypes -import tempfile -from collections.abc import Sequence from typing import BinaryIO from mindee.dependencies import requires_bernard_ledit from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE from mindee.error.mimetype_error import MimeTypeError from mindee.error.mindee_error import MindeeError, MindeeSourceError -from mindee.input.page_options import KEEP_ONLY, REMOVE, PageOptions +from mindee.input.page_options import PageOptions from mindee.logger import logger from mindee.pdf.pdf_utils import pdf_has_source_text @@ -81,6 +79,10 @@ def _check_mimetype(self) -> None: file_types = ", ".join(ALLOWED_MIME_TYPES) raise MimeTypeError(f"File type not allowed, must be one of {file_types}.") + def is_pdf(self) -> bool: + """:return: True if the file is a PDF.""" + return self.file_mimetype == "application/pdf" + def fix_pdf(self, maximum_offset: int = 500) -> None: """ Fix a potentially broken pdf file. @@ -96,106 +98,40 @@ def fix_pdf(self, maximum_offset: int = 500) -> None: """ if maximum_offset < 0: raise MindeeError("Can't set maximum offset for pdf-fixing to less than 0.") + self.file_object.seek(0) try: - buf = self.file_object.read() - self.file_object.seek(0) - pos: int = buf.find(b"%PDF-") - if pos != -1 and pos < maximum_offset: - self.file_object.seek(pos) - raw_bytes = self.file_object.read() - with tempfile.TemporaryFile() as temp_file: - temp_file.write(raw_bytes) - temp_file.seek(0) - self.file_object = io.BytesIO(temp_file.read()) - else: - if pos < 0: - raise MimeTypeError( - "Provided stream isn't a valid PDF-like object." - ) - raise MimeTypeError( - f"PDF couldn't be fixed. PDF tag was found at position {pos}." - ) - self.file_mimetype = "application/pdf" - except MimeTypeError as e: - raise e - except Exception as e: - logger.error("Attempt to fix pdf raised exception %s.", e) - raise e - - def is_pdf(self) -> bool: - """:return: True if the file is a PDF.""" - return self.file_mimetype == "application/pdf" + fixed = bernard.pdf.fix_pdf(self.file_object, maximum_offset) + except bernard.pdf.PdfFixError as e: + raise MimeTypeError(str(e)) from e + self.file_object = io.BytesIO(fixed) + self.file_mimetype = "application/pdf" @requires_bernard_ledit def apply_page_options(self, page_options: PageOptions) -> None: """Apply cut and merge options on multipage documents.""" if not self.is_pdf(): raise MindeeSourceError(f"File is not a PDF: {self.filename}") - self.process_pdf( - page_options.operation, - page_options.on_min_pages, - page_options.page_indexes, - ) self.file_object.seek(0) - pdf = bernard.pdf.PdfDocument(self.file_object) - self.page_count = len(pdf) - pdf.close() - - def process_pdf( - self, - behavior: str, - on_min_pages: int, - page_indexes: Sequence[int], - ) -> None: - """Run any required processing on a PDF file.""" - if self.is_pdf_empty(): - raise MindeeSourceError(f"PDF pages are empty in: {self.filename}") - page_count = self.page_count - if on_min_pages > page_count: + try: + doc, skipped = bernard.pdf.apply_page_options( + self.file_object, + page_options.operation, + page_options.on_min_pages, + list(page_options.page_indexes), + ) + except bernard.pdf.PageOptionsError as e: + raise MindeeSourceError(f"{e} ({self.filename})") from e + for page_id in skipped: + logger.warning("Page index not in source document: %s", page_id) + if doc is None: return - all_pages = list(range(page_count)) - if behavior == KEEP_ONLY: - pages_to_keep = set() - for page_id in page_indexes: - try: - pages_to_keep.add(all_pages[page_id]) - except IndexError: - logger.warning("Page index not in source document: %s", page_id) - elif behavior == REMOVE: - pages_to_remove = set() - for page_id in page_indexes: - try: - pages_to_remove.add(all_pages[page_id]) - except IndexError: - logger.warning("Page index not in source document: %s", page_id) - pages_to_keep = pages_to_remove.symmetric_difference(set(all_pages)) - else: - raise MindeeSourceError(f"Invalid cut behavior specified: {behavior}") - - if len(pages_to_keep) < 1: - raise MindeeSourceError("Resulting PDF would have no pages left.") - self.merge_pdf_pages(pages_to_keep) - - @requires_bernard_ledit - def merge_pdf_pages(self, page_numbers: set) -> None: - """ - Create a new PDF from pages and set it to ``file_object``. - - :param page_numbers: List of page numbers to use for merging in the original PDF. - :return: None - """ - self.file_object.seek(0) - new_pdf = bernard.pdf.PdfDocument.new() - pdf = bernard.pdf.PdfDocument(self.file_object) - new_pdf.import_pages(pdf, list(page_numbers)) + with doc: + buf = io.BytesIO() + doc.save(buf) + self.page_count = len(doc) + buf.seek(0) self.file_object.close() - bytes_io = io.BytesIO() - new_pdf.save(bytes_io) - bytes_io.seek(0) - self.file_object = bytes_io - self.page_count = len(new_pdf) - new_pdf.close() - pdf.close() + self.file_object = buf @requires_bernard_ledit def is_pdf_empty(self) -> bool: @@ -207,7 +143,6 @@ def is_pdf_empty(self) -> bool: self.file_object.seek(0) with bernard.pdf.PdfDocument(self.file_object) as pdf: return pdf.has_no_content() - raise MindeeSourceError(f"PDF couldn't be accessed: {self.filename}") def read_contents(self, close_file: bool) -> tuple[str, bytes]: """ diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index edca4113..6daa0b30 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -70,7 +70,7 @@ def _check_indexes(self, page_indexes: list[int]) -> None: def _extract(self, groups: list[list[int]]) -> list[ExtractedPDF]: self._source.seek(0) - docs = bernard_pdf.extract_documents(self._source, groups) # type: ignore[attr-defined] + docs = bernard_pdf.extract_from_page_ranges(self._source, groups) # type: ignore[attr-defined] extracted: list[ExtractedPDF] = [] for doc, indexes in zip(docs, groups, strict=True): with doc: diff --git a/mindee/v1/client.py b/mindee/v1/client.py index f19ee451..7b385bf5 100644 --- a/mindee/v1/client.py +++ b/mindee/v1/client.py @@ -130,10 +130,12 @@ def parse( and page_options and input_source.is_pdf() ): - input_source.process_pdf( - page_options.operation, - page_options.on_min_pages, - page_options.page_indexes, + input_source.apply_page_options( + PageOptions( + operation=page_options.operation, + on_min_pages=page_options.on_min_pages, + page_indexes=page_options.page_indexes, + ) ) options = PredictOptions(cropper, full_text, include_words) return self._make_request( @@ -204,10 +206,12 @@ def enqueue( and page_options and input_source.is_pdf() ): - input_source.process_pdf( - page_options.operation, - page_options.on_min_pages, - page_options.page_indexes, + input_source.apply_page_options( + PageOptions( + operation=page_options.operation, + on_min_pages=page_options.on_min_pages, + page_indexes=page_options.page_indexes, + ) ) options = AsyncPredictOptions( cropper, full_text, include_words, workflow_id, rag @@ -282,10 +286,12 @@ def execute_workflow( and page_options and input_source.is_pdf() ): - input_source.process_pdf( - page_options.operation, - page_options.on_min_pages, - page_options.page_indexes, + input_source.apply_page_options( + PageOptions( + operation=page_options.operation, + on_min_pages=page_options.on_min_pages, + page_indexes=page_options.page_indexes, + ) ) if not options: diff --git a/tests/input/test_apply_page_options.py b/tests/input/test_apply_page_options.py index 979f8204..33b996be 100644 --- a/tests/input/test_apply_page_options.py +++ b/tests/input/test_apply_page_options.py @@ -38,7 +38,9 @@ def _assert_page_options(input_source: LocalInputSource, numb_pages: int): def test_pdf_reconstruct_ok(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") - input_source.process_pdf(behavior=KEEP_ONLY, on_min_pages=2, page_indexes=range(5)) + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=range(5)) + ) assert isinstance(input_source.file_object, io.BytesIO) @@ -46,8 +48,10 @@ def test_pdf_reconstruct_ok(): def test_process_pdf_cut_n_pages(numb_pages: int): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") assert input_source.page_count == 12 - input_source.process_pdf( - behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0, -2, -1][:numb_pages] + input_source.apply_page_options( + PageOptions( + operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0, -2, -1][:numb_pages] + ) ) assert input_source.page_count == numb_pages _assert_page_options(input_source, numb_pages) @@ -67,8 +71,8 @@ def test_apply_pages_pdf_cut_n_pages(numb_pages: int): def test_pdf_keep_5_first_pages(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") assert input_source.page_count == 12 - input_source.process_pdf( - behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0, 1, 2, 3, 4] + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0, 1, 2, 3, 4]) ) assert input_source.page_count == 5 @@ -76,8 +80,8 @@ def test_pdf_keep_5_first_pages(): def test_pdf_keep_invalid_pages(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") assert input_source.page_count == 12 - input_source.process_pdf( - behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0, 1, 17] + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0, 1, 17]) ) assert input_source.page_count == 2 @@ -85,8 +89,8 @@ def test_pdf_keep_invalid_pages(): def test_pdf_remove_5_last_pages(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") assert input_source.is_pdf() is True - input_source.process_pdf( - behavior=REMOVE, on_min_pages=2, page_indexes=[-5, -4, -3, -2, -1] + input_source.apply_page_options( + PageOptions(operation=REMOVE, on_min_pages=2, page_indexes=[-5, -4, -3, -2, -1]) ) assert input_source.page_count == 7 @@ -94,8 +98,8 @@ def test_pdf_remove_5_last_pages(): def test_pdf_remove_5_first_pages(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") assert input_source.is_pdf() is True - input_source.process_pdf( - behavior=REMOVE, on_min_pages=2, page_indexes=list(range(5)) + input_source.apply_page_options( + PageOptions(operation=REMOVE, on_min_pages=2, page_indexes=list(range(5))) ) assert input_source.page_count == 7 @@ -103,7 +107,9 @@ def test_pdf_remove_5_first_pages(): def test_pdf_remove_invalid_pages(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") assert input_source.is_pdf() is True - input_source.process_pdf(behavior=REMOVE, on_min_pages=2, page_indexes=[16]) + input_source.apply_page_options( + PageOptions(operation=REMOVE, on_min_pages=2, page_indexes=[16]) + ) assert input_source.page_count == 12 @@ -112,11 +118,13 @@ def test_pdf_keep_no_pages(): assert input_source.is_pdf() is True # empty page indexes with pytest.raises(RuntimeError): - input_source.process_pdf(behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[]) + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[]) + ) # all invalid pages with pytest.raises(RuntimeError): - input_source.process_pdf( - behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[16, 17] + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[16, 17]) ) @@ -124,8 +132,8 @@ def test_pdf_remove_all_pages(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "multipage.pdf") assert input_source.is_pdf() is True with pytest.raises(RuntimeError): - input_source.process_pdf( - behavior=REMOVE, on_min_pages=2, page_indexes=list(range(15)) + input_source.apply_page_options( + PageOptions(operation=REMOVE, on_min_pages=2, page_indexes=list(range(15))) ) @@ -133,7 +141,9 @@ def test_pdf_input_from_file(): with open(FILE_TYPES_PATH / "pdf" / "multipage.pdf", "rb") as fp: input_source = FileInput(fp) assert input_source.is_pdf() is True - input_source.process_pdf(behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + ) assert input_source.page_count == 1 @@ -141,7 +151,9 @@ def test_pdf_input_from_base64(): with open(V1_PRODUCT_PATH / "invoices" / "invoice_10p.txt") as fp: input_source = Base64Input(fp.read(), filename="invoice_10p.pdf") assert input_source.is_pdf() is True - input_source.process_pdf(behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + ) assert input_source.page_count == 1 @@ -149,18 +161,24 @@ def test_pdf_input_from_bytes(): with open(V1_PRODUCT_PATH / "invoices" / "invoice_10p.pdf", "rb") as fp: input_source = BytesInput(fp.read(), filename="invoice_10p.pdf") assert input_source.is_pdf() is True - input_source.process_pdf(behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + ) assert input_source.page_count == 1 def test_pdf_blank_check(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "blank.pdf") with pytest.raises(MindeeError): - input_source.process_pdf(behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + ) input_source = PathInput(FILE_TYPES_PATH / "pdf" / "blank_1.pdf") with pytest.raises(MindeeError): - input_source.process_pdf(behavior=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + input_source.apply_page_options( + PageOptions(operation=KEEP_ONLY, on_min_pages=2, page_indexes=[0]) + ) input_not_blank = PathInput(FILE_TYPES_PATH / "pdf" / "not_blank_image_only.pdf") assert input_not_blank.page_count == 1 From 9542f9969212e8fa5dd3b8edc8197ae1dfaa7d29 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:24:17 +0200 Subject: [PATCH 06/26] upgrade test so that it's less ugly --- tests/input/test_apply_page_options.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/tests/input/test_apply_page_options.py b/tests/input/test_apply_page_options.py index 33b996be..9bab3798 100644 --- a/tests/input/test_apply_page_options.py +++ b/tests/input/test_apply_page_options.py @@ -16,24 +16,22 @@ bernard_ledit = pytest.importorskip("bernard_ledit") bernard_pdf = bernard_ledit.pdf +def _page_texts(doc) -> list[str]: + return [doc[i].text().replace("\r\n", "") for i in range(len(doc))] + def _assert_page_options(input_source: LocalInputSource, numb_pages: int): assert input_source.is_pdf() is True - # Currently the least verbose way of comparing pages with pdfium - # I.e., each page is read and rendered as a rasterized image. - # These images are then compared as raw byte sequences. input_source.file_object.seek(0) - cut_pdf = bernard_pdf.PdfDocument(input_source.file_object) - pdf = bernard_pdf.PdfDocument( - FILE_TYPES_PATH / "pdf" / f"multipage_cut-{numb_pages}.pdf" - ) - for idx in range(len(pdf)): - pdf_page_render = pdf.rasterize_page(idx, 100) - cut_pdf_page_render = cut_pdf.rasterize_page(idx, 100) - - assert bytes(pdf_page_render) == bytes(cut_pdf_page_render) - cut_pdf.close() - pdf.close() + with ( + bernard_pdf.PdfDocument(input_source.file_object) as cut_pdf, + bernard_pdf.PdfDocument( + FILE_TYPES_PATH / "pdf" / f"multipage_cut-{numb_pages}.pdf" + ) as expected, + ): + assert len(cut_pdf) == len(expected) == numb_pages + assert input_source.page_count == numb_pages + assert _page_texts(cut_pdf) == _page_texts(expected) def test_pdf_reconstruct_ok(): From 0ccdd4f11b779f4df5d7fe1d222bbc2800e90075 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:41:49 +0200 Subject: [PATCH 07/26] fix stuff --- mindee/input/local_input_source.py | 10 ++++------ mindee/pdf/pdf_extractor.py | 14 ++++++-------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index d96803d8..24a2ac81 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -119,19 +119,17 @@ def apply_page_options(self, page_options: PageOptions) -> None: page_options.on_min_pages, list(page_options.page_indexes), ) + page_count = len(doc) except bernard.pdf.PageOptionsError as e: raise MindeeSourceError(f"{e} ({self.filename})") from e for page_id in skipped: logger.warning("Page index not in source document: %s", page_id) if doc is None: return - with doc: - buf = io.BytesIO() - doc.save(buf) - self.page_count = len(doc) - buf.seek(0) self.file_object.close() - self.file_object = buf + with doc: + self.file_object = io.BytesIO(doc.as_bytes()) + self.page_count = page_count @requires_bernard_ledit def is_pdf_empty(self) -> bool: diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index 6daa0b30..ef64d02d 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -74,15 +74,13 @@ def _extract(self, groups: list[list[int]]) -> list[ExtractedPDF]: extracted: list[ExtractedPDF] = [] for doc, indexes in zip(docs, groups, strict=True): with doc: - bytes_io = io.BytesIO() - doc.save(bytes_io) - extracted.append( - ExtractedPDF( - pdf_byte_stream=bytes_io, - filename=self._make_filename(indexes[0], indexes[-1]), - page_indexes=indexes, + extracted.append( + ExtractedPDF( + pdf_byte_stream=io.BytesIO(doc.as_bytes()), + filename=self._make_filename(indexes[0], indexes[-1]), + page_indexes=indexes, + ) ) - ) return extracted def _make_filename(self, first_page: int, last_page: int) -> str: From 400b366ee3f95fa7c3e60c3090e41aa6260958a1 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:44:52 +0200 Subject: [PATCH 08/26] fix bernard-linking --- bernard-ledit | 2 +- mindee/image/extracted_image.py | 2 +- mindee/image/image_extractor.py | 2 +- mindee/pdf/pdf_extractor.py | 2 +- tests/input/test_apply_page_options.py | 1 + 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/bernard-ledit b/bernard-ledit index 8dcccd65..e4e613b7 160000 --- a/bernard-ledit +++ b/bernard-ledit @@ -1 +1 @@ -Subproject commit 8dcccd65ad5d696240b43e955330d53de8a621b0 +Subproject commit e4e613b7877cddbaed0126f6dc7ca2c5ac75709e diff --git a/mindee/image/extracted_image.py b/mindee/image/extracted_image.py index 9cf392f4..03f28033 100644 --- a/mindee/image/extracted_image.py +++ b/mindee/image/extracted_image.py @@ -69,7 +69,7 @@ def write_to_file(self, output_path: Path | str, file_format: str | None = None) if file_format is None: out_file_path.write_bytes(self.buffer.read()) else: - image = bernard_image.Image(self.buffer.read()) # type: ignore[call-arg] + image = bernard_image.Image(self.buffer.read()) image.save(out_file_path, format=file_format) logger.info("File saved successfully to '%s'.", out_file_path) except Exception as e: diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index aa8ff73a..7f0cdf06 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -33,7 +33,7 @@ def extract_multiple_images_from_source( stem = Path(input_source.filename).stem input_source.file_object.seek(0) pts = [[(p.x, p.y) for p in poly] for poly in polygons] - images = bernard_image.extract_from_polygons(input_source.file_object, page_id, pts) # type: ignore[attr-defined] + images = bernard_image.extract_from_polygons(input_source.file_object, page_id, pts) extracted = [] for element_id, img in enumerate(images): diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index ef64d02d..5f606a22 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -70,7 +70,7 @@ def _check_indexes(self, page_indexes: list[int]) -> None: def _extract(self, groups: list[list[int]]) -> list[ExtractedPDF]: self._source.seek(0) - docs = bernard_pdf.extract_from_page_ranges(self._source, groups) # type: ignore[attr-defined] + docs = bernard_pdf.extract_from_page_ranges(self._source, groups) extracted: list[ExtractedPDF] = [] for doc, indexes in zip(docs, groups, strict=True): with doc: diff --git a/tests/input/test_apply_page_options.py b/tests/input/test_apply_page_options.py index 9bab3798..fa5f8dd2 100644 --- a/tests/input/test_apply_page_options.py +++ b/tests/input/test_apply_page_options.py @@ -16,6 +16,7 @@ bernard_ledit = pytest.importorskip("bernard_ledit") bernard_pdf = bernard_ledit.pdf + def _page_texts(doc) -> list[str]: return [doc[i].text().replace("\r\n", "") for i in range(len(doc))] From 05e9940150fe3884bc28ac2d462c9abd93eae17e Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:55:04 +0200 Subject: [PATCH 09/26] fix mypy in CI? --- prek.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/prek.toml b/prek.toml index 06c08875..f30f3df8 100644 --- a/prek.toml +++ b/prek.toml @@ -57,6 +57,7 @@ hooks = [ name = "mypy", entry = "mypy", language = "python", + require_serial = true, language_version = "python3.10", types = ["python"], exclude = "tests/|examples/|docs/", From 531736bf5a54bd7d46ed17a04d628a47893060f3 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:15:46 +0200 Subject: [PATCH 10/26] add debug --- .github/workflows/_test-units.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/_test-units.yml b/.github/workflows/_test-units.yml index d021c342..f1b66f16 100644 --- a/.github/workflows/_test-units.yml +++ b/.github/workflows/_test-units.yml @@ -105,6 +105,14 @@ jobs: pip install -e '.[test]' shell: bash + - name: Debug PDFium versions + shell: bash + run: | + echo "--- release file:"; cat bernard-ledit/core/pdfium-release || true + echo "--- cache contents:"; find bernard-ledit/core/.pdfium_cache -name 'libpdfium*' || true + echo "--- shipped library:" + nm -D .github/artifacts/bernard-ledit/libpdfium.so | grep -c FPDFTextObj_SetFontSize || echo "symbol MISSING" + - name: Unit testing with pytest run: | pytest From 4242c1416608e91ea2e52ece0c767c08c5d6626a Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:18:49 +0200 Subject: [PATCH 11/26] bump bernie --- bernard-ledit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bernard-ledit b/bernard-ledit index e4e613b7..50a58ff7 160000 --- a/bernard-ledit +++ b/bernard-ledit @@ -1 +1 @@ -Subproject commit e4e613b7877cddbaed0126f6dc7ca2c5ac75709e +Subproject commit 50a58ff7a29db420f12310e94699de7ff346cf30 From 6c131add9170dd24ad8e4f58fddb853544227d70 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:21:02 +0200 Subject: [PATCH 12/26] move debug step --- .github/workflows/_test-units.yml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/_test-units.yml b/.github/workflows/_test-units.yml index f1b66f16..6d1d853a 100644 --- a/.github/workflows/_test-units.yml +++ b/.github/workflows/_test-units.yml @@ -62,6 +62,15 @@ jobs: python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.[test]' + + - name: Debug PDFium versions + shell: bash + run: | + echo "--- release file:"; cat bernard-ledit/core/pdfium-release || true + echo "--- cache contents:"; find bernard-ledit/core/.pdfium_cache -name 'libpdfium*' || true + echo "--- shipped library:" + nm -D .github/artifacts/bernard-ledit/libpdfium.so | grep -c FPDFTextObj_SetFontSize || echo "symbol MISSING" + - name: Unit testing with pytest run: | pytest --cov mindee --cov-fail-under 87 @@ -105,14 +114,6 @@ jobs: pip install -e '.[test]' shell: bash - - name: Debug PDFium versions - shell: bash - run: | - echo "--- release file:"; cat bernard-ledit/core/pdfium-release || true - echo "--- cache contents:"; find bernard-ledit/core/.pdfium_cache -name 'libpdfium*' || true - echo "--- shipped library:" - nm -D .github/artifacts/bernard-ledit/libpdfium.so | grep -c FPDFTextObj_SetFontSize || echo "symbol MISSING" - - name: Unit testing with pytest run: | pytest From 98b5631955db1dab6db9201d55a7de72f30d5b67 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:30:38 +0200 Subject: [PATCH 13/26] fix build --- .github/workflows/_build-bernard-ledit.yml | 11 ++++++----- .github/workflows/_test-units.yml | 9 --------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/.github/workflows/_build-bernard-ledit.yml b/.github/workflows/_build-bernard-ledit.yml index e3558cec..ed270e43 100644 --- a/.github/workflows/_build-bernard-ledit.yml +++ b/.github/workflows/_build-bernard-ledit.yml @@ -32,7 +32,10 @@ jobs: - name: Resolve bernard-ledit submodule commit id: bernard shell: bash - run: echo "sha=$(git -C bernard-ledit rev-parse HEAD)" >> "$GITHUB_OUTPUT" + run: | + echo "sha=$(git -C bernard-ledit rev-parse HEAD)" >> "$GITHUB_OUTPUT" + rel="$(tr -d '[:space:]' < bernard-ledit/core/pdfium-release)" + echo "pdfium_dir=${rel//\//_}" >> "$GITHUB_OUTPUT" # Skip the whole Rust/maturin build when the submodule pointer is unchanged. - name: Restore cached bernard-ledit build @@ -40,16 +43,14 @@ jobs: uses: actions/cache@v5 with: path: ./.github/artifacts/bernard-ledit - key: bernard-ledit-${{ runner.os }}-${{ steps.bernard.outputs.sha }} + key: bernard-ledit-v2-${{ runner.os }}-${{ steps.bernard.outputs.sha }} - name: Cache downloaded PDFium binary if: steps.cache.outputs.cache-hit != 'true' uses: actions/cache@v5 with: path: bernard-ledit/core/.pdfium_cache - key: pdfium-${{ runner.os }}-${{ hashFiles('bernard-ledit/core/build.rs') }} - restore-keys: | - pdfium-${{ runner.os }}- + key: pdfium-${{ runner.os }}-${{ runner.arch }}-${{ steps.bernard.outputs.pdfium_dir }} - name: Cache Rust build if: steps.cache.outputs.cache-hit != 'true' diff --git a/.github/workflows/_test-units.yml b/.github/workflows/_test-units.yml index 6d1d853a..d021c342 100644 --- a/.github/workflows/_test-units.yml +++ b/.github/workflows/_test-units.yml @@ -62,15 +62,6 @@ jobs: python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" pip install -e '.[test]' - - - name: Debug PDFium versions - shell: bash - run: | - echo "--- release file:"; cat bernard-ledit/core/pdfium-release || true - echo "--- cache contents:"; find bernard-ledit/core/.pdfium_cache -name 'libpdfium*' || true - echo "--- shipped library:" - nm -D .github/artifacts/bernard-ledit/libpdfium.so | grep -c FPDFTextObj_SetFontSize || echo "symbol MISSING" - - name: Unit testing with pytest run: | pytest --cov mindee --cov-fail-under 87 From fe4d5983677af2ca4cf62424aeafde3b817cee43 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:31:24 +0200 Subject: [PATCH 14/26] fix missing step --- .github/workflows/_build-bernard-ledit.yml | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/.github/workflows/_build-bernard-ledit.yml b/.github/workflows/_build-bernard-ledit.yml index ed270e43..320589dc 100644 --- a/.github/workflows/_build-bernard-ledit.yml +++ b/.github/workflows/_build-bernard-ledit.yml @@ -71,13 +71,21 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' shell: bash run: | - lib=$(find bernard-ledit/core/.pdfium_cache \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print | head -n 1) - if [ -z "$lib" ]; then - echo "::error::PDFium library not found under bernard-ledit/core/.pdfium_cache after build" + base="bernard-ledit/core/.pdfium_cache/${{ steps.bernard.outputs.pdfium_dir }}" + case "${{ runner.os }}-${{ runner.arch }}" in + Linux-X64) lib="$base/linux-x64/lib/libpdfium.so" ;; + Linux-ARM64) lib="$base/linux-arm64/lib/libpdfium.so" ;; + macOS-ARM64) lib="$base/mac-arm64/lib/libpdfium.dylib" ;; + macOS-X64) lib="$base/mac-x64/lib/libpdfium.dylib" ;; + Windows-X64) lib="$base/win-x64/bin/pdfium.dll" ;; + *) echo "::error::unsupported runner ${{ runner.os }}-${{ runner.arch }}"; exit 1 ;; + esac + if [ ! -f "$lib" ]; then + echo "::error::Expected PDFium library not found: $lib" exit 1 fi cp "$lib" ./.github/artifacts/bernard-ledit/ - echo "Bundled PDFium library: $(basename "$lib")" + echo "Bundled PDFium library: $lib" - name: Upload bernard-ledit build uses: actions/upload-artifact@v4 From cc16b3d862c7ed77d09d985c179ea34404347e79 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:37:42 +0200 Subject: [PATCH 15/26] fix broken bernie import --- mindee/input/local_input_source.py | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index 24a2ac81..1193f372 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -14,9 +14,11 @@ if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import bernard_ledit as bernard + import bernard_ledit.image as bernard_image + import bernard_ledit.pdf as bernard_pdf else: - bernard = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name mimetypes.add_type("image/heic", ".heic") mimetypes.add_type("image/heif", ".heif") @@ -52,9 +54,9 @@ def __init__(self) -> None: # Some broken (yet fixable) PDFs can cause Bernard to crash on open. if BERNARD_LEDIT_AVAILABLE: try: - pdf = bernard.pdf.PdfDocument(self.file_object) + pdf = bernard_pdf.PdfDocument(self.file_object) self.page_count = len(pdf) - except bernard.pdf.PdfiumError as e: + except bernard_pdf.PdfiumError as e: logger.warning( "Could not open PDF file: %s due to %s", self.filename, e ) @@ -100,8 +102,8 @@ def fix_pdf(self, maximum_offset: int = 500) -> None: raise MindeeError("Can't set maximum offset for pdf-fixing to less than 0.") self.file_object.seek(0) try: - fixed = bernard.pdf.fix_pdf(self.file_object, maximum_offset) - except bernard.pdf.PdfFixError as e: + fixed = bernard_pdf.fix_pdf(self.file_object, maximum_offset) + except bernard_pdf.PdfFixError as e: raise MimeTypeError(str(e)) from e self.file_object = io.BytesIO(fixed) self.file_mimetype = "application/pdf" @@ -113,14 +115,14 @@ def apply_page_options(self, page_options: PageOptions) -> None: raise MindeeSourceError(f"File is not a PDF: {self.filename}") self.file_object.seek(0) try: - doc, skipped = bernard.pdf.apply_page_options( + doc, skipped = bernard_pdf.apply_page_options( self.file_object, page_options.operation, page_options.on_min_pages, list(page_options.page_indexes), ) - page_count = len(doc) - except bernard.pdf.PageOptionsError as e: + page_count = len(doc or []) + except bernard_pdf.PageOptionsError as e: raise MindeeSourceError(f"{e} ({self.filename})") from e for page_id in skipped: logger.warning("Page index not in source document: %s", page_id) @@ -139,8 +141,9 @@ def is_pdf_empty(self) -> bool: :return: ``True`` if the PDF is empty """ self.file_object.seek(0) - with bernard.pdf.PdfDocument(self.file_object) as pdf: + with bernard_pdf.PdfDocument(self.file_object) as pdf: return pdf.has_no_content() + raise MindeeSourceError("Failed to read PDF") def read_contents(self, close_file: bool) -> tuple[str, bytes]: """ @@ -192,9 +195,9 @@ def compress( self.file_object.seek(0) data = self.file_object.read() if self.is_pdf(): - compressed = bernard.pdf.compress(data, quality) + compressed = bernard_pdf.compress(data, quality) else: - compressed = bernard.image.compress(data, quality, max_width, max_height) + compressed = bernard_image.compress(data, quality, max_width, max_height) self.file_object = io.BytesIO(compressed) self.file_object.seek(0) From 018ea043377aa1c5923cfc5192e19945fb28d675 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:42:56 +0200 Subject: [PATCH 16/26] fix test? --- mindee/input/local_input_source.py | 1 + 1 file changed, 1 insertion(+) diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index 1193f372..625661bc 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -85,6 +85,7 @@ def is_pdf(self) -> bool: """:return: True if the file is a PDF.""" return self.file_mimetype == "application/pdf" + @requires_bernard_ledit def fix_pdf(self, maximum_offset: int = 500) -> None: """ Fix a potentially broken pdf file. From 770bebbcd77c11367d2855d56efa7aa615357e85 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:45:48 +0200 Subject: [PATCH 17/26] add missing mark (huhh?) --- tests/input/test_fix_pdf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/input/test_fix_pdf.py b/tests/input/test_fix_pdf.py index 7c851f02..0b86afcd 100644 --- a/tests/input/test_fix_pdf.py +++ b/tests/input/test_fix_pdf.py @@ -19,6 +19,7 @@ def test_broken_fixable_pdf(): assert input_source.page_count == 1 +@pytest.mark.bernard_ledit def test_broken_fixable_invoice_pdf(): input_source = PathInput(FILE_TYPES_PATH / "pdf" / "broken_invoice.pdf") input_source.fix_pdf() From b307376dc600d59b151c1a119e4b6600787ab686 Mon Sep 17 00:00:00 2001 From: sebastianMindee <130448732+sebastianMindee@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:05:33 +0200 Subject: [PATCH 18/26] fix test --- .../test_invoice_splitter_auto_extraction.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/tests/v1/extraction/test_invoice_splitter_auto_extraction.py b/tests/v1/extraction/test_invoice_splitter_auto_extraction.py index 7bd7e7a1..a51a7b39 100644 --- a/tests/v1/extraction/test_invoice_splitter_auto_extraction.py +++ b/tests/v1/extraction/test_invoice_splitter_auto_extraction.py @@ -1,8 +1,10 @@ +import re from pathlib import Path import pytest from mindee.input.path_input import PathInput +from mindee.pdf.extracted_pdf import ExtractedPDF from mindee.v1.client import Client from mindee.v1.parsing.common import Document from mindee.v1.pdf.pdf_extractor import PDFExtractor @@ -27,6 +29,16 @@ def prepare_invoice_return(rst_file_path: Path, invoice_prediction: Document): return rst_content +_VOLATILE = re.compile( + rb"/ID\s*\[<[0-9A-Fa-f]*>\s*<[0-9A-Fa-f]*>\]|/CreationDate\s*\([^)]*\)|/ModDate\s*\([^)]*\)" +) + + +def _pdf_fingerprint(pdf: ExtractedPDF) -> bytes: + pdf.buffer.seek(0) + return _VOLATILE.sub(b"", pdf.buffer.read()) + + @pytest.mark.bernard_ledit @pytest.mark.integration def test_pdf_should_extract_invoices_strict(): @@ -51,8 +63,10 @@ def test_pdf_should_extract_invoices_strict(): [int_list.page_indexes for int_list in inference.prediction.invoice_page_groups] ) for i, extracted_pdf in enumerate(extracted_base_pdfs): - assert extracted_pdf.filename == extracted_pdfs_strict[i].filename - assert extracted_pdf.buffer.read() == extracted_pdfs_strict[i].buffer.read() + strict = extracted_pdfs_strict[i] + assert extracted_pdf.filename == strict.filename + assert extracted_pdf.page_indexes == strict.page_indexes + assert _pdf_fingerprint(extracted_pdf) == _pdf_fingerprint(strict) assert len(extracted_pdfs_not_strict) == 2 assert extracted_pdfs_not_strict[0].filename == "default_sample_pages-001-001.pdf" From 2b3465a9ab7d099bc554137db52bdd3672f5970c Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Thu, 12 Nov 2026 19:56:46 +0100 Subject: [PATCH 19/26] Sync image compression API and remove fallback Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- mindee/image/image_extractor.py | 9 ++++++++- mindee/input/local_input_source.py | 8 ++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index 7f0cdf06..51dbda55 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -13,8 +13,10 @@ if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error import bernard_ledit.image as bernard_image + import bernard_ledit.pdf as bernard_pdf else: bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_pdf = None # type: ignore[assignment] # pylint: disable=invalid-name @requires_bernard_ledit @@ -33,7 +35,12 @@ def extract_multiple_images_from_source( stem = Path(input_source.filename).stem input_source.file_object.seek(0) pts = [[(p.x, p.y) for p in poly] for poly in polygons] - images = bernard_image.extract_from_polygons(input_source.file_object, page_id, pts) + if input_source.is_pdf(): + with bernard_pdf.PdfDocument(input_source.file_object) as pdf: + source_image = pdf.rasterize_page(page_id) + else: + source_image = bernard_image.Image(input_source.file_object) + images = [source_image.crop_polygon(polygon) for polygon in pts] extracted = [] for element_id, img in enumerate(images): diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index 625661bc..05e0e367 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -196,9 +196,13 @@ def compress( self.file_object.seek(0) data = self.file_object.read() if self.is_pdf(): - compressed = bernard_pdf.compress(data, quality) + compressed = bernard_pdf.compress_to_jpeg(data, quality) else: - compressed = bernard_image.compress(data, quality, max_width, max_height) + compressed = bernard_image.Image(data).compress_to_jpeg( + quality=quality, + max_width=max_width, + max_height=max_height, + ) self.file_object = io.BytesIO(compressed) self.file_object.seek(0) From b2bbb72865636df15439c80ec70f59ef637f6714 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 02:47:36 +0100 Subject: [PATCH 20/26] Use shared format inference for extracted files Use the common Bernard Ledit helper when saving extracted images and PDFs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- mindee/image/extracted_image.py | 25 ++++++--- mindee/image/image_extractor.py | 6 +- mindee/pdf/extracted_pdf.py | 16 +++++- tests/test_extracted_image.py | 99 +++++++++++++++++++++++++++++++++ tests/test_extracted_pdf.py | 37 ++++++++++++ 5 files changed, 171 insertions(+), 12 deletions(-) create mode 100644 tests/test_extracted_image.py create mode 100644 tests/test_extracted_pdf.py diff --git a/mindee/image/extracted_image.py b/mindee/image/extracted_image.py index 03f28033..38f20647 100644 --- a/mindee/image/extracted_image.py +++ b/mindee/image/extracted_image.py @@ -12,8 +12,10 @@ if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error import bernard_ledit.image as bernard_image + import bernard_ledit.common as bernard_common else: bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_common = None # type: ignore[assignment] # pylint: disable=invalid-name class ExtractedImage: @@ -52,12 +54,12 @@ def write_to_file(self, output_path: Path | str, file_format: str | None = None) """ Saves the document to a file. - When no format conversion is requested the buffer is written directly - to avoid a lossy decode → re-encode cycle. + When no format is provided, the output filename's extension determines + the format. If it matches the buffer's format, the bytes are written as-is. :param output_path: Path to save the file to. - :param file_format: Format of the file to save. If omitted the buffer is - written as-is; pass an explicit format to force a conversion. + :param file_format: Format of the file to save. If omitted, infer it from + the filename extension (JPEG when there is no extension). :raises MindeeError: If an invalid path or filename is provided. """ out_path = Path(output_path) @@ -66,11 +68,18 @@ def write_to_file(self, output_path: Path | str, file_format: str | None = None) out_file_path = out_path / self.filename try: self.buffer.seek(0) - if file_format is None: - out_file_path.write_bytes(self.buffer.read()) + image_bytes = self.buffer.read() + image = bernard_image.Image(image_bytes) + output_format = ( + file_format + if file_format is not None + else bernard_common.format_from_extension(out_file_path.suffix) + ) + if file_format is None and image.format == output_format: + encoded = image_bytes else: - image = bernard_image.Image(self.buffer.read()) - image.save(out_file_path, format=file_format) + encoded = image.encode(output_format) + out_file_path.write_bytes(encoded) logger.info("File saved successfully to '%s'.", out_file_path) except Exception as e: raise MindeeError(f"Could not save file {Path(output_path).name}.") from e diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index 51dbda55..61d41669 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -44,9 +44,9 @@ def extract_multiple_images_from_source( extracted = [] for element_id, img in enumerate(images): - buf = io.BytesIO() - img.save(buf) - fmt = str(img.format).lower() if img.format else "jpeg" + image_format = img.format or "JPEG" + buf = io.BytesIO(img.encode(image_format)) + fmt = image_format.lower() fmt = fmt if fmt != "jpeg" else "jpg" extracted.append( ExtractedImage( diff --git a/mindee/pdf/extracted_pdf.py b/mindee/pdf/extracted_pdf.py index 7c63af05..fddbc683 100644 --- a/mindee/pdf/extracted_pdf.py +++ b/mindee/pdf/extracted_pdf.py @@ -3,9 +3,16 @@ from pathlib import Path from typing import BinaryIO +from mindee.dependencies.checkers import BERNARD_LEDIT_AVAILABLE from mindee.error.mindee_error import MindeeError from mindee.input.bytes_input import BytesInput +if BERNARD_LEDIT_AVAILABLE: + # pylint: disable=import-error + import bernard_ledit.common as bernard_common +else: + bernard_common = None # type: ignore[assignment] # pylint: disable=invalid-name + class ExtractedPDF: """An extracted sub-Pdf.""" @@ -28,12 +35,19 @@ def write_to_file(self, output_path: Path | str): Writes the contents of the current PDF object to a file. :param output_path: Path of the destination file. - If no extension is provided, '.pdf' will be appended by default. + If the extension doesn't identify a PDF, '.pdf' is appended. """ out_path = Path(output_path) if not out_path.resolve().is_dir(): raise MindeeError("Provided path is not a directory.") out_file_path = out_path / self.filename + is_pdf = ( + bernard_common.format_from_extension(out_file_path.suffix) == "PDF" + if bernard_common is not None + else out_file_path.suffix.lower() == ".pdf" + ) + if not is_pdf: + out_file_path = out_file_path.with_name(f"{out_file_path.name}.pdf") try: self.buffer.seek(0) diff --git a/tests/test_extracted_image.py b/tests/test_extracted_image.py new file mode 100644 index 00000000..967a0ea7 --- /dev/null +++ b/tests/test_extracted_image.py @@ -0,0 +1,99 @@ +import io +from types import SimpleNamespace + +import pytest + +import mindee.dependencies.decorators as decorators +import mindee.image.extracted_image as extracted_image_module +from mindee.image.extracted_image import ExtractedImage + + +class FakeImage: + def __init__(self, data: bytes): + self.data = data + self.format = "PNG" + + def encode(self, image_format: str) -> bytes: + return image_format.encode() + + +def _image(filename: str) -> ExtractedImage: + return ExtractedImage(io.BytesIO(b"image-bytes"), filename, 0, 0) + + +@pytest.mark.parametrize( + ("filename", "expected"), + [ + ("crop.jpg", b"JPEG"), + ("crop.tif", b"TIFF"), + ("crop.exr", b"OPENEXR"), + ("crop.pdf", b"PDF"), + ("crop", b"JPEG"), + ], +) +def test_write_to_file_infers_format_from_extension( + monkeypatch, tmp_path, filename: str, expected: bytes +): + extensions = [] + + def format_from_extension(extension: str) -> str: + extensions.append(extension) + return expected.decode() + + monkeypatch.setattr(decorators, "requires_bernard", lambda: None) + monkeypatch.setattr( + extracted_image_module, + "bernard_image", + SimpleNamespace(Image=FakeImage), + ) + monkeypatch.setattr( + extracted_image_module, + "bernard_common", + SimpleNamespace(format_from_extension=format_from_extension), + ) + + _image(filename).write_to_file(tmp_path) + + assert (tmp_path / filename).read_bytes() == expected + expected_extension = f".{filename.rsplit('.', 1)[-1]}" if "." in filename else "" + assert extensions == [expected_extension] + + +def test_write_to_file_explicit_format_overrides_extension(monkeypatch, tmp_path): + monkeypatch.setattr(decorators, "requires_bernard", lambda: None) + monkeypatch.setattr( + extracted_image_module, + "bernard_image", + SimpleNamespace(Image=FakeImage), + ) + monkeypatch.setattr( + extracted_image_module, + "bernard_common", + SimpleNamespace( + format_from_extension=lambda extension: pytest.fail( + "format should not be inferred when explicitly provided" + ) + ), + ) + + _image("crop.jpg").write_to_file(tmp_path, file_format="PNG") + + assert (tmp_path / "crop.jpg").read_bytes() == b"PNG" + + +def test_write_to_file_keeps_bytes_when_inferred_format_matches(monkeypatch, tmp_path): + monkeypatch.setattr(decorators, "requires_bernard", lambda: None) + monkeypatch.setattr( + extracted_image_module, + "bernard_image", + SimpleNamespace(Image=FakeImage), + ) + monkeypatch.setattr( + extracted_image_module, + "bernard_common", + SimpleNamespace(format_from_extension=lambda extension: "PNG"), + ) + + _image("crop.png").write_to_file(tmp_path) + + assert (tmp_path / "crop.png").read_bytes() == b"image-bytes" diff --git a/tests/test_extracted_pdf.py b/tests/test_extracted_pdf.py new file mode 100644 index 00000000..8548772a --- /dev/null +++ b/tests/test_extracted_pdf.py @@ -0,0 +1,37 @@ +import io +from types import SimpleNamespace + +import pytest + +import mindee.pdf.extracted_pdf as extracted_pdf_module +from mindee.pdf.extracted_pdf import ExtractedPDF + + +@pytest.mark.parametrize( + ("filename", "expected_filename", "extension"), + [ + ("document.jpg", "document.jpg.pdf", ".jpg"), + ("document.pdf", "document.pdf", ".pdf"), + ("document", "document.pdf", ""), + ], +) +def test_write_to_file_normalizes_pdf_extension( + monkeypatch, tmp_path, filename: str, expected_filename: str, extension: str +): + seen_extensions = [] + + def format_from_extension(value: str) -> str: + seen_extensions.append(value) + return "PDF" if value.lower() == ".pdf" else "JPEG" + + monkeypatch.setattr( + extracted_pdf_module, + "bernard_common", + SimpleNamespace(format_from_extension=format_from_extension), + ) + extracted_pdf = ExtractedPDF(io.BytesIO(b"%PDF-content"), filename, [0]) + + extracted_pdf.write_to_file(tmp_path) + + assert (tmp_path / expected_filename).read_bytes() == b"%PDF-content" + assert seen_extensions == [extension] From 80e8134c5bfd9e10976b228ff7f711296e2f130f Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 02:56:59 +0100 Subject: [PATCH 21/26] Render PDF pages through the page API Replace PdfDocument.rasterize_page with get_page().render(). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- mindee/image/image_extractor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index 61d41669..aef9b0c9 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -37,7 +37,7 @@ def extract_multiple_images_from_source( pts = [[(p.x, p.y) for p in poly] for poly in polygons] if input_source.is_pdf(): with bernard_pdf.PdfDocument(input_source.file_object) as pdf: - source_image = pdf.rasterize_page(page_id) + source_image = pdf.get_page(page_id).render() else: source_image = bernard_image.Image(input_source.file_object) images = [source_image.crop_polygon(polygon) for polygon in pts] From 5d4eda42c8ed69091894509165d62dc3ec024ba0 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 03:12:56 +0100 Subject: [PATCH 22/26] Use to_bytes for PDF serialization Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- mindee/input/local_input_source.py | 2 +- mindee/pdf/pdf_extractor.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index 05e0e367..a88bfa8d 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -131,7 +131,7 @@ def apply_page_options(self, page_options: PageOptions) -> None: return self.file_object.close() with doc: - self.file_object = io.BytesIO(doc.as_bytes()) + self.file_object = io.BytesIO(doc.to_bytes()) self.page_count = page_count @requires_bernard_ledit diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index 5f606a22..a2b97a02 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -76,7 +76,7 @@ def _extract(self, groups: list[list[int]]) -> list[ExtractedPDF]: with doc: extracted.append( ExtractedPDF( - pdf_byte_stream=io.BytesIO(doc.as_bytes()), + pdf_byte_stream=io.BytesIO(doc.to_bytes()), filename=self._make_filename(indexes[0], indexes[-1]), page_indexes=indexes, ) From 018dfc25a4b1b70f8846f48c8b609b0939b708a4 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 16:03:14 +0100 Subject: [PATCH 23/26] use read bytes instead of passing a file like object --- mindee/image/image_extractor.py | 4 ++-- mindee/input/local_input_source.py | 8 ++++---- mindee/pdf/pdf_extractor.py | 2 +- tests/input/test_apply_page_options.py | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index aef9b0c9..4396bc45 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -36,10 +36,10 @@ def extract_multiple_images_from_source( input_source.file_object.seek(0) pts = [[(p.x, p.y) for p in poly] for poly in polygons] if input_source.is_pdf(): - with bernard_pdf.PdfDocument(input_source.file_object) as pdf: + with bernard_pdf.PdfDocument(input_source.file_object.read()) as pdf: source_image = pdf.get_page(page_id).render() else: - source_image = bernard_image.Image(input_source.file_object) + source_image = bernard_image.Image(input_source.file_object.read()) images = [source_image.crop_polygon(polygon) for polygon in pts] extracted = [] diff --git a/mindee/input/local_input_source.py b/mindee/input/local_input_source.py index a88bfa8d..ed3d8503 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -54,7 +54,7 @@ def __init__(self) -> None: # Some broken (yet fixable) PDFs can cause Bernard to crash on open. if BERNARD_LEDIT_AVAILABLE: try: - pdf = bernard_pdf.PdfDocument(self.file_object) + pdf = bernard_pdf.PdfDocument(self.file_object.read()) self.page_count = len(pdf) except bernard_pdf.PdfiumError as e: logger.warning( @@ -103,7 +103,7 @@ def fix_pdf(self, maximum_offset: int = 500) -> None: raise MindeeError("Can't set maximum offset for pdf-fixing to less than 0.") self.file_object.seek(0) try: - fixed = bernard_pdf.fix_pdf(self.file_object, maximum_offset) + fixed = bernard_pdf.fix_pdf(self.file_object.read(), maximum_offset) except bernard_pdf.PdfFixError as e: raise MimeTypeError(str(e)) from e self.file_object = io.BytesIO(fixed) @@ -117,7 +117,7 @@ def apply_page_options(self, page_options: PageOptions) -> None: self.file_object.seek(0) try: doc, skipped = bernard_pdf.apply_page_options( - self.file_object, + self.file_object.read(), page_options.operation, page_options.on_min_pages, list(page_options.page_indexes), @@ -142,7 +142,7 @@ def is_pdf_empty(self) -> bool: :return: ``True`` if the PDF is empty """ self.file_object.seek(0) - with bernard_pdf.PdfDocument(self.file_object) as pdf: + with bernard_pdf.PdfDocument(self.file_object.read()) as pdf: return pdf.has_no_content() raise MindeeSourceError("Failed to read PDF") diff --git a/mindee/pdf/pdf_extractor.py b/mindee/pdf/pdf_extractor.py index a2b97a02..c4c7b579 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -70,7 +70,7 @@ def _check_indexes(self, page_indexes: list[int]) -> None: def _extract(self, groups: list[list[int]]) -> list[ExtractedPDF]: self._source.seek(0) - docs = bernard_pdf.extract_from_page_ranges(self._source, groups) + docs = bernard_pdf.extract_from_page_ranges(self._source.read(), groups) extracted: list[ExtractedPDF] = [] for doc, indexes in zip(docs, groups, strict=True): with doc: diff --git a/tests/input/test_apply_page_options.py b/tests/input/test_apply_page_options.py index fa5f8dd2..b882bfd4 100644 --- a/tests/input/test_apply_page_options.py +++ b/tests/input/test_apply_page_options.py @@ -25,9 +25,9 @@ def _assert_page_options(input_source: LocalInputSource, numb_pages: int): assert input_source.is_pdf() is True input_source.file_object.seek(0) with ( - bernard_pdf.PdfDocument(input_source.file_object) as cut_pdf, + bernard_pdf.PdfDocument(input_source.file_object.read()) as cut_pdf, bernard_pdf.PdfDocument( - FILE_TYPES_PATH / "pdf" / f"multipage_cut-{numb_pages}.pdf" + (FILE_TYPES_PATH / "pdf" / f"multipage_cut-{numb_pages}.pdf").read_bytes() ) as expected, ): assert len(cut_pdf) == len(expected) == numb_pages From d1d70116132f84ebcec8c0bf7cd347ec75828279 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 27 Nov 2026 22:40:27 +0100 Subject: [PATCH 24/26] fix tests --- tests/input/test_compression.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/input/test_compression.py b/tests/input/test_compression.py index d30f44db..c198e949 100644 --- a/tests/input/test_compression.py +++ b/tests/input/test_compression.py @@ -135,7 +135,7 @@ def test_pdf_compress_from_input_source(): V1_RESOURCE_PATH / "products" / "invoice_splitter" / "default_sample.pdf" ) - pdf_resize_input.compress(75, True) + pdf_resize_input.compress(50, True) with open(OUTPUT_PATH / "resize_indirect.pdf", "wb") as f: f.write(pdf_resize_input.file_object.read()) @@ -154,8 +154,8 @@ def test_pdf_compress_from_compressor(): pdf_inputs = { 85: PathInput(file_path), - 75: PathInput(file_path), 50: PathInput(file_path), + 30: PathInput(file_path), 10: PathInput(file_path), } @@ -163,8 +163,8 @@ def test_pdf_compress_from_compressor(): file_names = [ "compress85.pdf", - "compress75.pdf", "compress50.pdf", + "compress30.pdf", "compress10.pdf", ] for i, compressed in enumerate(list(pdf_inputs.values())): @@ -199,8 +199,8 @@ def cleanup(): cleanup_output_files( [ "compress10.pdf", + "compress30.pdf", "compress50.pdf", - "compress75.pdf", "compress85.pdf", "resize_indirect.pdf", "compress1.jpg", From eceead102827d98c6fb4441951e02f264c59ea0a Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 27 Nov 2026 23:48:50 +0100 Subject: [PATCH 25/26] use bernard-ledit submodule --- .github/workflows/_build-bernard-ledit.yml | 56 +++------------------- .github/workflows/_smoke-test.yml | 13 ++--- .github/workflows/_static-analysis.yml | 13 ++--- .github/workflows/_test-cli.yml | 13 ++--- .github/workflows/_test-integrations.yml | 13 ++--- .github/workflows/_test-regressions.yml | 13 ++--- .github/workflows/_test-units.yml | 13 ++--- .gitmodules | 2 +- CONTRIBUTING.md | 19 ++++++++ bernard-ledit | 2 +- 10 files changed, 45 insertions(+), 112 deletions(-) diff --git a/.github/workflows/_build-bernard-ledit.yml b/.github/workflows/_build-bernard-ledit.yml index 320589dc..ae1f683d 100644 --- a/.github/workflows/_build-bernard-ledit.yml +++ b/.github/workflows/_build-bernard-ledit.yml @@ -15,7 +15,7 @@ jobs: fail-fast: false matrix: os: - - "ubuntu-22.04" + - "ubuntu-24.04" - "windows-2022" - "macos-latest" runs-on: ${{ matrix.os }} @@ -29,70 +29,26 @@ jobs: with: python-version: "3.10" - - name: Resolve bernard-ledit submodule commit - id: bernard - shell: bash - run: | - echo "sha=$(git -C bernard-ledit rev-parse HEAD)" >> "$GITHUB_OUTPUT" - rel="$(tr -d '[:space:]' < bernard-ledit/core/pdfium-release)" - echo "pdfium_dir=${rel//\//_}" >> "$GITHUB_OUTPUT" + - uses: ./bernard-ledit/.github/actions/setup-libheif - # Skip the whole Rust/maturin build when the submodule pointer is unchanged. - - name: Restore cached bernard-ledit build - id: cache - uses: actions/cache@v5 - with: - path: ./.github/artifacts/bernard-ledit - key: bernard-ledit-v2-${{ runner.os }}-${{ steps.bernard.outputs.sha }} + - uses: ./bernard-ledit/.github/actions/setup-pdfium - - name: Cache downloaded PDFium binary - if: steps.cache.outputs.cache-hit != 'true' - uses: actions/cache@v5 - with: - path: bernard-ledit/core/.pdfium_cache - key: pdfium-${{ runner.os }}-${{ runner.arch }}-${{ steps.bernard.outputs.pdfium_dir }} + - uses: dtolnay/rust-toolchain@1.99.0 - name: Cache Rust build - if: steps.cache.outputs.cache-hit != 'true' uses: Swatinem/rust-cache@v2 with: workspaces: bernard-ledit - key: ${{ steps.bernard.outputs.sha }} - name: Build bernard-ledit wheel - if: steps.cache.outputs.cache-hit != 'true' shell: bash run: | python -m pip install --upgrade pip - pip wheel --no-deps --wheel-dir ./.github/artifacts/bernard-ledit bernard-ledit/bindings/python/ - - # The wheel does not embed PDFium; ship the library so consumers can set PDFIUM_PATH. - - name: Collect bundled PDFium library - if: steps.cache.outputs.cache-hit != 'true' - shell: bash - run: | - base="bernard-ledit/core/.pdfium_cache/${{ steps.bernard.outputs.pdfium_dir }}" - case "${{ runner.os }}-${{ runner.arch }}" in - Linux-X64) lib="$base/linux-x64/lib/libpdfium.so" ;; - Linux-ARM64) lib="$base/linux-arm64/lib/libpdfium.so" ;; - macOS-ARM64) lib="$base/mac-arm64/lib/libpdfium.dylib" ;; - macOS-X64) lib="$base/mac-x64/lib/libpdfium.dylib" ;; - Windows-X64) lib="$base/win-x64/bin/pdfium.dll" ;; - *) echo "::error::unsupported runner ${{ runner.os }}-${{ runner.arch }}"; exit 1 ;; - esac - if [ ! -f "$lib" ]; then - echo "::error::Expected PDFium library not found: $lib" - exit 1 - fi - cp "$lib" ./.github/artifacts/bernard-ledit/ - echo "Bundled PDFium library: $lib" + python -m pip wheel --no-deps --wheel-dir ./.github/artifacts/bernard-ledit bernard-ledit/bindings/python/ - name: Upload bernard-ledit build uses: actions/upload-artifact@v4 with: name: bernard-ledit-wheel-${{ runner.os }} - path: | - ./.github/artifacts/bernard-ledit/*.whl - ./.github/artifacts/bernard-ledit/libpdfium.* - ./.github/artifacts/bernard-ledit/pdfium.dll + path: ./.github/artifacts/bernard-ledit/*.whl if-no-files-found: error diff --git a/.github/workflows/_smoke-test.yml b/.github/workflows/_smoke-test.yml index 14c6fcf5..b78b4856 100644 --- a/.github/workflows/_smoke-test.yml +++ b/.github/workflows/_smoke-test.yml @@ -23,7 +23,7 @@ jobs: python-version: - "3.10" - "3.14" - runs-on: "ubuntu-22.04" + runs-on: "ubuntu-24.04" steps: - uses: actions/checkout@v7 with: @@ -44,23 +44,16 @@ jobs: - name: Download prebuilt bernard-ledit wheel uses: actions/download-artifact@v5 - continue-on-error: true with: name: bernard-ledit-wheel-${{ runner.os }} path: ./.github/artifacts/bernard-ledit - - name: Locate bundled PDFium - shell: bash - run: | - lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) - if [ -n "$lib" ]; then - echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" - fi + - uses: ./bernard-ledit/.github/actions/setup-libheif - name: Install dependencies run: | python -m pip install pip - python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" + python -c "from pathlib import Path; import subprocess, sys; wheels = list(Path('.github/artifacts/bernard-ledit').glob('*.whl')); assert len(wheels) == 1, 'Expected one Bernard wheel'; subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0])])" pip install -e '.' - name: Tests v2 sample code diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 03fccaee..f4afd970 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -9,7 +9,7 @@ on: jobs: static-check: name: Run Static Analysis - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: matrix: python-version: ["3.12"] @@ -55,23 +55,16 @@ jobs: - name: Download prebuilt bernard-ledit wheel uses: actions/download-artifact@v5 - continue-on-error: true with: name: bernard-ledit-wheel-${{ runner.os }} path: ./.github/artifacts/bernard-ledit - - name: Locate bundled PDFium - shell: bash - run: | - lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) - if [ -n "$lib" ]; then - echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" - fi + - uses: ./bernard-ledit/.github/actions/setup-libheif - name: Install dependencies run: | python -m pip install pip - python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" + python -c "from pathlib import Path; import subprocess, sys; wheels = list(Path('.github/artifacts/bernard-ledit').glob('*.whl')); assert len(wheels) == 1, 'Expected one Bernard wheel'; subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0])])" pip install -e '.[lint]' - name: License check diff --git a/.github/workflows/_test-cli.yml b/.github/workflows/_test-cli.yml index 28ee4f27..2496e446 100644 --- a/.github/workflows/_test-cli.yml +++ b/.github/workflows/_test-cli.yml @@ -23,7 +23,7 @@ jobs: max-parallel: 4 matrix: os: - - "ubuntu-22.04" + - "ubuntu-24.04" - "macos-latest" - "windows-2022" python-version: @@ -50,23 +50,16 @@ jobs: - name: Download prebuilt bernard-ledit wheel uses: actions/download-artifact@v5 - continue-on-error: true with: name: bernard-ledit-wheel-${{ runner.os }} path: ./.github/artifacts/bernard-ledit - - name: Locate bundled PDFium - shell: bash - run: | - lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) - if [ -n "$lib" ]; then - echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" - fi + - uses: ./bernard-ledit/.github/actions/setup-libheif - name: Install dependencies run: | python -m pip install pip - python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" + python -c "from pathlib import Path; import subprocess, sys; wheels = list(Path('.github/artifacts/bernard-ledit').glob('*.whl')); assert len(wheels) == 1, 'Expected one Bernard wheel'; subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0])])" pip install -e '.' - name: Test V1 CLI diff --git a/.github/workflows/_test-integrations.yml b/.github/workflows/_test-integrations.yml index 399de795..81e81ab1 100644 --- a/.github/workflows/_test-integrations.yml +++ b/.github/workflows/_test-integrations.yml @@ -28,7 +28,7 @@ jobs: strategy: matrix: os: - - "ubuntu-22.04" + - "ubuntu-24.04" - "windows-2022" python-version: - "3.10" @@ -54,23 +54,16 @@ jobs: - name: Download prebuilt bernard-ledit wheel uses: actions/download-artifact@v5 - continue-on-error: true with: name: bernard-ledit-wheel-${{ runner.os }} path: ./.github/artifacts/bernard-ledit - - name: Locate bundled PDFium - shell: bash - run: | - lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) - if [ -n "$lib" ]; then - echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" - fi + - uses: ./bernard-ledit/.github/actions/setup-libheif - name: Install dependencies run: | python -m pip install pip - python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" + python -c "from pathlib import Path; import subprocess, sys; wheels = list(Path('.github/artifacts/bernard-ledit').glob('*.whl')); assert len(wheels) == 1, 'Expected one Bernard wheel'; subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0])])" pip install -e '.[test]' - name: Run Integration Testing run: | diff --git a/.github/workflows/_test-regressions.yml b/.github/workflows/_test-regressions.yml index 9d2afd08..a033ed31 100644 --- a/.github/workflows/_test-regressions.yml +++ b/.github/workflows/_test-regressions.yml @@ -14,7 +14,7 @@ jobs: strategy: matrix: os: - - "ubuntu-22.04" + - "ubuntu-24.04" - "windows-2022" python-version: - "3.10" @@ -40,23 +40,16 @@ jobs: - name: Download prebuilt bernard-ledit wheel uses: actions/download-artifact@v5 - continue-on-error: true with: name: bernard-ledit-wheel-${{ runner.os }} path: ./.github/artifacts/bernard-ledit - - name: Locate bundled PDFium - shell: bash - run: | - lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) - if [ -n "$lib" ]; then - echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" - fi + - uses: ./bernard-ledit/.github/actions/setup-libheif - name: Install dependencies run: | python -m pip install pip - python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" + python -c "from pathlib import Path; import subprocess, sys; wheels = list(Path('.github/artifacts/bernard-ledit').glob('*.whl')); assert len(wheels) == 1, 'Expected one Bernard wheel'; subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0])])" pip install -e '.[test]' - name: Run Regression Testing env: diff --git a/.github/workflows/_test-units.yml b/.github/workflows/_test-units.yml index d021c342..0893a405 100644 --- a/.github/workflows/_test-units.yml +++ b/.github/workflows/_test-units.yml @@ -13,7 +13,7 @@ jobs: strategy: matrix: os: - - "ubuntu-22.04" + - "ubuntu-24.04" - "windows-2022" - "macos-latest" python-version: @@ -43,23 +43,16 @@ jobs: - name: Download prebuilt bernard-ledit wheel uses: actions/download-artifact@v5 - continue-on-error: true with: name: bernard-ledit-wheel-${{ runner.os }} path: ./.github/artifacts/bernard-ledit - - name: Locate bundled PDFium - shell: bash - run: | - lib=$(find .github/artifacts/bernard-ledit \( -name 'libpdfium.*' -o -name 'pdfium.dll' \) -print 2>/dev/null | head -n 1) - if [ -n "$lib" ]; then - echo "PDFIUM_PATH=$(python -c 'import os,sys;print(os.path.abspath(sys.argv[1]))' "$lib")" >> "$GITHUB_ENV" - fi + - uses: ./bernard-ledit/.github/actions/setup-libheif - name: Install dependencies run: | python -m pip install pip - python -c "from pathlib import Path; import subprocess, sys; wheels = sorted(Path('.github/artifacts/bernard-ledit').glob('*.whl')); subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0]) if wheels else 'bernard-ledit/bindings/python/'])" + python -c "from pathlib import Path; import subprocess, sys; wheels = list(Path('.github/artifacts/bernard-ledit').glob('*.whl')); assert len(wheels) == 1, 'Expected one Bernard wheel'; subprocess.check_call([sys.executable, '-m', 'pip', 'install', str(wheels[0])])" pip install -e '.[test]' - name: Unit testing with pytest diff --git a/.gitmodules b/.gitmodules index dae31977..d04cac93 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,4 +4,4 @@ [submodule "bernard-ledit"] path = bernard-ledit url = https://github.com/mindee/bernard-ledit.git - branch = dev + branch = refacto diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8efdd9f0..646aa8c5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,6 +62,25 @@ Please follow these steps to have your contribution considered by the maintainer While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted. +### Bernard l'Édit + +Initialize the submodules before you build or test: + +```bash +git submodule update --init --recursive +``` + +Follow the [Bernard build prerequisites](bernard-ledit/README.md#development), then install the +Python binding from the submodule: + +```bash +python -m pip install -e ./bernard-ledit/bindings/python +python -m pip install -e '.[test]' +``` + +CI builds the same submodule commit. To use a newer commit from `refacto`, update the submodule +and commit its new revision. + ## Styleguides ### Git Commit Messages diff --git a/bernard-ledit b/bernard-ledit index 50a58ff7..cb09a35b 160000 --- a/bernard-ledit +++ b/bernard-ledit @@ -1 +1 @@ -Subproject commit 50a58ff7a29db420f12310e94699de7ff346cf30 +Subproject commit cb09a35bd8e80db9b25c26f0c77a8ef7dc12be2b From 6472d9fee2713a8c7a324c45aefe98bdb0ab4f1e Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Sat, 28 Nov 2026 00:13:28 +0100 Subject: [PATCH 26/26] fix lint --- mindee/image/extracted_image.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mindee/image/extracted_image.py b/mindee/image/extracted_image.py index 38f20647..9ad95cdc 100644 --- a/mindee/image/extracted_image.py +++ b/mindee/image/extracted_image.py @@ -11,8 +11,8 @@ if BERNARD_LEDIT_AVAILABLE: # pylint: disable=import-error - import bernard_ledit.image as bernard_image import bernard_ledit.common as bernard_common + import bernard_ledit.image as bernard_image else: bernard_image = None # type: ignore[assignment] # pylint: disable=invalid-name bernard_common = None # type: ignore[assignment] # pylint: disable=invalid-name