diff --git a/.github/labeler.yml b/.github/labeler.yml index 349edf670c..4b2a08c6ac 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -14,6 +14,11 @@ integration:amazon-sagemaker: - any-glob-to-any-file: "integrations/amazon_sagemaker/**/*" - any-glob-to-any-file: ".github/workflows/amazon_sagemaker.yml" +integration:amazon-textract: + - changed-files: + - any-glob-to-any-file: "integrations/amazon_textract/**/*" + - any-glob-to-any-file: ".github/workflows/amazon_textract.yml" + integration:anthropic: - changed-files: - any-glob-to-any-file: "integrations/anthropic/**/*" diff --git a/.github/workflows/CI_coverage_comment.yml b/.github/workflows/CI_coverage_comment.yml index e4d682b7cf..d097192a0b 100644 --- a/.github/workflows/CI_coverage_comment.yml +++ b/.github/workflows/CI_coverage_comment.yml @@ -6,6 +6,7 @@ on: - "Test / aimlapi" - "Test / amazon-bedrock" - "Test / amazon-sagemaker" + - "Test / amazon-textract" - "Test / anthropic" - "Test / arcadedb" - "Test / astra" diff --git a/.github/workflows/amazon_textract.yml b/.github/workflows/amazon_textract.yml new file mode 100644 index 0000000000..3e907eead6 --- /dev/null +++ b/.github/workflows/amazon_textract.yml @@ -0,0 +1,139 @@ +# This workflow comes from https://github.com/ofek/hatch-mypyc +# https://github.com/ofek/hatch-mypyc/blob/5a198c0ba8660494d02716cfc9d79ce4adfb1442/.github/workflows/test.yml +name: Test / amazon-textract + +on: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "integrations/amazon_textract/**" + - "!integrations/amazon_textract/*.md" + - ".github/workflows/amazon_textract.yml" + push: + branches: + - main + paths: + - "integrations/amazon_textract/**" + - "!integrations/amazon_textract/*.md" + - ".github/workflows/amazon_textract.yml" + +defaults: + run: + working-directory: integrations/amazon_textract + +concurrency: + group: amazon_textract-${{ github.head_ref || github.sha }} + cancel-in-progress: true + +env: + PYTHONUNBUFFERED: "1" + FORCE_COLOR: "1" + TEST_MATRIX_OS: '["ubuntu-latest", "windows-latest", "macos-latest"]' + TEST_MATRIX_PYTHON: '["3.10", "3.14"]' + +jobs: + compute-test-matrix: + runs-on: ubuntu-slim + defaults: + run: + working-directory: . + outputs: + os: ${{ steps.set.outputs.os }} + python-version: ${{ steps.set.outputs.python-version }} + steps: + - id: set + run: | + echo 'os=${{ github.event_name == 'push' && '["ubuntu-latest"]' || env.TEST_MATRIX_OS }}' >> "$GITHUB_OUTPUT" + echo 'python-version=${{ github.event_name == 'push' && '["3.10"]' || env.TEST_MATRIX_PYTHON }}' >> "$GITHUB_OUTPUT" + + run: + name: Python ${{ matrix.python-version }} on ${{ startsWith(matrix.os, 'macos-') && 'macOS' || startsWith(matrix.os, 'windows-') && 'Windows' || 'Linux' }} + needs: compute-test-matrix + permissions: + contents: write + pull-requests: write + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: ${{ fromJSON(needs.compute-test-matrix.outputs.os) }} + python-version: ${{ fromJSON(needs.compute-test-matrix.outputs.python-version) }} + + steps: + - name: Support longpaths + if: matrix.os == 'windows-latest' + working-directory: . + run: git config --system core.longpaths true + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Hatch + run: pip install --upgrade hatch + - name: Lint + if: matrix.python-version == '3.10' && runner.os == 'Linux' + run: hatch run fmt-check && hatch run test:types + + - name: Run unit tests + run: hatch run test:unit-cov-retry + + # On PR: posts coverage comment (directly on same-repo PRs; via artifact for fork PRs). On push to main: stores coverage baseline on data branch. + - name: Store unit tests coverage + id: coverage_comment + if: matrix.python-version == '3.10' && runner.os == 'Linux' && github.event_name != 'schedule' + uses: py-cov-action/python-coverage-comment-action@7188638f871f721a365d644f505d1ff3df20d683 # v3.40 + with: + GITHUB_TOKEN: ${{ github.token }} + COVERAGE_PATH: integrations/amazon_textract + SUBPROJECT_ID: amazon_textract + MINIMUM_GREEN: 90 + MINIMUM_ORANGE: 60 + + - name: Upload coverage comment to be posted + if: matrix.python-version == '3.10' && runner.os == 'Linux' && github.event_name == 'pull_request' && steps.coverage_comment.outputs.COMMENT_FILE_WRITTEN == 'true' + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: coverage-comment-amazon_textract + path: python-coverage-comment-action-amazon_textract.txt + + - name: Run integration tests + run: hatch run test:integration-cov-append-retry + + - name: Store combined coverage + if: github.event_name == 'push' + uses: py-cov-action/python-coverage-comment-action@7188638f871f721a365d644f505d1ff3df20d683 # v3.40 + with: + GITHUB_TOKEN: ${{ github.token }} + COVERAGE_PATH: integrations/amazon_textract + SUBPROJECT_ID: amazon_textract-combined + MINIMUM_GREEN: 90 + MINIMUM_ORANGE: 60 + + - name: Run unit tests with lowest direct dependencies + if: github.event_name != 'push' + run: | + hatch run uv pip compile pyproject.toml --resolution lowest-direct --output-file requirements_lowest_direct.txt + hatch -e test env run -- uv pip install -r requirements_lowest_direct.txt + hatch run test:unit + + - name: Nightly - run unit tests with Haystack main branch + if: github.event_name == 'schedule' + run: | + hatch env prune + hatch -e test env run -- uv pip install git+https://github.com/deepset-ai/haystack.git@main + hatch run test:unit + + + notify-slack-on-failure: + needs: run + if: failure() && github.event_name == 'schedule' + runs-on: ubuntu-slim + steps: + - uses: deepset-ai/notify-slack-action@3cda73b77a148f16f703274198e7771340cf862b # v1 + with: + slack-webhook-url: ${{ secrets.SLACK_WEBHOOK_URL_NOTIFICATIONS }} diff --git a/README.md b/README.md index 42891b8360..6412d5370f 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Please check out our [Contribution Guidelines](CONTRIBUTING.md) for all the deta | [aimlapi-haystack](integrations/aimlapi/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/aimlapi-haystack.svg)](https://pypi.org/project/aimlapi-haystack) | [![Test / aimlapi](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/aimlapi.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/aimlapi.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-aimlapi/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-aimlapi/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-aimlapi-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-aimlapi-combined/htmlcov/index.html) | | [amazon-bedrock-haystack](integrations/amazon_bedrock/) | Embedder, Generator, Ranker, Downloader | [![PyPI - Version](https://img.shields.io/pypi/v/amazon-bedrock-haystack.svg)](https://pypi.org/project/amazon-bedrock-haystack) | [![Test / amazon_bedrock](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_bedrock.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_bedrock.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-amazon_bedrock/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-amazon_bedrock/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-amazon_bedrock-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-amazon_bedrock-combined/htmlcov/index.html) | | [amazon-sagemaker-haystack](integrations/amazon_sagemaker/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/amazon-sagemaker-haystack.svg)](https://pypi.org/project/amazon-sagemaker-haystack) | [![Test / amazon_sagemaker](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_sagemaker.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_sagemaker.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-amazon_sagemaker/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-amazon_sagemaker/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-amazon_sagemaker-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-amazon_sagemaker-combined/htmlcov/index.html) | +| [amazon-textract-haystack](integrations/amazon_textract/) | Converter | [![PyPI - Version](https://img.shields.io/pypi/v/amazon-textract-haystack.svg)](https://pypi.org/project/amazon-textract-haystack) | [![Test / amazon_textract](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_textract.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_textract.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-amazon_textract/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-amazon_textract/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-amazon_textract-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-amazon_textract-combined/htmlcov/index.html) | | [anthropic-haystack](integrations/anthropic/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/anthropic-haystack.svg)](https://pypi.org/project/anthropic-haystack) | [![Test / anthropic](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/anthropic.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/anthropic.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-anthropic/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-anthropic/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-anthropic-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-anthropic-combined/htmlcov/index.html) | | [arcadedb-haystack](integrations/arcadedb/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/arcadedb-haystack.svg)](https://pypi.org/project/arcadedb-haystack) | [![Test / arcadedb](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/arcadedb.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/arcadedb.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-arcadedb/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-arcadedb/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-arcadedb-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-arcadedb-combined/htmlcov/index.html) | | [astra-haystack](integrations/astra/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/astra-haystack.svg)](https://pypi.org/project/astra-haystack) | [![Test / astra](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/astra.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/astra.yml) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-astra/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-astra/htmlcov/index.html) | [![Coverage badge](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/python-coverage-comment-action-data-astra-combined/endpoint.json&label=)](https://htmlpreview.github.io/?https://github.com/deepset-ai/haystack-core-integrations/blob/python-coverage-comment-action-data-astra-combined/htmlcov/index.html) | diff --git a/integrations/amazon_textract/CHANGELOG.md b/integrations/amazon_textract/CHANGELOG.md new file mode 100644 index 0000000000..522f6d5d8b --- /dev/null +++ b/integrations/amazon_textract/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + + diff --git a/integrations/amazon_textract/LICENSE.txt b/integrations/amazon_textract/LICENSE.txt new file mode 100644 index 0000000000..6134ab324f --- /dev/null +++ b/integrations/amazon_textract/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023-present deepset GmbH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/integrations/amazon_textract/README.md b/integrations/amazon_textract/README.md new file mode 100644 index 0000000000..d829054361 --- /dev/null +++ b/integrations/amazon_textract/README.md @@ -0,0 +1,134 @@ +# amazon-textract-haystack + +[![PyPI - Version](https://img.shields.io/pypi/v/amazon-textract-haystack.svg)](https://pypi.org/project/amazon-textract-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/amazon-textract-haystack.svg)](https://pypi.org/project/amazon-textract-haystack) + +- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_textract/CHANGELOG.md) + +--- + +## Overview + +A [Haystack](https://haystack.deepset.ai/) integration for [AWS Textract](https://aws.amazon.com/textract/) that extracts text and structured data from documents using OCR. + +The `AmazonTextractConverter` component converts images and single-page PDFs into Haystack `Document` objects using the AWS Textract synchronous API. + +**Supported file formats:** JPEG, PNG, TIFF, BMP, and single-page PDF (up to 10 MB). + +## Installation + +```bash +pip install amazon-textract-haystack +``` + +## Usage + +### Basic text extraction + +Extract plain text from a document using `DetectDocumentText`: + +```python +from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter + +converter = AmazonTextractConverter() +results = converter.run(sources=["document.png"]) +documents = results["documents"] + +print(documents[0].content) +``` + +### Table and form analysis + +Use `AnalyzeDocument` to detect tables and forms by setting `feature_types`: + +```python +converter = AmazonTextractConverter(feature_types=["TABLES", "FORMS"]) +results = converter.run(sources=["invoice.png"]) + +documents = results["documents"] +raw_responses = results["raw_textract_response"] +``` + +Valid `feature_types` values: `"TABLES"`, `"FORMS"`, `"SIGNATURES"`, `"LAYOUT"`. + +### Natural-language queries + +Ask questions about a document and get extracted answers. The `QUERIES` feature type +is enabled automatically when you pass the `queries` parameter at runtime: + +```python +converter = AmazonTextractConverter() +results = converter.run( + sources=["medical_form.png"], + queries=["What is the patient name?", "What is the date of birth?"], +) + +documents = results["documents"] +raw_responses = results["raw_textract_response"] +``` + +Queries can be combined with `feature_types` for both structural and question-based extraction: + +```python +converter = AmazonTextractConverter(feature_types=["TABLES", "FORMS"]) +results = converter.run( + sources=["invoice.png"], + queries=["What is the total amount due?"], +) +``` + +### In a Haystack pipeline + +```python +from haystack import Pipeline +from haystack.components.preprocessors import DocumentCleaner +from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter + +pipeline = Pipeline() +pipeline.add_component("converter", AmazonTextractConverter()) +pipeline.add_component("cleaner", DocumentCleaner()) +pipeline.connect("converter.documents", "cleaner.documents") + +result = pipeline.run({"converter": {"sources": ["scan.png"]}}) +``` + +## AWS Credentials + +The component uses the standard boto3 credential chain. You can configure credentials in any of these ways: + +1. **Environment variables** (default): Set `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION`. +2. **AWS credentials file**: Configure via `~/.aws/credentials` and `~/.aws/config`. +3. **IAM role**: When running on AWS infrastructure (EC2, Lambda, ECS). +4. **Explicit parameters**: + +```python +from haystack.utils import Secret + +converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_env_var("MY_AWS_KEY"), + aws_secret_access_key=Secret.from_env_var("MY_AWS_SECRET"), + aws_region_name=Secret.from_token("us-east-1"), +) +``` + +## Running Tests + +Unit tests (no AWS credentials needed): + +```bash +cd integrations/amazon_textract +hatch run test:unit +``` + +Integration tests (require AWS credentials and a test image at `tests/test_files/sample_text.png`): + +```bash +export AWS_ACCESS_KEY_ID=... +export AWS_SECRET_ACCESS_KEY=... +export AWS_DEFAULT_REGION=us-east-1 +hatch run test:integration +``` + +## Contributing + +Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md). diff --git a/integrations/amazon_textract/examples/analyze_document_example.py b/integrations/amazon_textract/examples/analyze_document_example.py new file mode 100644 index 0000000000..a8e2dd6c23 --- /dev/null +++ b/integrations/amazon_textract/examples/analyze_document_example.py @@ -0,0 +1,25 @@ +# To run this example, you will need to: +# 1) Set `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables +# 2) Place a document image named `invoice.png` in the same directory as this script +# +# This example demonstrates structural analysis using AWS Textract's AnalyzeDocument API. +# Setting `feature_types` enables extraction of tables, forms, and layout information +# in addition to plain text. + +from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter + +converter = AmazonTextractConverter(feature_types=["TABLES", "FORMS"]) + +results = converter.run(sources=["invoice.png"]) + +for doc in results["documents"]: + print(f"--- {doc.meta.get('file_path', 'unknown')} ---") + print(doc.content) + print() + +raw = results["raw_textract_response"][0] +table_blocks = [b for b in raw.get("Blocks", []) if b.get("BlockType") == "TABLE"] +print(f"Tables found: {len(table_blocks)}") + +form_blocks = [b for b in raw.get("Blocks", []) if b.get("BlockType") == "KEY_VALUE_SET"] +print(f"Key-value pairs found: {len(form_blocks)}") diff --git a/integrations/amazon_textract/examples/queries_example.py b/integrations/amazon_textract/examples/queries_example.py new file mode 100644 index 0000000000..aa70efe689 --- /dev/null +++ b/integrations/amazon_textract/examples/queries_example.py @@ -0,0 +1,34 @@ +# To run this example, you will need to: +# 1) Set `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables +# 2) Place a document image named `medical_form.png` in the same directory as this script +# +# This example demonstrates natural-language queries using AWS Textract. +# The QUERIES feature type is enabled automatically when you pass the `queries` +# parameter at runtime. Textract will attempt to find answers to each question +# in the document. + +from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter + +converter = AmazonTextractConverter() + +results = converter.run( + sources=["medical_form.png"], + queries=["What is the patient name?", "What is the date of birth?", "What is the diagnosis?"], +) + +for doc in results["documents"]: + print("--- Extracted text ---") + print(doc.content) + print() + +raw = results["raw_textract_response"][0] +query_blocks = [b for b in raw.get("Blocks", []) if b.get("BlockType") == "QUERY"] +for block in query_blocks: + question = block.get("Query", {}).get("Text", "") + print(f"Q: {question}") + +query_result_blocks = [b for b in raw.get("Blocks", []) if b.get("BlockType") == "QUERY_RESULT"] +for block in query_result_blocks: + answer = block.get("Text", "") + confidence = block.get("Confidence", 0) + print(f"A: {answer} (confidence: {confidence:.1f}%)") diff --git a/integrations/amazon_textract/examples/text_extraction_example.py b/integrations/amazon_textract/examples/text_extraction_example.py new file mode 100644 index 0000000000..e979e64146 --- /dev/null +++ b/integrations/amazon_textract/examples/text_extraction_example.py @@ -0,0 +1,17 @@ +# To run this example, you will need to: +# 1) Set `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` environment variables +# 2) Place an image or single-page PDF named `document.png` in the same directory as this script +# +# This example demonstrates basic text extraction from a document image using +# AWS Textract's DetectDocumentText API. + +from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter + +converter = AmazonTextractConverter() + +results = converter.run(sources=["document.png"]) + +for doc in results["documents"]: + print(f"--- {doc.meta.get('file_path', 'unknown')} (pages: {doc.meta.get('page_count')}) ---") + print(doc.content) + print() diff --git a/integrations/amazon_textract/pydoc/config_docusaurus.yml b/integrations/amazon_textract/pydoc/config_docusaurus.yml new file mode 100644 index 0000000000..61eaf37e11 --- /dev/null +++ b/integrations/amazon_textract/pydoc/config_docusaurus.yml @@ -0,0 +1,13 @@ +loaders: + - modules: + - haystack_integrations.components.converters.amazon_textract.converter + search_path: [../src] +processors: + - type: filter + documented_only: true + skip_empty_modules: true +renderer: + description: Amazon Textract integration for Haystack + id: integrations-amazon_textract + filename: amazon_textract.md + title: Amazon Textract diff --git a/integrations/amazon_textract/pyproject.toml b/integrations/amazon_textract/pyproject.toml new file mode 100644 index 0000000000..af772bb9bf --- /dev/null +++ b/integrations/amazon_textract/pyproject.toml @@ -0,0 +1,177 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "amazon-textract-haystack" +dynamic = ["version"] +description = "Haystack integration for AWS Textract document text extraction and analysis" +readme = "README.md" +requires-python = ">=3.10" +license = "Apache-2.0" +keywords = [ + "AWS", + "Textract", + "Haystack", + "OCR", + "PDF", + "Document Converter", +] +authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }] +classifiers = [ + "License :: OSI Approved :: Apache Software License", + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: Implementation :: CPython", +] +dependencies = [ + "haystack-ai>=2.24.1", + "boto3>=1.42.84,<2", +] + +[project.urls] +Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/amazon_textract#readme" +Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues" +Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/amazon_textract" + +[tool.hatch.build.targets.wheel] +packages = ["src/haystack_integrations"] + +[tool.hatch.version] +source = "vcs" +tag-pattern = 'integrations\/amazon_textract-v(?P.*)' + +[tool.hatch.version.raw-options] +root = "../.." +git_describe_command = 'git describe --tags --match="integrations/amazon_textract-v[0-9]*"' + +[tool.hatch.envs.default] +installer = "uv" +dependencies = ["haystack-pydoc-tools", "ruff"] + +[tool.hatch.envs.default.scripts] +docs = ["haystack-pydoc pydoc/config_docusaurus.yml"] +fmt = "ruff check --fix {args}; ruff format {args}" +fmt-check = "ruff check {args} && ruff format --check {args}" + +[tool.hatch.envs.test] +dependencies = [ + "pytest", + "pytest-cov", + "pytest-rerunfailures", + "mypy", + "pip", +] + +[tool.hatch.envs.test.scripts] +unit = 'pytest -m "not integration" {args:tests}' +integration = 'pytest -m "integration" {args:tests}' +all = 'pytest {args:tests}' +unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}' +integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}' +types = "mypy -p haystack_integrations.components.converters.amazon_textract {args}" + +[tool.mypy] +install_types = true +non_interactive = true +check_untyped_defs = true +disallow_incomplete_defs = true + +[[tool.mypy.overrides]] +module = [ + "botocore.*", + "boto3.*", +] +ignore_missing_imports = true + +[tool.ruff] +line-length = 120 + +[tool.ruff.lint] +select = [ + "A", + "ANN", + "ARG", + "B", + "C", + "D102", # Missing docstring in public method + "D103", # Missing docstring in public function + "D205", # 1 blank line required between summary line and description + "D209", # Closing triple quotes go to new line + "D213", # summary lines must be positioned on the second physical line of the docstring + "D417", # Missing argument descriptions in the docstring + "D419", # Docstring is empty + "DTZ", + "E", + "EM", + "F", + "I", + "ICN", + "ISC", + "N", + "PLC", + "PLE", + "PLR", + "PLW", + "Q", + "RUF", + "S", + "T", + "TID", + "UP", + "W", + "YTT", +] +ignore = [ + # Allow non-abstract empty methods in abstract base classes + "B027", + # Allow function calls in argument defaults (common Haystack pattern for Secret.from_env_var) + "B008", + # Ignore checks for possible passwords + "S105", + "S106", + "S107", + # Ignore complexity + "C901", + "PLR0911", + "PLR0912", + "PLR0913", + "PLR0915", + # Allow `Any` type - used legitimately for dynamic types and SDK boundaries + "ANN401", +] + +[tool.ruff.lint.isort] +known-first-party = ["haystack_integrations"] + +[tool.ruff.lint.flake8-tidy-imports] +ban-relative-imports = "parents" + +[tool.ruff.lint.per-file-ignores] +# Tests can use magic values, assertions, relative imports, and don't need type annotations +"tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"] +"examples/**/*" = ["T201"] + +[tool.coverage.run] +source = ["haystack_integrations"] +branch = true +parallel = false +relative_files = true + +[tool.coverage.report] +omit = ["*/tests/*", "*/__init__.py"] +show_missing = true +exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] + +[tool.pytest.ini_options] +addopts = "--strict-markers" +markers = [ + "unit: unit tests", + "integration: integration tests", +] +log_cli = true diff --git a/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/__init__.py b/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/__init__.py new file mode 100644 index 0000000000..145fdb12d7 --- /dev/null +++ b/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .converter import AmazonTextractConverter +from .errors import AmazonTextractConfigurationError + +__all__ = ["AmazonTextractConfigurationError", "AmazonTextractConverter"] diff --git a/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/converter.py b/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/converter.py new file mode 100644 index 0000000000..e6068ce1b7 --- /dev/null +++ b/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/converter.py @@ -0,0 +1,270 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path +from typing import Any + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.utils import Secret, deserialize_secrets_inplace + +from .errors import AmazonTextractConfigurationError + +logger = logging.getLogger(__name__) + +VALID_FEATURE_TYPES = frozenset({"TABLES", "FORMS", "SIGNATURES", "LAYOUT"}) + + +@component +class AmazonTextractConverter: + """ + Converts documents to Haystack Documents using AWS Textract. + + This component uses AWS Textract to extract text and optionally structured data + (tables, forms) from images and single-page PDFs. + + When `feature_types` is not set, the component uses `DetectDocumentText` for + plain text OCR. When `feature_types` is set (e.g. `["TABLES", "FORMS"]`), it + uses `AnalyzeDocument` for richer structural analysis. + + Natural-language queries are also supported via the `queries` parameter on + `run()`. When queries are provided, the `QUERIES` feature type is added + automatically and Textract returns answers extracted from the document. + + Supported input formats: JPEG, PNG, TIFF, BMP, and single-page PDF (up to 10 MB). + + AWS credentials are resolved via `Secret` parameters or the default boto3 + credential chain (environment variables, AWS config files, IAM roles). + + ### Usage example + + ```python + from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter + + converter = AmazonTextractConverter() + results = converter.run(sources=["document.png"]) + documents = results["documents"] + ``` + """ + + def __init__( + self, + *, + aws_access_key_id: Secret | None = Secret.from_env_var("AWS_ACCESS_KEY_ID", strict=False), + aws_secret_access_key: Secret | None = Secret.from_env_var("AWS_SECRET_ACCESS_KEY", strict=False), + aws_session_token: Secret | None = Secret.from_env_var("AWS_SESSION_TOKEN", strict=False), + aws_region_name: Secret | None = Secret.from_env_var("AWS_DEFAULT_REGION", strict=False), + aws_profile_name: Secret | None = Secret.from_env_var("AWS_PROFILE", strict=False), + feature_types: list[str] | None = None, + store_full_path: bool = False, + boto3_config: dict[str, Any] | None = None, + ) -> None: + """ + Creates an AmazonTextractConverter component. + + :param aws_access_key_id: AWS access key ID. + :param aws_secret_access_key: AWS secret access key. + :param aws_session_token: AWS session token. + :param aws_region_name: AWS region name. Must be a region that supports Textract. + :param aws_profile_name: AWS profile name from the credentials file. + :param feature_types: + List of feature types to detect when using AnalyzeDocument. + Valid values: "TABLES", "FORMS", "SIGNATURES", "LAYOUT". + If None, uses DetectDocumentText for basic text extraction. + The "QUERIES" feature type is managed automatically when the + `queries` parameter is passed to `run()`. + :param store_full_path: + If True, stores the complete file path in Document metadata. + If False, stores only the filename (default). + :param boto3_config: + Dictionary of configuration options for the underlying boto3 client. + Can be used to tune retry behavior, timeouts, and connection management. + """ + if feature_types is not None: + invalid = set(feature_types) - VALID_FEATURE_TYPES + if invalid: + msg = f"Invalid feature_types: {invalid}. Valid values are: {sorted(VALID_FEATURE_TYPES)}" + raise ValueError(msg) + + self.aws_access_key_id = aws_access_key_id + self.aws_secret_access_key = aws_secret_access_key + self.aws_session_token = aws_session_token + self.aws_region_name = aws_region_name + self.aws_profile_name = aws_profile_name + self.feature_types = feature_types + self.store_full_path = store_full_path + self.boto3_config = boto3_config + self._client: Any = None + + def warm_up(self) -> None: + """Initializes the AWS Textract client.""" + if self._client is not None: + return + + def resolve_secret(secret: Secret | None) -> str | None: + return secret.resolve_value() if secret else None + + try: + session = boto3.Session( + aws_access_key_id=resolve_secret(self.aws_access_key_id), + aws_secret_access_key=resolve_secret(self.aws_secret_access_key), + aws_session_token=resolve_secret(self.aws_session_token), + region_name=resolve_secret(self.aws_region_name), + profile_name=resolve_secret(self.aws_profile_name), + ) + config = Config( + user_agent_extra="x-client-framework:haystack", + **(self.boto3_config if self.boto3_config else {}), + ) + self._client = session.client("textract", config=config) + except BotoCoreError as e: + msg = ( + "Could not connect to AWS Textract. Make sure the AWS environment is configured correctly. " + "See https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration" + ) + raise AmazonTextractConfigurationError(msg) from e + + @component.output_types(documents=list[Document], raw_textract_response=list[dict]) + def run( + self, + sources: list[str | Path | ByteStream], + meta: dict[str, Any] | list[dict[str, Any]] | None = None, + queries: list[str] | None = None, + ) -> dict[str, Any]: + """ + Convert documents to Haystack Documents using AWS Textract. + + :param sources: + List of file paths or ByteStream objects to convert. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources. + :param queries: + Optional list of natural-language questions to ask about each document. + When provided, the Textract ``QUERIES`` feature type is enabled + automatically and each question is sent as a query. Answers are + included in the raw Textract response. Example: + ``["What is the patient name?", "What is the total due?"]`` + :returns: + A dictionary with the following keys: + - `documents`: List of created Documents with extracted text as content. + - `raw_textract_response`: List of raw Textract API responses. + """ + if self._client is None: + self.warm_up() + + documents: list[Document] = [] + raw_responses: list[dict[str, Any]] = [] + meta_list = normalize_metadata(meta=meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list, strict=True): + try: + bytestream = get_bytestream_from_source(source=source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + + try: + response = self._call_textract(bytestream.data, queries=queries) + raw_responses.append(response) + + merged_metadata = {**bytestream.meta, **metadata} + if not self.store_full_path and (file_path := bytestream.meta.get("file_path")): + merged_metadata["file_path"] = Path(file_path).name + + doc = self._create_document(response, merged_metadata) + documents.append(doc) + + except (BotoCoreError, ClientError) as e: + logger.warning( + "Failed to convert {source} using AWS Textract. Skipping it. Error: {error}", + source=source, + error=e, + ) + continue + + return {"documents": documents, "raw_textract_response": raw_responses} + + def _call_textract(self, document_bytes: bytes, queries: list[str] | None = None) -> dict[str, Any]: + """Calls the appropriate Textract API based on configuration.""" + doc_param: dict[str, Any] = {"Document": {"Bytes": document_bytes}} + + feature_types = list(self.feature_types) if self.feature_types else [] + if queries: + if "QUERIES" not in feature_types: + feature_types.append("QUERIES") + + if feature_types: + kwargs: dict[str, Any] = {**doc_param, "FeatureTypes": feature_types} + if queries: + kwargs["QueriesConfig"] = {"Queries": [{"Text": q} for q in queries]} + return self._client.analyze_document(**kwargs) + + return self._client.detect_document_text(**doc_param) + + def _create_document(self, response: dict[str, Any], meta: dict[str, Any]) -> Document: + """ + Creates a Document from a Textract response. + + Extracts LINE blocks in reading order and joins them with newlines. + """ + blocks = response.get("Blocks", []) + lines = [block["Text"] for block in blocks if block.get("BlockType") == "LINE" and "Text" in block] + content = "\n".join(lines) + + page_count = sum(1 for block in blocks if block.get("BlockType") == "PAGE") + + doc_meta = { + **meta, + "page_count": page_count, + } + + return Document(content=content, meta=doc_meta) + + def to_dict(self) -> dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + aws_access_key_id=self.aws_access_key_id, + aws_secret_access_key=self.aws_secret_access_key, + aws_session_token=self.aws_session_token, + aws_region_name=self.aws_region_name, + aws_profile_name=self.aws_profile_name, + feature_types=self.feature_types, + store_full_path=self.store_full_path, + boto3_config=self.boto3_config, + ) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> "AmazonTextractConverter": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + deserialize_secrets_inplace( + data["init_parameters"], + keys=[ + "aws_access_key_id", + "aws_secret_access_key", + "aws_session_token", + "aws_region_name", + "aws_profile_name", + ], + ) + return default_from_dict(cls, data) diff --git a/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/errors.py b/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/errors.py new file mode 100644 index 0000000000..3e77de21db --- /dev/null +++ b/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/errors.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +class AmazonTextractConfigurationError(Exception): + """Exception raised when AWS is not configured correctly for Textract.""" diff --git a/integrations/amazon_textract/src/haystack_integrations/components/converters/py.typed b/integrations/amazon_textract/src/haystack_integrations/components/converters/py.typed new file mode 100644 index 0000000000..e69de29bb2 diff --git a/integrations/amazon_textract/tests/__init__.py b/integrations/amazon_textract/tests/__init__.py new file mode 100644 index 0000000000..c1764a6e03 --- /dev/null +++ b/integrations/amazon_textract/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/amazon_textract/tests/test_amazon_textract_converter.py b/integrations/amazon_textract/tests/test_amazon_textract_converter.py new file mode 100644 index 0000000000..a7c0106047 --- /dev/null +++ b/integrations/amazon_textract/tests/test_amazon_textract_converter.py @@ -0,0 +1,510 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from botocore.exceptions import BotoCoreError, ClientError +from haystack.dataclasses import ByteStream +from haystack.utils import Secret + +from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter +from haystack_integrations.components.converters.amazon_textract.errors import ( + AmazonTextractConfigurationError, +) + +TEST_FILES_DIR = Path(__file__).parent / "test_files" + + +def _make_textract_response(lines=None, page_count=1): + """Helper to build a mock Textract response dict.""" + blocks = [{"BlockType": "PAGE", "Id": f"page-{i}"} for i in range(page_count)] + for text in lines or []: + blocks.append( + { + "BlockType": "LINE", + "Id": f"line-{len(blocks)}", + "Text": text, + "Confidence": 99.5, + } + ) + return {"Blocks": blocks, "ResponseMetadata": {"HTTPStatusCode": 200}} + + +class TestAmazonTextractConverterInit: + def test_init_default(self): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake_id"), + aws_secret_access_key=Secret.from_token("fake_secret"), + aws_region_name=Secret.from_token("us-east-1"), + ) + + assert converter.feature_types is None + assert converter.store_full_path is False + assert converter.boto3_config is None + + def test_init_custom_params(self): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake_id"), + aws_secret_access_key=Secret.from_token("fake_secret"), + aws_region_name=Secret.from_token("eu-west-1"), + feature_types=["TABLES", "FORMS"], + store_full_path=True, + boto3_config={"connect_timeout": 10}, + ) + + assert converter.feature_types == ["TABLES", "FORMS"] + assert converter.store_full_path is True + assert converter.boto3_config == {"connect_timeout": 10} + + def test_init_invalid_feature_types(self): + with pytest.raises(ValueError, match="Invalid feature_types"): + AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake"), + aws_secret_access_key=Secret.from_token("fake"), + feature_types=["INVALID_TYPE"], + ) + + def test_init_all_valid_feature_types(self): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake"), + aws_secret_access_key=Secret.from_token("fake"), + feature_types=["TABLES", "FORMS", "SIGNATURES", "LAYOUT"], + ) + assert len(converter.feature_types) == 4 + + +class TestAmazonTextractConverterSerialization: + def test_to_dict(self): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_env_var("AWS_ACCESS_KEY_ID"), + aws_secret_access_key=Secret.from_env_var("AWS_SECRET_ACCESS_KEY"), + aws_session_token=Secret.from_env_var("AWS_SESSION_TOKEN", strict=False), + aws_region_name=Secret.from_env_var("AWS_DEFAULT_REGION", strict=False), + aws_profile_name=Secret.from_env_var("AWS_PROFILE", strict=False), + feature_types=["TABLES"], + store_full_path=True, + boto3_config={"connect_timeout": 5}, + ) + + data = converter.to_dict() + + expected_type = "haystack_integrations.components.converters.amazon_textract.converter.AmazonTextractConverter" + assert data["type"] == expected_type + assert data["init_parameters"]["feature_types"] == ["TABLES"] + assert data["init_parameters"]["store_full_path"] is True + assert data["init_parameters"]["boto3_config"] == {"connect_timeout": 5} + assert data["init_parameters"]["aws_access_key_id"] == { + "type": "env_var", + "env_vars": ["AWS_ACCESS_KEY_ID"], + "strict": True, + } + + def test_to_dict_default_params(self): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_env_var("AWS_ACCESS_KEY_ID", strict=False), + aws_secret_access_key=Secret.from_env_var("AWS_SECRET_ACCESS_KEY", strict=False), + ) + + data = converter.to_dict() + + assert data["init_parameters"]["feature_types"] is None + assert data["init_parameters"]["store_full_path"] is False + assert data["init_parameters"]["boto3_config"] is None + + def test_from_dict(self): + expected_type = "haystack_integrations.components.converters.amazon_textract.converter.AmazonTextractConverter" + data = { + "type": expected_type, + "init_parameters": { + "aws_access_key_id": {"type": "env_var", "env_vars": ["AWS_ACCESS_KEY_ID"], "strict": False}, + "aws_secret_access_key": {"type": "env_var", "env_vars": ["AWS_SECRET_ACCESS_KEY"], "strict": False}, + "aws_session_token": {"type": "env_var", "env_vars": ["AWS_SESSION_TOKEN"], "strict": False}, + "aws_region_name": {"type": "env_var", "env_vars": ["AWS_DEFAULT_REGION"], "strict": False}, + "aws_profile_name": {"type": "env_var", "env_vars": ["AWS_PROFILE"], "strict": False}, + "feature_types": ["TABLES", "FORMS"], + "store_full_path": False, + "boto3_config": None, + }, + } + + converter = AmazonTextractConverter.from_dict(data) + + assert converter.feature_types == ["TABLES", "FORMS"] + assert converter.store_full_path is False + assert converter.boto3_config is None + + def test_from_dict_roundtrip(self): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_env_var("AWS_ACCESS_KEY_ID", strict=False), + aws_secret_access_key=Secret.from_env_var("AWS_SECRET_ACCESS_KEY", strict=False), + feature_types=["FORMS"], + store_full_path=True, + ) + + data = converter.to_dict() + restored = AmazonTextractConverter.from_dict(data) + + assert restored.feature_types == converter.feature_types + assert restored.store_full_path == converter.store_full_path + assert restored.boto3_config == converter.boto3_config + + +class TestAmazonTextractConverterWarmUp: + @patch("haystack_integrations.components.converters.amazon_textract.converter.boto3.Session") + def test_warm_up_creates_client(self, mock_session_cls): + mock_session = MagicMock() + mock_client = MagicMock() + mock_session.client.return_value = mock_client + mock_session_cls.return_value = mock_session + + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake_id"), + aws_secret_access_key=Secret.from_token("fake_secret"), + aws_region_name=Secret.from_token("us-east-1"), + ) + converter.warm_up() + + mock_session_cls.assert_called_once() + mock_session.client.assert_called_once() + call_args = mock_session.client.call_args + assert call_args[0][0] == "textract" + assert converter._client is mock_client + + @patch("haystack_integrations.components.converters.amazon_textract.converter.boto3.Session") + def test_warm_up_idempotent(self, mock_session_cls): + mock_session = MagicMock() + mock_session.client.return_value = MagicMock() + mock_session_cls.return_value = mock_session + + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake"), + aws_secret_access_key=Secret.from_token("fake"), + ) + converter.warm_up() + converter.warm_up() + + mock_session_cls.assert_called_once() + + @patch( + "haystack_integrations.components.converters.amazon_textract.converter.boto3.Session", + side_effect=BotoCoreError(), + ) + def test_warm_up_configuration_error(self, _mock_session_cls): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake"), + aws_secret_access_key=Secret.from_token("fake"), + ) + with pytest.raises(AmazonTextractConfigurationError, match="Could not connect to AWS Textract"): + converter.warm_up() + + +class TestAmazonTextractConverterRun: + def _make_converter_with_mock_client(self, feature_types=None, store_full_path=False): + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake"), + aws_secret_access_key=Secret.from_token("fake"), + aws_region_name=Secret.from_token("us-east-1"), + feature_types=feature_types, + store_full_path=store_full_path, + ) + converter._client = MagicMock() + return converter + + def test_run_detect_text(self, tmp_path): + converter = self._make_converter_with_mock_client() + response = _make_textract_response(lines=["Hello World", "Second line"]) + converter._client.detect_document_text.return_value = response + + test_file = tmp_path / "test.png" + test_file.write_bytes(b"fake image bytes") + + result = converter.run(sources=[test_file]) + + assert len(result["documents"]) == 1 + assert result["documents"][0].content == "Hello World\nSecond line" + assert result["documents"][0].meta["page_count"] == 1 + assert len(result["raw_textract_response"]) == 1 + converter._client.detect_document_text.assert_called_once() + + def test_run_analyze_document(self, tmp_path): + converter = self._make_converter_with_mock_client(feature_types=["TABLES", "FORMS"]) + response = _make_textract_response(lines=["Name: John", "Age: 30"]) + converter._client.analyze_document.return_value = response + + test_file = tmp_path / "form.png" + test_file.write_bytes(b"fake image bytes") + + result = converter.run(sources=[test_file]) + + assert len(result["documents"]) == 1 + assert result["documents"][0].content == "Name: John\nAge: 30" + converter._client.analyze_document.assert_called_once() + call_kwargs = converter._client.analyze_document.call_args[1] + assert call_kwargs["FeatureTypes"] == ["TABLES", "FORMS"] + + def test_run_with_metadata(self, tmp_path): + converter = self._make_converter_with_mock_client() + converter._client.detect_document_text.return_value = _make_textract_response(lines=["text"]) + + test_file = tmp_path / "doc.png" + test_file.write_bytes(b"bytes") + + result = converter.run( + sources=[test_file], + meta={"custom_key": "custom_value"}, + ) + + doc = result["documents"][0] + assert doc.meta["custom_key"] == "custom_value" + assert doc.meta["page_count"] == 1 + + def test_run_with_bytestream(self): + converter = self._make_converter_with_mock_client() + converter._client.detect_document_text.return_value = _make_textract_response(lines=["from bytes"]) + + bs = ByteStream(data=b"fake image", meta={"file_path": "/some/path/image.png"}) + result = converter.run(sources=[bs]) + + assert len(result["documents"]) == 1 + assert result["documents"][0].content == "from bytes" + assert result["documents"][0].meta["file_path"] == "image.png" + + def test_run_store_full_path(self, tmp_path): + converter = self._make_converter_with_mock_client(store_full_path=True) + converter._client.detect_document_text.return_value = _make_textract_response(lines=["text"]) + + test_file = tmp_path / "doc.png" + test_file.write_bytes(b"bytes") + + result = converter.run(sources=[test_file]) + + doc = result["documents"][0] + assert doc.meta["file_path"] == str(test_file) + + def test_run_store_basename_only(self, tmp_path): + converter = self._make_converter_with_mock_client(store_full_path=False) + converter._client.detect_document_text.return_value = _make_textract_response(lines=["text"]) + + test_file = tmp_path / "doc.png" + test_file.write_bytes(b"bytes") + + result = converter.run(sources=[test_file]) + + doc = result["documents"][0] + assert doc.meta["file_path"] == "doc.png" + + def test_run_multiple_sources(self, tmp_path): + converter = self._make_converter_with_mock_client() + converter._client.detect_document_text.side_effect = [ + _make_textract_response(lines=["First doc"]), + _make_textract_response(lines=["Second doc"]), + ] + + file1 = tmp_path / "a.png" + file1.write_bytes(b"bytes1") + file2 = tmp_path / "b.png" + file2.write_bytes(b"bytes2") + + result = converter.run(sources=[file1, file2]) + + assert len(result["documents"]) == 2 + assert result["documents"][0].content == "First doc" + assert result["documents"][1].content == "Second doc" + assert len(result["raw_textract_response"]) == 2 + + def test_run_multiple_sources_with_per_source_metadata(self, tmp_path): + converter = self._make_converter_with_mock_client() + converter._client.detect_document_text.side_effect = [ + _make_textract_response(lines=["A"]), + _make_textract_response(lines=["B"]), + ] + + file1 = tmp_path / "a.png" + file1.write_bytes(b"bytes1") + file2 = tmp_path / "b.png" + file2.write_bytes(b"bytes2") + + result = converter.run( + sources=[file1, file2], + meta=[{"source": "first"}, {"source": "second"}], + ) + + assert result["documents"][0].meta["source"] == "first" + assert result["documents"][1].meta["source"] == "second" + + def test_run_skips_failed_sources(self, tmp_path): + converter = self._make_converter_with_mock_client() + error_response = {"Error": {"Code": "InvalidParameterException", "Message": "bad image"}} + converter._client.detect_document_text.side_effect = ClientError(error_response, "DetectDocumentText") + + test_file = tmp_path / "broken_image.png" + test_file.write_bytes(b"bad bytes") + + result = converter.run(sources=[test_file]) + + assert len(result["documents"]) == 0 + assert len(result["raw_textract_response"]) == 0 + + def test_run_broken_image_mixed_with_valid(self, tmp_path): + """A broken image among valid sources should be skipped while valid ones succeed.""" + converter = self._make_converter_with_mock_client() + + error_response = {"Error": {"Code": "UnsupportedDocumentException", "Message": "unsupported format"}} + valid_response = _make_textract_response(lines=["Valid text"]) + + converter._client.detect_document_text.side_effect = [ + ClientError(error_response, "DetectDocumentText"), + valid_response, + ] + + valid_file = tmp_path / "good.png" + valid_file.write_bytes(b"fake valid image") + broken_image = TEST_FILES_DIR / "broken_image.png" + + result = converter.run(sources=[broken_image, valid_file]) + + assert len(result["documents"]) == 1 + assert result["documents"][0].content == "Valid text" + assert len(result["raw_textract_response"]) == 1 + + def test_run_skips_unreadable_source(self): + converter = self._make_converter_with_mock_client() + + result = converter.run(sources=["/nonexistent/path/file.png"]) + + assert len(result["documents"]) == 0 + assert len(result["raw_textract_response"]) == 0 + + def test_run_empty_response(self, tmp_path): + converter = self._make_converter_with_mock_client() + converter._client.detect_document_text.return_value = {"Blocks": [], "ResponseMetadata": {}} + + test_file = tmp_path / "empty.png" + test_file.write_bytes(b"bytes") + + result = converter.run(sources=[test_file]) + + assert len(result["documents"]) == 1 + assert result["documents"][0].content == "" + assert result["documents"][0].meta["page_count"] == 0 + + def test_run_multi_page_response(self, tmp_path): + converter = self._make_converter_with_mock_client() + response = _make_textract_response(lines=["Page 1 text", "Page 2 text"], page_count=2) + converter._client.detect_document_text.return_value = response + + test_file = tmp_path / "multipage.pdf" + test_file.write_bytes(b"fake pdf bytes") + + result = converter.run(sources=[test_file]) + + assert result["documents"][0].meta["page_count"] == 2 + assert "Page 1 text" in result["documents"][0].content + assert "Page 2 text" in result["documents"][0].content + + def test_run_auto_warm_up(self, tmp_path): + """Verify that run() calls warm_up() if client is not initialized.""" + converter = AmazonTextractConverter( + aws_access_key_id=Secret.from_token("fake"), + aws_secret_access_key=Secret.from_token("fake"), + aws_region_name=Secret.from_token("us-east-1"), + ) + + mock_client = MagicMock() + mock_client.detect_document_text.return_value = _make_textract_response(lines=["text"]) + + with patch("haystack_integrations.components.converters.amazon_textract.converter.boto3.Session") as mock_sess: + mock_sess.return_value.client.return_value = mock_client + + test_file = tmp_path / "test.png" + test_file.write_bytes(b"bytes") + + result = converter.run(sources=[test_file]) + + assert len(result["documents"]) == 1 + mock_sess.assert_called_once() + + def test_run_with_empty_sources(self): + converter = self._make_converter_with_mock_client() + result = converter.run(sources=[]) + + assert result["documents"] == [] + assert result["raw_textract_response"] == [] + + def test_run_with_queries_only(self, tmp_path): + """Queries alone should trigger AnalyzeDocument with QUERIES feature type.""" + converter = self._make_converter_with_mock_client() + response = _make_textract_response(lines=["John Doe"]) + converter._client.analyze_document.return_value = response + + test_file = tmp_path / "form.png" + test_file.write_bytes(b"fake image bytes") + + result = converter.run( + sources=[test_file], + queries=["What is the patient name?"], + ) + + assert len(result["documents"]) == 1 + converter._client.analyze_document.assert_called_once() + call_kwargs = converter._client.analyze_document.call_args[1] + assert "QUERIES" in call_kwargs["FeatureTypes"] + assert call_kwargs["QueriesConfig"] == { + "Queries": [{"Text": "What is the patient name?"}], + } + converter._client.detect_document_text.assert_not_called() + + def test_run_with_queries_and_feature_types(self, tmp_path): + """Queries combined with existing feature_types should merge correctly.""" + converter = self._make_converter_with_mock_client(feature_types=["TABLES"]) + response = _make_textract_response(lines=["Total: $100"]) + converter._client.analyze_document.return_value = response + + test_file = tmp_path / "invoice.png" + test_file.write_bytes(b"fake image bytes") + + result = converter.run( + sources=[test_file], + queries=["What is the total?", "What is the due date?"], + ) + + assert len(result["documents"]) == 1 + call_kwargs = converter._client.analyze_document.call_args[1] + assert "TABLES" in call_kwargs["FeatureTypes"] + assert "QUERIES" in call_kwargs["FeatureTypes"] + assert call_kwargs["QueriesConfig"] == { + "Queries": [ + {"Text": "What is the total?"}, + {"Text": "What is the due date?"}, + ], + } + + @pytest.mark.parametrize("queries", [None, []]) + def test_run_no_queries_uses_detect(self, tmp_path, queries): + """None and empty list for queries should both use detect_document_text.""" + converter = self._make_converter_with_mock_client() + converter._client.detect_document_text.return_value = _make_textract_response(lines=["text"]) + + test_file = tmp_path / "doc.png" + test_file.write_bytes(b"bytes") + + converter.run(sources=[test_file], queries=queries) + + converter._client.detect_document_text.assert_called_once() + converter._client.analyze_document.assert_not_called() + + def test_run_queries_does_not_mutate_feature_types(self, tmp_path): + """Passing queries at runtime should not modify the init feature_types.""" + converter = self._make_converter_with_mock_client(feature_types=["TABLES"]) + converter._client.analyze_document.return_value = _make_textract_response(lines=["text"]) + + test_file = tmp_path / "doc.png" + test_file.write_bytes(b"bytes") + + converter.run(sources=[test_file], queries=["What?"]) + + assert converter.feature_types == ["TABLES"] + assert "QUERIES" not in converter.feature_types diff --git a/integrations/amazon_textract/tests/test_amazon_textract_converter_integration.py b/integrations/amazon_textract/tests/test_amazon_textract_converter_integration.py new file mode 100644 index 0000000000..bbe79e9e04 --- /dev/null +++ b/integrations/amazon_textract/tests/test_amazon_textract_converter_integration.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from pathlib import Path + +import pytest +from haystack.dataclasses import ByteStream + +from haystack_integrations.components.converters.amazon_textract import AmazonTextractConverter + +SKIP_REASON_NO_CREDENTIALS = "AWS credentials not available" +SKIP_REASON_NO_REGION = "AWS region not configured" + + +@pytest.mark.integration +class TestAmazonTextractConverterIntegration: + @pytest.fixture + def test_files_path(self): + return Path(__file__).parent / "test_files" + + @pytest.fixture + def converter(self): + return AmazonTextractConverter() + + @pytest.mark.skipif(not os.environ.get("AWS_ACCESS_KEY_ID"), reason=SKIP_REASON_NO_CREDENTIALS) + @pytest.mark.skipif(not os.environ.get("AWS_DEFAULT_REGION"), reason=SKIP_REASON_NO_REGION) + def test_run_detect_text_from_image(self, converter, test_files_path): + """Integration test: detect text from an image file.""" + image_path = test_files_path / "sample_text.png" + if not image_path.exists(): + pytest.skip("Test image file not available") + + results = converter.run(sources=[image_path]) + + assert "documents" in results + assert len(results["documents"]) == 1 + assert len(results["documents"][0].content) > 0 + assert results["documents"][0].meta["page_count"] >= 1 + assert "raw_textract_response" in results + assert len(results["raw_textract_response"]) == 1 + + @pytest.mark.skipif(not os.environ.get("AWS_ACCESS_KEY_ID"), reason=SKIP_REASON_NO_CREDENTIALS) + @pytest.mark.skipif(not os.environ.get("AWS_DEFAULT_REGION"), reason=SKIP_REASON_NO_REGION) + def test_run_analyze_document_with_tables(self, test_files_path): + """Integration test: analyze document with table detection.""" + image_path = test_files_path / "sample_text.png" + if not image_path.exists(): + pytest.skip("Test image file not available") + + converter = AmazonTextractConverter(feature_types=["TABLES"]) + results = converter.run(sources=[image_path]) + + assert "documents" in results + assert len(results["documents"]) == 1 + assert len(results["documents"][0].content) > 0 + + @pytest.mark.skipif(not os.environ.get("AWS_ACCESS_KEY_ID"), reason=SKIP_REASON_NO_CREDENTIALS) + @pytest.mark.skipif(not os.environ.get("AWS_DEFAULT_REGION"), reason=SKIP_REASON_NO_REGION) + def test_run_with_metadata(self, converter, test_files_path): + """Integration test: verify metadata handling.""" + image_path = test_files_path / "sample_text.png" + if not image_path.exists(): + pytest.skip("Test image file not available") + + results = converter.run( + sources=[image_path], + meta={"custom_key": "custom_value"}, + ) + + doc = results["documents"][0] + assert doc.meta["custom_key"] == "custom_value" + assert doc.meta["file_path"] == "sample_text.png" + + @pytest.mark.skipif(not os.environ.get("AWS_ACCESS_KEY_ID"), reason=SKIP_REASON_NO_CREDENTIALS) + @pytest.mark.skipif(not os.environ.get("AWS_DEFAULT_REGION"), reason=SKIP_REASON_NO_REGION) + def test_run_with_bytestream(self, converter, test_files_path): + """Integration test: convert from ByteStream.""" + image_path = test_files_path / "sample_text.png" + if not image_path.exists(): + pytest.skip("Test image file not available") + + data = image_path.read_bytes() + bs = ByteStream(data=data, meta={"file_path": str(image_path)}) + results = converter.run(sources=[bs]) + + assert len(results["documents"]) == 1 + assert len(results["documents"][0].content) > 0 diff --git a/integrations/amazon_textract/tests/test_files/broken_image.png b/integrations/amazon_textract/tests/test_files/broken_image.png new file mode 100644 index 0000000000..302caf170f Binary files /dev/null and b/integrations/amazon_textract/tests/test_files/broken_image.png differ diff --git a/integrations/amazon_textract/tests/test_files/sample_text.png b/integrations/amazon_textract/tests/test_files/sample_text.png new file mode 100644 index 0000000000..25d202e024 Binary files /dev/null and b/integrations/amazon_textract/tests/test_files/sample_text.png differ