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..ae1f683d --- /dev/null +++ b/.github/workflows/_build-bernard-ledit.yml @@ -0,0 +1,54 @@ +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-24.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" + + - uses: ./bernard-ledit/.github/actions/setup-libheif + + - uses: ./bernard-ledit/.github/actions/setup-pdfium + + - uses: dtolnay/rust-toolchain@1.99.0 + + - name: Cache Rust build + uses: Swatinem/rust-cache@v2 + with: + workspaces: bernard-ledit + + - name: Build bernard-ledit wheel + shell: bash + run: | + python -m pip install --upgrade pip + 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 + if-no-files-found: error diff --git a/.github/workflows/_smoke-test.yml b/.github/workflows/_smoke-test.yml index 9716d307..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: @@ -42,9 +42,18 @@ jobs: restore-keys: | ${{ runner.os }}-samples- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - 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 = 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 7fe39fbd..31f6586e 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -9,9 +9,12 @@ on: jobs: static-check: name: Run Static Analysis - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 + with: + submodules: recursive + fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v7 @@ -26,15 +29,28 @@ jobs: restore-keys: | ${{ runner.os }}-lint- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - 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 = 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 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..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: @@ -48,9 +48,18 @@ jobs: restore-keys: | ${{ runner.os }}-cli- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - 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 = 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 7f99636f..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" @@ -52,9 +52,18 @@ jobs: restore-keys: | ${{ runner.os }}-test- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - 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 = 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: | @@ -107,4 +116,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..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" @@ -38,9 +38,18 @@ jobs: restore-keys: | ${{ runner.os }}-test- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - 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 = 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 5d7972ed..0893a405 100644 --- a/.github/workflows/_test-units.yml +++ b/.github/workflows/_test-units.yml @@ -13,8 +13,9 @@ jobs: strategy: matrix: os: - - "ubuntu-22.04" + - "ubuntu-24.04" - "windows-2022" + - "macos-latest" python-version: - "3.10" - "3.11" @@ -40,9 +41,18 @@ jobs: restore-keys: | ${{ runner.os }}-test- + - name: Download prebuilt bernard-ledit wheel + uses: actions/download-artifact@v5 + with: + name: bernard-ledit-wheel-${{ runner.os }} + path: ./.github/artifacts/bernard-ledit + + - 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 = 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 @@ -57,6 +67,7 @@ jobs: os: - "ubuntu-22.04" - "windows-2022" + - "macos-latest" python-version: - "3.10" - "3.14" @@ -90,4 +101,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 f579417d..580dc940 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -10,16 +10,20 @@ permissions: jobs: workflow-lint: uses: mindee/client-lib-actions/.github/workflows/workflow-lint.yml@main + build-bernard-ledit: + uses: ./.github/workflows/_build-bernard-ledit.yml betterleaks: uses: mindee/client-lib-actions/.github/workflows/betterleaks.yml@main needs: workflow-lint secrets: inherit 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: [ betterleaks, static-analysis ] + needs: [ build-bernard-ledit, betterleaks, static-analysis ] 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 483865c6..57fd1cb3 100644 --- a/.github/workflows/push-main-branch.yml +++ b/.github/workflows/push-main-branch.yml @@ -6,14 +6,17 @@ on: - main jobs: + build-bernard-ledit: + uses: ./.github/workflows/_build-bernard-ledit.yml betterleaks: uses: mindee/client-lib-actions/.github/workflows/betterleaks.yml@main secrets: inherit static-analysis: uses: ./.github/workflows/_static-analysis.yml + needs: build-bernard-ledit test-units: uses: ./.github/workflows/_test-units.yml - needs: [ betterleaks, static-analysis ] + needs: [ build-bernard-ledit, betterleaks, static-analysis ] secrets: inherit tag: uses: mindee/client-lib-actions/.github/workflows/tag-version.yml@main diff --git a/.gitmodules b/.gitmodules index 6a653ee9..d04cac93 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 = 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 new file mode 160000 index 00000000..cb09a35b --- /dev/null +++ b/bernard-ledit @@ -0,0 +1 @@ +Subproject commit cb09a35bd8e80db9b25c26f0c77a8ef7dc12be2b 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..9ad95cdc 100644 --- a/mindee/image/extracted_image.py +++ b/mindee/image/extracted_image.py @@ -1,19 +1,21 @@ 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.common as bernard_common + 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 + bernard_common = None # type: ignore[assignment] # pylint: disable=invalid-name class ExtractedImage: @@ -47,12 +49,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 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, 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) @@ -61,11 +68,20 @@ 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) + 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: + 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: - 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 deleted file mode 100644 index 37241933..00000000 --- a/mindee/image/image_compressor.py +++ /dev/null @@ -1,45 +0,0 @@ -from __future__ import annotations - -import io -from typing import Any, BinaryIO - -from mindee.dependencies.checkers import PILLOW_AVAILABLE -from mindee.dependencies.decorators import requires_pillow - -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 -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: - """ - 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 diff --git a/mindee/image/image_extractor.py b/mindee/image/image_extractor.py index 681b46f9..4396bc45 100644 --- a/mindee/image/image_extractor.py +++ b/mindee/image/image_extractor.py @@ -2,183 +2,58 @@ import io from pathlib import Path -from typing import Any, 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.geometry.polygon import Polygon 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_image = None # type: ignore[assignment] # pylint: disable=invalid-name + bernard_pdf = 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 - input_buffer: BinaryIO, -) -> pdfium.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) - 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() - return pdf - - -@requires_pillow -def extract_image_from_polygon( - page_content: Image.Image, - polygon: list[Point], - width: float, - height: float, - file_format: str, -) -> BinaryIO: - """ - Crops the image from the given polygon. - - :param page_content: Contents of the page as a Pillow 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. - :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), - ) - ) - return _save_image_to_buffer(cropped_image, file_format) - - -@requires_pillow -def _save_image_to_buffer(image: Image.Image, file_format: str) -> BinaryIO: - """ - Saves an image as a buffer. - - :param image: Pillow wrapper for the image. - :param file_format: Format to save the file as. - :return: A valid buffer. - """ - buffer = io.BytesIO() - image.save(buffer, format=file_format) - 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. - - :param file_format: Format of the file. - :return: A valid file extension. - """ - 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]], ) -> 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. - :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 - page = _load_pdf_doc(input_source).get_page(page_id) - page_content = page.render().to_pil() - width, height = page.get_size() - - file_format = determine_file_format(input_source) - file_extension = get_file_extension(file_format) - - extracted_elements = [] - for element_id, polygon in enumerate(polygons): - image_data = extract_image_from_polygon( - page_content, polygon, width, height, file_format - ) - extracted_elements.append( + 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.read()) as pdf: + source_image = pdf.get_page(page_id).render() + else: + source_image = bernard_image.Image(input_source.file_object.read()) + images = [source_image.crop_polygon(polygon) for polygon in pts] + + extracted = [] + for element_id, img in enumerate(images): + 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( - image_data, - f"{stem}_page-{(page_id + 1):03d}-item-{(element_id + 1):03d}.{file_extension}", + buf, + f"{stem}_page-{page_id + 1:03d}-item-{element_id + 1:03d}.{fmt}", page_id, element_id, ) ) - return extracted_elements - - -@requires_pypdfium2 -def _load_pdf_doc(input_file: LocalInputSource) -> pdfium.PdfDocument: # type: ignore - """ - 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 pdfium.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 0fe78842..ed3d8503 100644 --- a/mindee/input/local_input_source.py +++ b/mindee/input/local_input_source.py @@ -2,25 +2,23 @@ import io import mimetypes -import tempfile -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 -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_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.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 mimetypes.add_type("image/heic", ".heic") mimetypes.add_type("image/heif", ".heif") @@ -53,12 +51,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.read()) 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 ) @@ -83,6 +81,11 @@ 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" + + @requires_bernard_ledit def fix_pdf(self, maximum_offset: int = 500) -> None: """ Fix a potentially broken pdf file. @@ -98,107 +101,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 + 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) + self.file_mimetype = "application/pdf" - 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(): 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 = pdfium.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.read(), + page_options.operation, + page_options.on_min_pages, + list(page_options.page_indexes), + ) + 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) + 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_pypdfium2 - 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 = pdfium.PdfDocument.new() - pdf = pdfium.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) - self.file_object = bytes_io - self.page_count = len(new_pdf) - new_pdf.close() - pdf.close() + with doc: + self.file_object = io.BytesIO(doc.to_bytes()) + self.page_count = page_count - @requires_pypdfium2 + @requires_bernard_ledit def is_pdf_empty(self) -> bool: """ Check if the PDF is empty. @@ -206,11 +142,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.read()) as pdf: + return pdf.has_no_content() + raise MindeeSourceError("Failed to read PDF") def read_contents(self, close_file: bool) -> tuple[str, bytes]: """ @@ -243,14 +177,12 @@ 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, 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. @@ -259,20 +191,21 @@ 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_to_jpeg(data, quality) else: - new_file_bytes = compress_image( - self.file_object, 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(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 15b724dc..fcd7be66 100644 --- a/mindee/pdf/__init__.py +++ b/mindee/pdf/__init__.py @@ -1,15 +1,7 @@ -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/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/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 deleted file mode 100644 index 0df4c0fc..00000000 --- a/mindee/pdf/pdf_compressor.py +++ /dev/null @@ -1,242 +0,0 @@ -from __future__ import annotations - -import io -import logging -from ctypes import POINTER, c_char_p, c_ushort -from threading import RLock -from typing import Any, BinaryIO - -from mindee.dependencies.checkers import PILLOW_AVAILABLE, PYPDFIUM2_AVAILABLE -from mindee.dependencies.decorators import requires_pillow, requires_pypdfium2 -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: - # pylint: disable=import-error - import pypdfium2 as pdfium - import pypdfium2.raw as pdfium_c -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 - -logger = logging.getLogger(__name__) -MIN_QUALITY = 1 - - -@requires_pypdfium2 -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 - - extracted_text = ( - extract_text_from_pdf(pdf_bytes) if not disable_source_text else 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 = _collect_images_as_pdf( - [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) - - 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_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 -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 = pdfium.PdfDocument(pdf_data) - compressed_pages = [] - for page in pdf_document: - rasterized_page = _rasterize_page(page, image_quality) - compressed_image = compress_image(rasterized_page, image_quality) - image = Image.open(io.BytesIO(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 - - -@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..c4c7b579 100644 --- a/mindee/pdf/pdf_extractor.py +++ b/mindee/pdf/pdf_extractor.py @@ -2,47 +2,36 @@ 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.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 class PDFExtractor: """PDF extraction class.""" - _source_pdf: BinaryIO + _source: BinaryIO _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) - self._source_pdf = io.BytesIO() - pdf_image.save(self._source_pdf, format="PDF") + self._source = local_input.file_object - @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. @@ -50,28 +39,13 @@ 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._check_indexes(page_indexes) + return self._extract([page_indexes])[0] - self._source_pdf.seek(0) - new_pdf = pdfium.PdfDocument.new() - pdf = pdfium.PdfDocument(self._source_pdf) - 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, - ) - - @requires_pypdfium2 + @requires_bernard_ledit def extract_multiple_documents( self, page_indexes: list[list[int]] ) -> ExtractedPDFs: @@ -83,10 +57,31 @@ 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_from_page_ranges(self._source.read(), groups) + extracted: list[ExtractedPDF] = [] + for doc, indexes in zip(docs, groups, strict=True): + with doc: + extracted.append( + ExtractedPDF( + pdf_byte_stream=io.BytesIO(doc.to_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: stem = Path(self._filename).stem diff --git a/mindee/pdf/pdf_utils.py b/mindee/pdf/pdf_utils.py index f3ab2042..06827868 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,272 +20,10 @@ 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, - 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 diff --git a/mindee/v1/client.py b/mindee/v1/client.py index 3b9bcd15..b7fc54fa 100644 --- a/mindee/v1/client.py +++ b/mindee/v1/client.py @@ -125,10 +125,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( @@ -199,10 +201,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 diff --git a/prek.toml b/prek.toml index 55914957..f30f3df8 100644 --- a/prek.toml +++ b/prek.toml @@ -50,21 +50,25 @@ 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", + require_serial = true, + 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/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..b882bfd4 100644 --- a/tests/input/test_apply_page_options.py +++ b/tests/input/test_apply_page_options.py @@ -13,32 +13,33 @@ 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 _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 pypdfium2 - # 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( - 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) - - assert bytes(pdf_page_render.buffer) == bytes(cut_pdf_page_render.buffer) - cut_pdf.close() - pdf.close() + input_source.file_object.seek(0) + with ( + bernard_pdf.PdfDocument(input_source.file_object.read()) as cut_pdf, + bernard_pdf.PdfDocument( + (FILE_TYPES_PATH / "pdf" / f"multipage_cut-{numb_pages}.pdf").read_bytes() + ) 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(): 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 +47,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 +70,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 +79,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 +88,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 +97,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 +106,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 +117,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 +131,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 +140,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 +150,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 +160,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 diff --git a/tests/input/test_compression.py b/tests/input/test_compression.py index 6eb690a1..c198e949 100644 --- a/tests/input/test_compression.py +++ b/tests/input/test_compression.py @@ -1,15 +1,10 @@ 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 +13,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,15 +33,16 @@ 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 = [ - 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 = Image.open(image_resize_input.file_object) - assert image.width == 250 - assert image.height == 333 + 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(50, 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,64 +148,49 @@ 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), + 50: PathInput(file_path), + 30: PathInput(file_path), + 10: PathInput(file_path), + } + + [value.compress(key) for key, value in pdf_inputs.items()] file_names = [ "compress85.pdf", - "compress75.pdf", "compress50.pdf", + "compress30.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 -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") + 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) @@ -213,8 +199,8 @@ def cleanup(): cleanup_output_files( [ "compress10.pdf", + "compress30.pdf", "compress50.pdf", - "compress75.pdf", "compress85.pdf", "resize_indirect.pdf", "compress1.jpg", diff --git a/tests/input/test_fix_pdf.py b/tests/input/test_fix_pdf.py index 13f6e70f..0b86afcd 100644 --- a/tests/input/test_fix_pdf.py +++ b/tests/input/test_fix_pdf.py @@ -5,20 +5,21 @@ 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() 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() 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/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] diff --git a/tests/v1/extraction/test_invoice_splitter_auto_extraction.py b/tests/v1/extraction/test_invoice_splitter_auto_extraction.py index 213bd0ba..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,8 +29,17 @@ def prepare_invoice_return(rst_file_path: Path, invoice_prediction: Document): return rst_content -@pytest.mark.pillow -@pytest.mark.pypdfium2 +_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(): client = Client() @@ -52,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" diff --git a/tests/v1/extraction/test_multi_receipts_extractor.py b/tests/v1/extraction/test_multi_receipts_extractor.py index 518e9039..9d0707e3 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,33 +52,34 @@ 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) - assert image_buffer_0.size == (341, 505) + extracted_receipts[0].buffer.seek(0) + 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 = Image.open(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 = Image.open(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 = Image.open(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 = Image.open(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 = Image.open(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( @@ -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) - 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 = Image.open(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 = Image.open(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 = Image.open(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 = Image.open(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/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/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..548c78bc 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.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 Image.open(crop1.buffer).size == (1298, 1869) + assert bernard_image.Image(crop1.buffer.read()).size == (1298, 1868) -@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.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 Image.open(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 Image.open(crop4.buffer).size == (197, 520) + assert bernard_image.Image(crop4.buffer.read()).size == (197, 521) 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